instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | protected SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
SavedRequestAwareAuthenticationSuccessHandler successHandler = new SavedRequestAwareAuthenticationSuccessHandler();
successHandler.setTargetUrlParameter("redirectTo");
successHandler.setDefaultTargetUrl(this.adminContextPath + "/");
http.authorizeHttpRequests((authorizeRequests) -> authorizeRequests
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/assets/**"))
.permitAll()
.requestMatchers(PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/login"))
.permitAll()
.anyRequest()
.authenticated())
.formLogin((formLogin) -> formLogin.loginPage(this.adminContextPath + "/login")
.successHandler(successHandler))
.logout((logout) -> logout.logoutUrl(this.adminContextPath + "/logout")) | .httpBasic(Customizer.withDefaults())
.csrf((csrf) -> csrf.csrfTokenRepository(CookieCsrfTokenRepository.withHttpOnlyFalse())
.ignoringRequestMatchers(
PathPatternRequestMatcher.withDefaults()
.matcher(POST, this.adminContextPath + "/instances"),
PathPatternRequestMatcher.withDefaults()
.matcher(DELETE, this.adminContextPath + "/instances/*"),
PathPatternRequestMatcher.withDefaults().matcher(this.adminContextPath + "/actuator/**")));
return http.build();
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-consul\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminConsulApplication.java | 2 |
请完成以下Java代码 | public void updateActionButtonUI()
{
if (isDisposed())
{
return;
}
final JComponent textComponent = getTextComponent();
final VEditorActionButton actionButton = getActionButton();
if (textComponent == null || actionButton == null)
{
dispose();
return;
}
updateActionButtonUI_PreferredSize(actionButton, textComponent);
updateActionButtonUI_Background(actionButton, textComponent);
}
private static void updateActionButtonUI_PreferredSize(final VEditorActionButton actionButton, final JComponent textComponent)
{
final Dimension textCompSize = textComponent.getPreferredSize();
final int textCompHeight = textCompSize.height;
final Dimension buttonSize = new Dimension(textCompHeight, textCompHeight);
actionButton.setPreferredSize(buttonSize);
}
private static void updateActionButtonUI_Background(final VEditorActionButton actionButton, final JComponent textComponent)
{
final Color textCompBackground = textComponent.getBackground();
actionButton.setBackground(textCompBackground);
}
@Override
public void propertyChange(final PropertyChangeEvent evt) | {
if (isDisposed())
{
return;
}
final JComponent textComponent = (JComponent)evt.getSource();
if (textComponent == null)
{
return; // shall not happen
}
final VEditorActionButton actionButton = getActionButton();
if (actionButton == null)
{
dispose();
return;
}
final String propertyName = evt.getPropertyName();
if (PROPERTY_PreferredSize.equals(propertyName))
{
updateActionButtonUI_PreferredSize(actionButton, textComponent);
}
else if (PROPERTY_Background.equals(propertyName))
{
updateActionButtonUI_Background(actionButton, textComponent);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VEditorActionButton.java | 1 |
请完成以下Java代码 | public CmmnTaskService getCmmnTaskService() {
return cmmnTaskService;
}
public void setCmmnTaskService(CmmnTaskService cmmnTaskService) {
this.cmmnTaskService = cmmnTaskService;
}
@Override
public CmmnManagementService getCmmnManagementService() {
return cmmnManagementService;
}
public void setCmmnManagementService(CmmnManagementService cmmnManagementService) {
this.cmmnManagementService = cmmnManagementService;
}
@Override
public CmmnRepositoryService getCmmnRepositoryService() {
return cmmnRepositoryService;
}
public void setCmmnRepositoryService(CmmnRepositoryService cmmnRepositoryService) {
this.cmmnRepositoryService = cmmnRepositoryService;
}
@Override
public CmmnHistoryService getCmmnHistoryService() { | return cmmnHistoryService;
}
public void setCmmnHistoryService(CmmnHistoryService cmmnHistoryService) {
this.cmmnHistoryService = cmmnHistoryService;
}
@Override
public CmmnMigrationService getCmmnMigrationService() {
return cmmnMigrationService;
}
public void setCmmnMigrationService(CmmnMigrationService cmmnMigrationService) {
this.cmmnMigrationService = cmmnMigrationService;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnEngineImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected static int toSeconds(@Nullable Duration duration) {
return duration != null ? Long.valueOf(duration.getSeconds()).intValue()
: GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS;
}
protected static @NonNull String toSecondsAsString(@Nullable Duration duration) {
return String.valueOf(toSeconds(duration));
}
protected static boolean isNotSet(ConfigurableEnvironment environment, String propertyName) {
return !isSet(environment, propertyName);
}
protected static boolean isSet(ConfigurableEnvironment environment, String propertyName) {
return environment.containsProperty(propertyName)
&& StringUtils.hasText(environment.getProperty(propertyName)); | }
protected static class SpringSessionStoreTypeCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
String springSessionStoreTypeValue =
context.getEnvironment().getProperty(SPRING_SESSION_STORE_TYPE_PROPERTY);
return !StringUtils.hasText(springSessionStoreTypeValue)
|| SPRING_SESSION_STORE_TYPES.contains(springSessionStoreTypeValue.trim().toLowerCase());
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\SpringSessionAutoConfiguration.java | 2 |
请完成以下Java代码 | public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
String mobile = obtainMobile(request);
if (mobile == null) {
mobile = "";
}
mobile = mobile.trim();
SmsAuthenticationToken authRequest = new SmsAuthenticationToken(mobile);
setDetails(request, authRequest);
return this.getAuthenticationManager().authenticate(authRequest);
}
protected String obtainMobile(HttpServletRequest request) {
return request.getParameter(mobileParameter);
}
protected void setDetails(HttpServletRequest request,
SmsAuthenticationToken authRequest) { | authRequest.setDetails(authenticationDetailsSource.buildDetails(request));
}
public void setMobileParameter(String mobileParameter) {
Assert.hasText(mobileParameter, "mobile parameter must not be empty or null");
this.mobileParameter = mobileParameter;
}
public void setPostOnly(boolean postOnly) {
this.postOnly = postOnly;
}
public final String getMobileParameter() {
return mobileParameter;
}
} | repos\SpringAll-master\38.Spring-Security-SmsCode\src\main\java\cc\mrbird\validate\smscode\SmsAuthenticationFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public AppDeploymentBuilder addString(String resourceName, String text) {
if (text == null) {
throw new FlowableException("text is null");
}
AppResourceEntity resource = resourceEntityManager.create();
resource.setName(resourceName);
resource.setBytes(text.getBytes(StandardCharsets.UTF_8));
deployment.addResource(resource);
return this;
}
@Override
public AppDeploymentBuilder addBytes(String resourceName, byte[] bytes) {
if (bytes == null) {
throw new FlowableException("bytes array is null");
}
AppResourceEntity resource = resourceEntityManager.create();
resource.setName(resourceName);
resource.setBytes(bytes);
deployment.addResource(resource);
return this;
}
@Override
public AppDeploymentBuilder addZipInputStream(ZipInputStream zipInputStream) {
try {
ZipEntry entry = zipInputStream.getNextEntry();
while (entry != null) {
if (!entry.isDirectory()) {
String entryName = entry.getName();
byte[] bytes = IoUtil.readInputStream(zipInputStream, entryName);
AppResourceEntity resource = resourceEntityManager.create();
resource.setName(entryName);
resource.setBytes(bytes);
deployment.addResource(resource);
}
entry = zipInputStream.getNextEntry();
}
} catch (Exception e) {
throw new FlowableException("problem reading zip input stream", e);
}
return this;
}
@Override
public AppDeploymentBuilder name(String name) {
deployment.setName(name);
return this;
}
@Override
public AppDeploymentBuilder category(String category) {
deployment.setCategory(category);
return this;
}
@Override
public AppDeploymentBuilder key(String key) {
deployment.setKey(key);
return this;
}
@Override | public AppDeploymentBuilder disableSchemaValidation() {
this.isXsdValidationEnabled = false;
return this;
}
@Override
public AppDeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
@Override
public AppDeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true;
return this;
}
@Override
public AppDeployment deploy() {
return repositoryService.deploy(this);
}
public AppDeploymentEntity getDeployment() {
return deployment;
}
public boolean isXsdValidationEnabled() {
return isXsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\repository\AppDeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public BigDecimal getUnit() {
return unit;
}
/**
* Sets the value of the unit property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setUnit(BigDecimal value) {
this.unit = value;
}
/**
* Gets the value of the faceAmt property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getFaceAmt() {
return faceAmt;
}
/**
* Sets the value of the faceAmt property.
*
* @param value
* allowed object is | * {@link BigDecimal }
*
*/
public void setFaceAmt(BigDecimal value) {
this.faceAmt = value;
}
/**
* Gets the value of the amtsdVal property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getAmtsdVal() {
return amtsdVal;
}
/**
* Sets the value of the amtsdVal property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setAmtsdVal(BigDecimal value) {
this.amtsdVal = 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\FinancialInstrumentQuantityChoice.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static final class ClientLoginConfig extends Configuration {
private final String keyTabLocation;
private final String userPrincipal;
private final String password;
private final Map<String, Object> loginOptions;
private ClientLoginConfig(String keyTabLocation, String userPrincipal, String password,
Map<String, Object> loginOptions) {
super();
this.keyTabLocation = keyTabLocation;
this.userPrincipal = userPrincipal;
this.password = password;
this.loginOptions = loginOptions;
}
@Override
public AppConfigurationEntry[] getAppConfigurationEntry(String name) {
Map<String, Object> options = new HashMap<String, Object>();
// if we don't have keytab or principal only option is to rely on
// credentials cache.
if (!StringUtils.hasText(this.keyTabLocation) || !StringUtils.hasText(this.userPrincipal)) {
// cache
options.put("useTicketCache", "true");
}
else {
// keytab
options.put("useKeyTab", "true");
options.put("keyTab", this.keyTabLocation);
options.put("principal", this.userPrincipal);
options.put("storeKey", "true");
}
options.put("doNotPrompt", Boolean.toString(this.password == null));
options.put("isInitiator", "true");
if (this.loginOptions != null) {
options.putAll(this.loginOptions);
}
return new AppConfigurationEntry[] {
new AppConfigurationEntry("com.sun.security.auth.module.Krb5LoginModule",
AppConfigurationEntry.LoginModuleControlFlag.REQUIRED, options) };
}
}
private static class NullCredentials implements Credentials {
@Override
public Principal getUserPrincipal() {
return null;
}
@Override
public char[] getPassword() {
return null;
} | }
private static final class CallbackHandlerImpl implements CallbackHandler {
private final String userPrincipal;
private final String password;
private CallbackHandlerImpl(String userPrincipal, String password) {
super();
this.userPrincipal = userPrincipal;
this.password = password;
}
@Override
public void handle(Callback[] callbacks) throws IOException, UnsupportedCallbackException {
for (Callback callback : callbacks) {
if (callback instanceof NameCallback) {
NameCallback nc = (NameCallback) callback;
nc.setName(this.userPrincipal);
}
else if (callback instanceof PasswordCallback) {
PasswordCallback pc = (PasswordCallback) callback;
pc.setPassword(this.password.toCharArray());
}
else {
throw new UnsupportedCallbackException(callback, "Unknown Callback");
}
}
}
}
} | repos\spring-security-main\kerberos\kerberos-client\src\main\java\org\springframework\security\kerberos\client\KerberosRestTemplate.java | 2 |
请完成以下Java代码 | public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
/**
* {@inheritDoc}
*/
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
public void setPointcut(Pointcut pointcut) {
this.pointcut = pointcut;
}
@Override
public Advice getAdvice() {
return this;
}
@Override
public boolean isPerInstance() {
return true;
}
static final class MethodReturnTypePointcut extends StaticMethodMatcherPointcut { | private final Predicate<Class<?>> returnTypeMatches;
MethodReturnTypePointcut(Predicate<Class<?>> returnTypeMatches) {
this.returnTypeMatches = returnTypeMatches;
}
@Override
public boolean matches(Method method, Class<?> targetClass) {
return this.returnTypeMatches.test(method.getReturnType());
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\AuthorizeReturnObjectMethodInterceptor.java | 1 |
请完成以下Java代码 | public static Constructor<?> makeAccessible(@NonNull Constructor<?> constructor) {
ReflectionUtils.makeAccessible(constructor);
return constructor;
}
/**
* Makes the {@link Field} accessible.
*
* @param field {@link Field} to make accessible; must not be {@literal null}.
* @return the given {@link Field}.
* @see java.lang.reflect.Field
*/
public static Field makeAccessible(Field field) {
ReflectionUtils.makeAccessible(field);
return field;
}
/**
* Makes the {@link Method} accessible.
*
* @param method {@link Method} to make accessible; must not be {@literal null}.
* @return the given {@link Method}.
* @see java.lang.reflect.Method
*/
public static Method makeAccessible(Method method) {
ReflectionUtils.makeAccessible(method);
return method;
}
/**
* Returns the given {@link Object value} or throws an {@link IllegalArgumentException}
* if {@link Object value} is {@literal null}.
*
* @param <T> {@link Class type} of the {@link Object value}.
* @param value {@link Object} to return.
* @return the {@link Object value} or throw an {@link IllegalArgumentException}
* if {@link Object value} is {@literal null}.
* @see #returnValueThrowOnNull(Object, RuntimeException)
*/
public static <T> T returnValueThrowOnNull(T value) {
return returnValueThrowOnNull(value, newIllegalArgumentException("Value must not be null"));
}
/** | * Returns the given {@link Object value} or throws the given {@link RuntimeException}
* if {@link Object value} is {@literal null}.
*
* @param <T> {@link Class type} of the {@link Object value}.
* @param value {@link Object} to return.
* @param exception {@link RuntimeException} to throw if {@link Object value} is {@literal null}.
* @return the {@link Object value} or throw the given {@link RuntimeException}
* if {@link Object value} is {@literal null}.
*/
public static <T> T returnValueThrowOnNull(T value, RuntimeException exception) {
if (value == null) {
throw exception;
}
return value;
}
/**
* Resolves the {@link Object invocation target} for the given {@link Method}.
*
* If the {@link Method} is {@link Modifier#STATIC} then {@literal null} is returned,
* otherwise {@link Object target} will be returned.
*
* @param <T> {@link Class type} of the {@link Object target}.
* @param target {@link Object} on which the {@link Method} will be invoked.
* @param method {@link Method} to invoke on the {@link Object}.
* @return the resolved {@link Object invocation method}.
* @see java.lang.Object
* @see java.lang.reflect.Method
*/
public static <T> T resolveInvocationTarget(T target, Method method) {
return Modifier.isStatic(method.getModifiers()) ? null : target;
}
@FunctionalInterface
public interface ExceptionThrowingOperation<T> {
T run() throws Exception;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\core\util\ObjectUtils.java | 1 |
请完成以下Java代码 | public void setIsPrinted (final boolean IsPrinted)
{
set_Value (COLUMNNAME_IsPrinted, IsPrinted);
}
@Override
public boolean isPrinted()
{
return get_ValueAsBoolean(COLUMNNAME_IsPrinted);
}
@Override
public void setLine (final int Line)
{
set_Value (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setM_Product_Category_ID (final int M_Product_Category_ID)
{
if (M_Product_Category_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_ID, M_Product_Category_ID);
}
@Override
public int getM_Product_Category_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPlannedAmt (final BigDecimal PlannedAmt)
{
set_Value (COLUMNNAME_PlannedAmt, PlannedAmt);
} | @Override
public BigDecimal getPlannedAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPlannedMarginAmt (final BigDecimal PlannedMarginAmt)
{
set_Value (COLUMNNAME_PlannedMarginAmt, PlannedMarginAmt);
}
@Override
public BigDecimal getPlannedMarginAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedMarginAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPlannedPrice (final BigDecimal PlannedPrice)
{
set_Value (COLUMNNAME_PlannedPrice, PlannedPrice);
}
@Override
public BigDecimal getPlannedPrice()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedPrice);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPlannedQty (final BigDecimal PlannedQty)
{
set_Value (COLUMNNAME_PlannedQty, PlannedQty);
}
@Override
public BigDecimal getPlannedQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PlannedQty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_ProjectLine.java | 1 |
请完成以下Java代码 | public class RabbitStreamMessageSenderContext extends SenderContext<Message> {
private final String beanName;
private final String destination;
@SuppressWarnings("this-escape")
public RabbitStreamMessageSenderContext(Message message, String beanName, String destination) {
super((carrier, key, value) -> {
Map<String, Object> props = message.getApplicationProperties();
if (props != null) {
props.put(key, value);
}
});
setCarrier(message);
this.beanName = beanName;
this.destination = destination;
setRemoteServiceName("RabbitMQ Stream"); | }
public String getBeanName() {
return this.beanName;
}
/**
* Return the destination - {@code exchange/routingKey}.
* @return the destination.
*/
public String getDestination() {
return this.destination;
}
} | repos\spring-amqp-main\spring-rabbit-stream\src\main\java\org\springframework\rabbit\stream\micrometer\RabbitStreamMessageSenderContext.java | 1 |
请完成以下Java代码 | public void setOtherClause (String OtherClause)
{
set_Value (COLUMNNAME_OtherClause, OtherClause);
}
/** Get Other SQL Clause.
@return Other SQL Clause
*/
public String getOtherClause ()
{
return (String)get_Value(COLUMNNAME_OtherClause);
}
/** Set Post Processing.
@param PostProcessing
Process SQL after executing the query
*/
public void setPostProcessing (String PostProcessing)
{
set_Value (COLUMNNAME_PostProcessing, PostProcessing);
}
/** Get Post Processing.
@return Process SQL after executing the query
*/
public String getPostProcessing ()
{
return (String)get_Value(COLUMNNAME_PostProcessing);
}
/** Set Pre Processing.
@param PreProcessing
Process SQL before executing the query
*/
public void setPreProcessing (String PreProcessing)
{
set_Value (COLUMNNAME_PreProcessing, PreProcessing);
}
/** Get Pre Processing.
@return Process SQL before executing the query
*/
public String getPreProcessing ()
{
return (String)get_Value(COLUMNNAME_PreProcessing);
}
/** Set Sql SELECT.
@param SelectClause
SQL SELECT clause
*/
public void setSelectClause (String SelectClause)
{
set_Value (COLUMNNAME_SelectClause, SelectClause); | }
/** Get Sql SELECT.
@return SQL SELECT clause
*/
public String getSelectClause ()
{
return (String)get_Value(COLUMNNAME_SelectClause);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertRule.java | 1 |
请完成以下Java代码 | protected static void addTaskSuspensionStateEntryLog(TaskEntity taskEntity, SuspensionState state) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
TaskServiceConfiguration taskServiceConfiguration = processEngineConfiguration.getTaskServiceConfiguration();
if (taskServiceConfiguration.isEnableHistoricTaskLogging()) {
BaseHistoricTaskLogEntryBuilderImpl taskLogEntryBuilder = new BaseHistoricTaskLogEntryBuilderImpl(taskEntity);
ObjectNode data = taskServiceConfiguration.getObjectMapper().createObjectNode();
data.put("previousSuspensionState", taskEntity.getSuspensionState());
data.put("newSuspensionState", state.getStateCode());
taskLogEntryBuilder.timeStamp(taskServiceConfiguration.getClock().getCurrentTime());
taskLogEntryBuilder.userId(Authentication.getAuthenticatedUserId());
taskLogEntryBuilder.data(data.toString());
taskLogEntryBuilder.type(HistoricTaskLogEntryType.USER_TASK_SUSPENSIONSTATE_CHANGED.name());
taskServiceConfiguration.getInternalHistoryTaskManager().recordHistoryUserTaskLog(taskLogEntryBuilder);
}
}
protected static void dispatchStateChangeEvent(Object entity, SuspensionState state) {
CommandContext commandContext = Context.getCommandContext(); | ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
FlowableEventDispatcher eventDispatcher = null;
if (commandContext != null) {
eventDispatcher = processEngineConfiguration.getEventDispatcher();
}
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
FlowableEngineEventType eventType = null;
if (state == SuspensionState.ACTIVE) {
eventType = FlowableEngineEventType.ENTITY_ACTIVATED;
} else {
eventType = FlowableEngineEventType.ENTITY_SUSPENDED;
}
eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(eventType, entity), processEngineConfiguration.getEngineCfgKey());
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\SuspensionStateUtil.java | 1 |
请完成以下Java代码 | private DocTaxesList applyUserChangesAndRecomputeTaxes(@NonNull final Fact fact)
{
final DocTaxesList taxes = getTaxes();
final FactAcctChangesApplier changesApplier = getFactAcctChangesApplier();
// If there are no user changes, we don't have to recompute the taxes,
// accept them as they come from C_InvoiceTax
if (!changesApplier.hasChangesToApply())
{
return taxes;
}
changesApplier.applyUpdatesTo(fact);
final DocTaxUpdater docTaxUpdater = new DocTaxUpdater(services, getAccountProvider(), InvoiceDocBaseType.ofDocBaseType(getDocBaseType()));
docTaxUpdater.collect(fact);
docTaxUpdater.updateDocTaxes(taxes);
return taxes;
}
@Override
public CurrencyConversionContext getCurrencyConversionContext(final AcctSchema ignoredAcctSchema)
{
CurrencyConversionContext invoiceCurrencyConversionCtx = this._invoiceCurrencyConversionCtx;
if (invoiceCurrencyConversionCtx == null)
{
final I_C_Invoice invoice = getModel(I_C_Invoice.class);
invoiceCurrencyConversionCtx = this._invoiceCurrencyConversionCtx = invoiceBL.getCurrencyConversionCtx(invoice);
}
return invoiceCurrencyConversionCtx;
}
@Override
protected void afterPost()
{
postDependingMatchInvsIfNeeded();
}
private void postDependingMatchInvsIfNeeded()
{
if (!services.getSysConfigBooleanValue(SYSCONFIG_PostMatchInvs, DEFAULT_PostMatchInvs))
{
return;
}
final Set<InvoiceAndLineId> invoiceAndLineIds = new HashSet<>();
for (final DocLine_Invoice line : getDocLines())
{
invoiceAndLineIds.add(line.getInvoiceAndLineId());
}
// 08643
// Do nothing in case there are no invoice lines
if (invoiceAndLineIds.isEmpty())
{
return;
}
final Set<MatchInvId> matchInvIds = matchInvoiceService.getIdsProcessedButNotPostedByInvoiceLineIds(invoiceAndLineIds);
postDependingDocuments(I_M_MatchInv.Table_Name, matchInvIds);
} | @Nullable
@Override
protected OrderId getSalesOrderId()
{
final Optional<OrderId> optionalSalesOrderId = CollectionUtils.extractSingleElementOrDefault(
getDocLines(),
docLine -> Optional.ofNullable(docLine.getSalesOrderId()),
Optional.empty());
//noinspection DataFlowIssue
return optionalSalesOrderId.orElse(null);
}
public static void unpostIfNeeded(final I_C_Invoice invoice)
{
if (!invoice.isPosted())
{
return;
}
// Make sure the period is open
final Properties ctx = InterfaceWrapperHelper.getCtx(invoice);
MPeriod.testPeriodOpen(ctx, invoice.getDateAcct(), invoice.getC_DocType_ID(), invoice.getAD_Org_ID());
Services.get(IFactAcctDAO.class).deleteForDocumentModel(invoice);
invoice.setPosted(false);
InterfaceWrapperHelper.save(invoice);
}
} // Doc_Invoice | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_Invoice.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Product {
private int id;
private String name;
private String description;
@Id
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
} | @Column(nullable = false)
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\Product.java | 2 |
请完成以下Java代码 | public java.sql.Timestamp getDunningGrace ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DunningGrace);
}
/** Set Summe Gesamt.
@param GrandTotal
Summe über Alles zu diesem Beleg
*/
@Override
public void setGrandTotal (java.math.BigDecimal GrandTotal)
{
set_Value (COLUMNNAME_GrandTotal, GrandTotal);
}
/** Get Summe Gesamt.
@return Summe über Alles zu diesem Beleg
*/
@Override
public java.math.BigDecimal getGrandTotal ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrandTotal);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set In Dispute.
@param IsInDispute
Document is in dispute
*/
@Override
public void setIsInDispute (boolean IsInDispute)
{
set_Value (COLUMNNAME_IsInDispute, Boolean.valueOf(IsInDispute));
}
/** Get In Dispute.
@return Document is in dispute
*/
@Override
public boolean isInDispute () | {
Object oo = get_Value(COLUMNNAME_IsInDispute);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Offener Betrag.
@param OpenAmt Offener Betrag */
@Override
public void setOpenAmt (java.math.BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Offener Betrag.
@return Offener Betrag */
@Override
public java.math.BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_Dunning_Candidate_Invoice_v1.java | 1 |
请完成以下Java代码 | public String getKey() {
return key;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public void setResources(Map<String, EngineResource> resources) {
this.resources = resources;
}
@Override
public Date getDeploymentTime() {
return deploymentTime;
}
@Override
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
@Override
public boolean isNew() {
return isNew; | }
@Override
public void setNew(boolean isNew) {
this.isNew = isNew;
}
@Override
public String getDerivedFrom() {
return null;
}
@Override
public String getDerivedFromRoot() {
return null;
}
@Override
public String getEngineVersion() {
return null;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "AppDeploymentEntity[id=" + id + ", name=" + name + "]";
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\persistence\entity\AppDeploymentEntityImpl.java | 1 |
请完成以下Java代码 | private void onEvent(final Event event)
{
if (!isEligibleToBeDisplayed(event))
{
return;
}
final NotificationItem notificationItem = toNotificationItem(event);
// Add the notification item component (in EDT)
executeInEDTAfter(0, () -> addNotificationItemNow(notificationItem));
}
private boolean isEligibleToBeDisplayed(final Event event)
{
final int loginUserId = Env.getAD_User_ID(getCtx());
return event.hasRecipient(loginUserId);
}
private NotificationItem toNotificationItem(final Event event)
{
//
// Build summary text
final String summaryTrl = msgBL.getMsg(getCtx(), MSG_Notification_Summary_Default, new Object[] { Adempiere.getName() });
final UserNotification notification = UserNotificationUtils.toUserNotification(event);
//
// Build detail message
final StringBuilder detailBuf = new StringBuilder();
{
// Add plain detail if any
final String detailPlain = notification.getDetailPlain();
if (!Check.isEmpty(detailPlain, true))
{
detailBuf.append(detailPlain.trim());
} | // Translate, parse and add detail (AD_Message).
final String detailADMessage = notification.getDetailADMessage();
if (!Check.isEmpty(detailADMessage, true))
{
final String detailTrl = msgBL.getMsg(getCtx(), detailADMessage);
final String detailTrlParsed = EventHtmlMessageFormat.newInstance()
.setArguments(notification.getDetailADMessageParams())
.format(detailTrl);
if (!Check.isEmpty(detailTrlParsed, true))
{
if (detailBuf.length() > 0)
{
detailBuf.append("<br>");
}
detailBuf.append(detailTrlParsed);
}
}
}
return NotificationItem.builder()
.setSummary(summaryTrl)
.setDetail(detailBuf.toString())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\SwingEventNotifierFrame.java | 1 |
请完成以下Java代码 | public static XMLGregorianCalendar toXMLGregorianCalendar(final ZonedDateTime date)
{
if (date == null)
{
return null;
}
final GregorianCalendar c = new GregorianCalendar();
c.setTimeInMillis(date.toInstant().toEpochMilli());
return datatypeFactoryHolder.get().newXMLGregorianCalendar(c);
}
public static LocalDateTime toLocalDateTime(final XMLGregorianCalendar xml)
{
if (xml == null)
{
return null;
}
return xml.toGregorianCalendar().toZonedDateTime().toLocalDateTime();
}
public static ZonedDateTime toZonedDateTime(final XMLGregorianCalendar xml)
{
if (xml == null)
{
return null;
}
return xml.toGregorianCalendar().toZonedDateTime();
}
public static java.util.Date toDate(final XMLGregorianCalendar xml) | {
return xml == null ? null : xml.toGregorianCalendar().getTime();
}
public static Timestamp toTimestamp(final XMLGregorianCalendar xmlGregorianCalendar)
{
final Date date = toDate(xmlGregorianCalendar);
if (date == null)
{
return null;
}
return new Timestamp(date.getTime());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\util\JAXBDateUtils.java | 1 |
请完成以下Java代码 | public void loadPurchaseItems(@NonNull final PurchaseCandidate purchaseCandidate)
{
final PurchaseCandidateId purchaseCandidateId = purchaseCandidate.getId();
if (purchaseCandidateId == null)
{
return;
}
final List<I_C_PurchaseCandidate_Alloc> purchaseCandidateAllocRecords = Services.get(IQueryBL.class)
.createQueryBuilder(I_C_PurchaseCandidate_Alloc.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_PurchaseCandidate_Alloc.COLUMN_C_PurchaseCandidate_ID, purchaseCandidateId.getRepoId())
.create()
.list();
for (final I_C_PurchaseCandidate_Alloc purchaseCandidateAllocRecord : purchaseCandidateAllocRecords)
{
loadPurchaseItem(purchaseCandidate, purchaseCandidateAllocRecord);
}
}
private void loadPurchaseItem(
@NonNull final PurchaseCandidate purchaseCandidate,
@NonNull final I_C_PurchaseCandidate_Alloc record)
{
final ITableRecordReference transactionReference = TableRecordReference.ofReferencedOrNull(record);
if (record.getAD_Issue_ID() <= 0)
{
final OrderAndLineId purchaseOrderAndLineId = OrderAndLineId.ofRepoIds(record.getC_OrderPO_ID(), record.getC_OrderLinePO_ID());
final Quantity purchasedQty = orderLineBL.getQtyOrdered(purchaseOrderAndLineId);
final PurchaseOrderItem purchaseOrderItem = PurchaseOrderItem.builder()
.purchaseCandidate(purchaseCandidate) | .dimension(purchaseCandidate.getDimension())
.purchaseItemId(PurchaseItemId.ofRepoId(record.getC_PurchaseCandidate_Alloc_ID()))
.datePromised(TimeUtil.asZonedDateTime(record.getDatePromised()))
.dateOrdered(TimeUtil.asZonedDateTime(record.getDateOrdered()))
.purchasedQty(purchasedQty)
.remotePurchaseOrderId(record.getRemotePurchaseOrderId())
.transactionReference(transactionReference)
.purchaseOrderAndLineId(purchaseOrderAndLineId)
.build();
purchaseCandidate.addLoadedPurchaseOrderItem(purchaseOrderItem);
}
else
{
purchaseCandidate.createErrorItem()
.purchaseItemId(PurchaseItemId.ofRepoId(record.getC_PurchaseCandidate_Alloc_ID()))
.adIssueId(AdIssueId.ofRepoIdOrNull(record.getAD_Issue_ID()))
.transactionReference(transactionReference)
.buildAndAdd();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\purchaseordercreation\remotepurchaseitem\PurchaseItemRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getAppId() {
return appId;
}
public void setAppId(String appId) {
this.appId = appId == null ? null : appId.trim();
}
public String getAppSectet() {
return appSectet;
}
public void setAppSectet(String appSectet) {
this.appSectet = appSectet == null ? null : appSectet.trim();
}
public String getMerchantId() {
return merchantId;
}
public void setMerchantId(String merchantId) {
this.merchantId = merchantId == null ? null : merchantId.trim();
} | public String getAppType() {
return appType;
}
public void setAppType(String appType) {
this.appType = appType == null ? null : appType.trim();
}
public String getUserNo() {
return userNo;
}
public void setUserNo(String userNo) {
this.userNo = userNo == null ? null : userNo.trim();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName == null ? null : userName.trim();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserPayInfo.java | 2 |
请完成以下Java代码 | private boolean checkIsPackagingMaterialTax(final boolean havePackingMaterialLines, final boolean haveNonPackingMaterialLines)
{
if (havePackingMaterialLines)
{
if (haveNonPackingMaterialLines)
{
log.warn("Found lines with packaging materials and lines without packing materials for C_Order_ID={} and C_Tax_ID={}. Considering {} not a packing material tax.", getC_Order_ID(), getC_Tax_ID(), this);
return false;
}
return true;
}
else
{
return false; | }
}
@Override
public String toString()
{
return "MOrderTax["
+ "C_Order_ID=" + getC_Order_ID()
+ ", C_Tax_ID=" + getC_Tax_ID()
+ ", Base=" + getTaxBaseAmt()
+ ", Tax=" + getTaxAmt()
+ "]";
}
} // MOrderTax | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MOrderTax.java | 1 |
请完成以下Java代码 | public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public java.lang.String getIsSOTrx()
{
return get_ValueAsString(COLUMNNAME_IsSOTrx);
}
@Override
public void setIsSwitchCreditMemo (final boolean IsSwitchCreditMemo)
{
set_Value (COLUMNNAME_IsSwitchCreditMemo, IsSwitchCreditMemo);
} | @Override
public boolean isSwitchCreditMemo()
{
return get_ValueAsBoolean(COLUMNNAME_IsSwitchCreditMemo);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_Export.java | 1 |
请完成以下Java代码 | public Collection<OptionHelp> getOptionsHelp() {
if (this.optionHelp == null) {
OptionHelpFormatter formatter = new OptionHelpFormatter();
getParser().formatHelpWith(formatter);
try {
getParser().printHelpOn(new ByteArrayOutputStream());
}
catch (Exception ex) {
// Ignore and provide no hints
}
this.optionHelp = formatter.getOptionHelp();
}
return this.optionHelp;
}
private static final class OptionHelpFormatter implements HelpFormatter {
private final List<OptionHelp> help = new ArrayList<>();
@Override
public String format(Map<String, ? extends OptionDescriptor> options) {
Comparator<OptionDescriptor> comparator = Comparator
.comparing((optionDescriptor) -> optionDescriptor.options().iterator().next());
Set<OptionDescriptor> sorted = new TreeSet<>(comparator);
sorted.addAll(options.values());
for (OptionDescriptor descriptor : sorted) {
if (!descriptor.representsNonOptions()) {
this.help.add(new OptionHelpAdapter(descriptor));
}
}
return "";
}
Collection<OptionHelp> getOptionHelp() {
return Collections.unmodifiableList(this.help);
}
}
private static class OptionHelpAdapter implements OptionHelp {
private final Set<String> options;
private final String description;
OptionHelpAdapter(OptionDescriptor descriptor) {
this.options = new LinkedHashSet<>(); | for (String option : descriptor.options()) {
String prefix = (option.length() != 1) ? "--" : "-";
this.options.add(prefix + option);
}
if (this.options.contains("--cp")) {
this.options.remove("--cp");
this.options.add("-cp");
}
this.description = descriptor.description();
}
@Override
public Set<String> getOptions() {
return this.options;
}
@Override
public String getUsageHelp() {
return this.description;
}
}
} | repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\options\OptionHandler.java | 1 |
请完成以下Java代码 | public void setEmail(final String email) {
this.email = email;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public int getAge() {
return age;
}
public void setAge(final int age) {
this.age = age;
}
public LocalDate getCreationDate() {
return creationDate;
}
public List<Possession> getPossessionList() {
return possessionList;
}
public void setPossessionList(List<Possession> possessionList) {
this.possessionList = possessionList;
}
@Override
public String toString() {
return "User [name=" + name + ", id=" + id + "]";
}
@Override
public boolean equals(Object o) {
if (this == o) return true; | if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return id == user.id &&
age == user.age &&
Objects.equals(name, user.name) &&
Objects.equals(creationDate, user.creationDate) &&
Objects.equals(email, user.email) &&
Objects.equals(status, user.status);
}
@Override
public int hashCode() {
return Objects.hash(id, name, creationDate, age, email, status);
}
public LocalDate getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(LocalDate lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\modifying\model\User.java | 1 |
请完成以下Java代码 | public abstract class AllowedListDeserializingMessageConverter extends AbstractMessageConverter {
private final Set<String> allowedListPatterns = new LinkedHashSet<>();
/**
* Set simple patterns for allowable packages/classes for deserialization.
* The patterns will be applied in order until a match is found.
* A class can be fully qualified or a wildcard '*' is allowed at the
* beginning or end of the class name.
* Examples: {@code com.foo.*}, {@code *.MyClass}.
* @param patterns the patterns.
*/
public void setAllowedListPatterns(List<String> patterns) {
this.allowedListPatterns.clear();
this.allowedListPatterns.addAll(patterns);
} | /**
* Add package/class patterns to the allowed list.
* @param patterns the patterns to add.
* @since 1.5.7
* @see #setAllowedListPatterns(List)
*/
public void addAllowedListPatterns(String... patterns) {
Collections.addAll(this.allowedListPatterns, patterns);
}
protected void checkAllowedList(Class<?> clazz) {
SerializationUtils.checkAllowedList(clazz, this.allowedListPatterns);
}
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\converter\AllowedListDeserializingMessageConverter.java | 1 |
请完成以下Java代码 | public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() {
return new HistoricTaskInstanceQueryImpl();
}
public HistoricDetailQueryImpl createHistoricDetailQuery() {
return new HistoricDetailQueryImpl();
}
public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() {
return new HistoricVariableInstanceQueryImpl();
}
public HistoricJobLogQueryImpl createHistoricJobLogQuery() {
return new HistoricJobLogQueryImpl();
}
public UserQueryImpl createUserQuery() {
return new DbUserQueryImpl();
}
public GroupQueryImpl createGroupQuery() {
return new DbGroupQueryImpl();
} | public void registerOptimisticLockingListener(OptimisticLockingListener optimisticLockingListener) {
if(optimisticLockingListeners == null) {
optimisticLockingListeners = new ArrayList<>();
}
optimisticLockingListeners.add(optimisticLockingListener);
}
public List<String> getTableNamesPresentInDatabase() {
return persistenceSession.getTableNamesPresent();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\DbEntityManager.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: demo-producer-application
cloud:
# Spring Cloud Stream 配置项,对应 BindingServiceProperties 类
stream:
# Binding 配置项,对应 BindingProperties Map
bindings:
demo01-output:
destination: DEMO-TOPIC-01 # 目的地。这里使用 RocketMQ Topic
content-type: application/json # 内容格式。这里使用 JSON
# Spring Cloud Stream RocketMQ 配置项
rocketmq:
# RocketMQ Binder 配置项,对应 RocketMQBinderConfigurationProperties 类
binder:
name-server: 127.0.0.1:9876 # RocketMQ Namesrv 地址
# RocketMQ 自定义 Binding 配置项,对应 RocketMQBindingProperties Map
bindings:
demo01-output:
# RocketMQ Producer 配置项,对应 RocketMQProducerProperties 类
producer:
group: test # 生产者分组
sync: true # 是否同步发送消息,默认为 false 异 | 步。
server:
port: 18080
management:
endpoints:
web:
exposure:
include: '*' # 需要开放的端点。默认值只打开 health 和 info 两个端点。通过设置 * ,可以开放所有端点。
endpoint:
# Health 端点配置项,对应 HealthProperties 配置类
health:
enabled: true # 是否开启。默认为 true 开启。
show-details: ALWAYS # 何时显示完整的健康信息。默认为 NEVER 都不展示。可选 WHEN_AUTHORIZED 当经过授权的用户;可选 ALWAYS 总是展示。 | repos\SpringBoot-Labs-master\labx-06-spring-cloud-stream-rocketmq\labx-06-sca-stream-rocketmq-producer-actuator\src\main\resources\application.yml | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AppConfig {
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2)
.build();
}
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean emf = new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
emf.setPackagesToScan("com.baeldung.flush");
emf.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
emf.setJpaProperties(getHibernateProperties());
return emf;
} | @Bean
public JpaTransactionManager transactionManager(LocalContainerEntityManagerFactoryBean entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory.getObject());
}
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.hbm2ddl.auto", "create");
properties.setProperty("hibernate.dialect", "org.hibernate.dialect.H2Dialect");
return properties;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-repo\src\main\java\com\baeldung\flush\AppConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void fetchAuthorsBooksByPriceInnerJoin() {
List<Author> authors = authorRepository.fetchAuthorsBooksByPriceInnerJoin(40);
authors.forEach((e) -> System.out.println("Author name: " + e.getName()
+ ", books: " + e.getBooks())); // causes extra SELECTs and the result is not ok
}
// INNER JOIN BAD
@Transactional(readOnly = true)
public void fetchBooksAuthorsInnerJoinBad() {
List<Book> books = bookRepository.fetchBooksAuthorsInnerJoinBad();
books.forEach((e) -> System.out.println("Book title: " + e.getTitle() + ", Isbn: " + e.getIsbn()
+ ", author: " + e.getAuthor())); // causes extra SELECTs but the result is ok
}
// INNER JOIN GOOD
@Transactional(readOnly = true)
public void fetchBooksAuthorsInnerJoinGood() {
List<Book> books = bookRepository.fetchBooksAuthorsInnerJoinGood();
books.forEach((e) -> System.out.println("Book title: " + e.getTitle() + ", Isbn: " + e.getIsbn() | + ", author: " + e.getAuthor())); // causes extra SELECTs but the result is ok
}
// JOIN FETCH
public void fetchAuthorsBooksByPriceJoinFetch() {
List<Author> authors = authorRepository.fetchAuthorsBooksByPriceJoinFetch(40);
authors.forEach((e) -> System.out.println("Author name: " + e.getName()
+ ", books: " + e.getBooks())); // does not cause extra SELECTs and the result is ok
}
// JOIN FETCH
public void fetchBooksAuthorsJoinFetch() {
List<Book> books = bookRepository.fetchBooksAuthorsJoinFetch();
books.forEach((e) -> System.out.println("Book title: " + e.getTitle() + ", Isbn:" + e.getIsbn()
+ ", author: " + e.getAuthor())); // does not cause extra SELECTs and the result is ok
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinVSJoinFetch\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | public class Iterative implements RestoreIPAddress {
public List<String> restoreIPAddresses(String s) {
List<String> result = new ArrayList<>();
if (s.length() < 4 || s.length() > 12) {
return result;
}
for (int i = 1; i < 4; i++) {
for (int j = i + 1; j < Math.min(i + 4, s.length()); j++) {
for (int k = j + 1; k < Math.min(j + 4, s.length()); k++) {
String part1 = s.substring(0, i);
String part2 = s.substring(i, j);
String part3 = s.substring(j, k);
String part4 = s.substring(k); | if (isValid(part1) && isValid(part2) && isValid(part3) && isValid(part4)) {
result.add(part1 + "." + part2 + "." + part3 + "." + part4);
}
}
}
}
return result;
}
private boolean isValid(String part) {
if (part.length() > 1 && part.startsWith("0")) return false;
int num = Integer.parseInt(part);
return num >= 0 && num <= 255;
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-3\src\main\java\com\baeldung\restoreipaddress\Iterative.java | 1 |
请完成以下Java代码 | public static ImportCandidates load(Class<?> annotation, @Nullable ClassLoader classLoader) {
Assert.notNull(annotation, "'annotation' must not be null");
ClassLoader classLoaderToUse = decideClassloader(classLoader);
String location = String.format(LOCATION, annotation.getName());
Enumeration<URL> urls = findUrlsInClasspath(classLoaderToUse, location);
List<String> importCandidates = new ArrayList<>();
while (urls.hasMoreElements()) {
URL url = urls.nextElement();
importCandidates.addAll(readCandidateConfigurations(url));
}
return new ImportCandidates(importCandidates);
}
private static ClassLoader decideClassloader(@Nullable ClassLoader classLoader) {
if (classLoader == null) {
return ImportCandidates.class.getClassLoader();
}
return classLoader;
}
private static Enumeration<URL> findUrlsInClasspath(ClassLoader classLoader, String location) {
try {
return classLoader.getResources(location);
}
catch (IOException ex) {
throw new IllegalArgumentException("Failed to load configurations from location [" + location + "]", ex);
}
}
private static List<String> readCandidateConfigurations(URL url) {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(new UrlResource(url).getInputStream(), StandardCharsets.UTF_8))) { | List<String> candidates = new ArrayList<>();
String line;
while ((line = reader.readLine()) != null) {
line = stripComment(line);
line = line.trim();
if (line.isEmpty()) {
continue;
}
candidates.add(line);
}
return candidates;
}
catch (IOException ex) {
throw new IllegalArgumentException("Unable to load configurations from location [" + url + "]", ex);
}
}
private static String stripComment(String line) {
int commentStart = line.indexOf(COMMENT_START);
if (commentStart == -1) {
return line;
}
return line.substring(0, commentStart);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\annotation\ImportCandidates.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HUInternalUseInventoryCreateRequest
{
@NonNull ZonedDateTime movementDate;
@Nullable
DocTypeId internalUseInventoryDocTypeId;
/**
NOTE: only the top level HUs are processed to avoid issue <a href="https://github.com/metasfresh/metasfresh-webui-api/issues/578">metasfresh/metasfresh-webui-api#578</a>.
Included lower-level HUs are processed recursively.
*/
@NonNull
@Singular("hu")
ImmutableList<I_M_HU> hus; | @Nullable
ActivityId activityId;
@Nullable
String description;
@Builder.Default
boolean completeInventory = true;
@Builder.Default
boolean moveEmptiesToEmptiesWarehouse = false;
@Builder.Default
boolean sendNotifications = true;
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\internaluse\HUInternalUseInventoryCreateRequest.java | 2 |
请完成以下Java代码 | public class CacheDeployer {
private final static CommandLogger LOG = ProcessEngineLogger.CMD_LOGGER;
protected List<Deployer> deployers;
public CacheDeployer() {
this.deployers = Collections.emptyList();
}
public void setDeployers(List<Deployer> deployers) {
this.deployers = deployers;
}
public void deploy(final DeploymentEntity deployment) {
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() throws Exception {
for (Deployer deployer : deployers) {
deployer.deploy(deployment);
}
return null;
}
});
}
public void deployOnlyGivenResourcesOfDeployment(final DeploymentEntity deployment, String... resourceNames) {
initDeployment(deployment, resourceNames);
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() throws Exception {
for (Deployer deployer : deployers) {
deployer.deploy(deployment);
}
return null;
} | });
deployment.setResources(null);
}
protected void initDeployment(final DeploymentEntity deployment, String... resourceNames) {
deployment.clearResources();
for (String resourceName : resourceNames) {
if (resourceName != null) {
// with the given resource we prevent the deployment of querying
// the database which means using all resources that were utilized during the deployment
ResourceEntity resource = Context.getCommandContext().getResourceManager().findResourceByDeploymentIdAndResourceName(deployment.getId(), resourceName);
deployment.addResource(resource);
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\deploy\cache\CacheDeployer.java | 1 |
请完成以下Java代码 | public static final LockOwner forOwnerName(final String ownerName)
{
Check.assumeNotEmpty(ownerName, "ownerName not empty");
return new LockOwner(ownerName, OwnerType.RealOwner);
}
private final String ownerName;
private final OwnerType ownerType;
private LockOwner(final String ownerName, final OwnerType ownerType)
{
Check.assumeNotNull(ownerName, "Param ownerName is not null");
this.ownerName = ownerName;
this.ownerType = ownerType;
}
public boolean isRealOwner()
{ | return ownerType == OwnerType.RealOwner;
}
public boolean isRealOwnerOrNoOwner()
{
return isRealOwner()
|| isNoOwner();
}
public boolean isNoOwner()
{
return ownerType == OwnerType.None;
}
public boolean isAnyOwner()
{
return ownerType == OwnerType.Any;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\LockOwner.java | 1 |
请完成以下Java代码 | public Stream<ProductTaxCategory> findAllFor(@NonNull final I_M_ProductPrice productPrice)
{
return productTaxCategoryRepository.findAllFor(createLookupTaxCategoryRequest(productPrice));
}
@NonNull
private Optional<TaxCategoryId> findTaxCategoryId(@NonNull final I_M_ProductPrice productPrice)
{
return productTaxCategoryRepository.getTaxCategoryId(createLookupTaxCategoryRequest(productPrice));
}
@NonNull
private LookupTaxCategoryRequest createLookupTaxCategoryRequest(@NonNull final I_M_ProductPrice productPrice)
{
final ProductId productId = ProductId.ofRepoId(productPrice.getM_Product_ID());
final PriceListVersionId priceListVersionId = PriceListVersionId.ofRepoId(productPrice.getM_PriceList_Version_ID());
final I_M_PriceList_Version priceListVersionRecord = priceListDAO.getPriceListVersionById(priceListVersionId);
final I_M_PriceList priceListRecord = priceListDAO.getById(priceListVersionRecord.getM_PriceList_ID());
return LookupTaxCategoryRequest.builder()
.productId(productId)
.targetDate(TimeUtil.asInstant(priceListVersionRecord.getValidFrom()))
.countryId(CountryId.ofRepoIdOrNull(priceListRecord.getC_Country_ID()))
.build();
}
@NonNull
public Optional<ProductTaxCategory> getProductTaxCategoryByUniqueKey(
@NonNull final ProductId productId,
@NonNull final CountryId countryId) | {
return productTaxCategoryRepository.getProductTaxCategoryByUniqueKey(productId, countryId);
}
public void save(@NonNull final ProductTaxCategory request)
{
productTaxCategoryRepository.save(request);
}
@NonNull
public ProductTaxCategory createProductTaxCategory(@NonNull final CreateProductTaxCategoryRequest createProductTaxCategoryRequest)
{
return productTaxCategoryRepository.createProductTaxCategory(createProductTaxCategoryRequest);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\tax\ProductTaxCategoryService.java | 1 |
请完成以下Java代码 | public void actionPerformed(ActionEvent e)
{
save();
}
});
checkEnabled();
}
public JMenuItem getJMenuItem()
{
return action.getMenuItem();
}
private boolean checkEnabled()
{
final boolean enabled = model.isEnabled();
action.setEnabled(enabled);
final JMenuItem menuItem = action.getMenuItem();
menuItem.setEnabled(enabled);
menuItem.setVisible(enabled);
return enabled;
}
private void assertEnabled()
{
if (!checkEnabled())
{
throw new AdempiereException("Action is not enabled");
}
}
private void save()
{
assertEnabled();
final GridController gc = parent.getCurrentGridController();
save(gc);
for (final GridController child : gc.getChildGridControllers()) | {
save(child);
}
}
private void save(final GridController gc)
{
Check.assumeNotNull(gc, "gc not null");
final GridTab gridTab = gc.getMTab();
final VTable table = gc.getVTable();
//
// Check CTable to GridTab synchronizer
final CTableColumns2GridTabSynchronizer synchronizer = CTableColumns2GridTabSynchronizer.get(table);
if (synchronizer == null)
{
// synchronizer does not exist, nothing to save
return;
}
//
// Make sure we have the latest values in GridTab
synchronizer.saveToGridTab();
//
// Ask model to settings to database
model.save(gridTab);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\AWindowSaveState.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, Object> checkForDriverNotifications(DriverNotificationRequest driverNotificationRequest) {
Map<String, Object> result = new HashMap<>();
return result;
}
@WorkerTask(value = "notify_customer", threadCount = 2, pollingInterval = 300)
public Map<String, Object> checkForCustomerNotifications(Order order) {
Map<String, Object> result = new HashMap<>();
return result;
}
//
@WorkerTask(value = "cancel_payment", threadCount = 2, pollingInterval = 300)
public Map<String, Object> cancelPaymentTask(CancelRequest cancelRequest) {
Map<String, Object> result = new HashMap<>();
PaymentService.cancelPayment(cancelRequest.getOrderId());
return result;
} | @WorkerTask(value = "cancel_delivery", threadCount = 2, pollingInterval = 300)
public Map<String, Object> cancelDeliveryTask(CancelRequest cancelRequest) {
Map<String, Object> result = new HashMap<>();
ShipmentService.cancelDelivery(cancelRequest.getOrderId());
return result;
}
@WorkerTask(value = "cancel_order", threadCount = 2, pollingInterval = 300)
public Map<String, Object> cancelOrderTask(CancelRequest cancelRequest) {
Map<String, Object> result = new HashMap<>();
Order order = OrderService.getOrder(cancelRequest.getOrderId());
OrderService.cancelOrder(order);
return result;
}
} | repos\tutorials-master\microservices-modules\saga-pattern\src\main\java\io\orkes\example\saga\workers\ConductorWorkers.java | 2 |
请完成以下Java代码 | public void endConcurrentExecutionInEventSubprocess() {
logDebug(
"040", "End concurrent execution in event subprocess");
}
public ProcessEngineException missingDelegateVariableMappingParentClassException(String className, String delegateVarMapping) {
return new ProcessEngineException(
exceptionMessage("041", "Class '{}' doesn't implement '{}'.", className, delegateVarMapping));
}
public ProcessEngineException missingBoundaryCatchEventError(String executionId, String errorCode, String errorMessage) {
return new ProcessEngineException(
exceptionMessage(
"042",
"Execution with id '{}' throws an error event with errorCode '{}' and errorMessage '{}', but no error handler was defined. ",
executionId, | errorCode,
errorMessage));
}
public ProcessEngineException missingBoundaryCatchEventEscalation(String executionId, String escalationCode) {
return new ProcessEngineException(
exceptionMessage(
"043",
"Execution with id '{}' throws an escalation event with escalationCode '{}', but no escalation handler was defined. ",
executionId,
escalationCode));
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\behavior\BpmnBehaviorLogger.java | 1 |
请完成以下Java代码 | public void setMnemonics(final boolean set)
{
final int size = m_fields.size();
for (int i = 0; i < size; i++)
{
final Component c = m_fields.get(i);
if (c instanceof CLabel)
{
final CLabel l = (CLabel)c;
if (set)
{
l.setDisplayedMnemonic(l.getSavedMnemonic());
}
else
{
l.setDisplayedMnemonic(0);
}
}
else if (c instanceof VCheckBox)
{
final VCheckBox cb = (VCheckBox)c;
if (set)
{ | cb.setMnemonic(cb.getSavedMnemonic());
}
else
{
cb.setMnemonic(0);
}
}
else if (c instanceof VButton)
{
final VButton b = (VButton)c;
if (set)
{
b.setMnemonic(b.getSavedMnemonic());
}
else
{
b.setMnemonic(0);
}
}
}
} // setMnemonics
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\VPanelMnemonics.java | 1 |
请完成以下Java代码 | public static DirectoryProperties ofDirectory(final File directory)
{
if (!directory.isDirectory())
{
return NONE;
}
final File propertiesFile = new File(directory, PROPERTIES_FILENAME);
if (!propertiesFile.exists())
{
return NONE;
}
final Properties properties = new Properties();
try (FileInputStream in = new FileInputStream(propertiesFile))
{
properties.load(in);
}
catch (final Exception e)
{
throw new RuntimeException("Failed loading " + propertiesFile, e);
}
return DirectoryProperties.builder()
.labels(Label.ofCommaSeparatedString(properties.getProperty("labels", "")))
.build();
}
public static final DirectoryProperties NONE = DirectoryProperties.builder().build();
@NonNull @Singular ImmutableSet<Label> labels;
public DirectoryProperties mergeFromParent(@NonNull final DirectoryProperties parent)
{
if (this == NONE)
{
return parent;
}
if (parent == NONE)
{
return this;
}
return DirectoryProperties.builder()
.labels(labels)
.labels(parent.labels)
.build();
} | public boolean hasAnyOfLabels(final Collection<Label> labelsToCheck)
{
if (labelsToCheck.isEmpty())
{
return false;
}
if (labels.isEmpty())
{
return false;
}
for (final Label label : labelsToCheck)
{
if (labels.contains(label))
{
return true;
}
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\workspace_migrate\DirectoryProperties.java | 1 |
请完成以下Java代码 | protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
SubProcess subProcess = (SubProcess) baseElement;
propertiesNode.put("activitytype", "Sub-Process");
propertiesNode.put("subprocesstype", "Embedded");
ArrayNode subProcessShapesArrayNode = objectMapper.createArrayNode();
GraphicInfo graphicInfo = model.getGraphicInfo(subProcess.getId());
processor.processFlowElements(
subProcess,
model,
subProcessShapesArrayNode,
formKeyMap,
decisionTableKeyMap,
graphicInfo.getX(),
graphicInfo.getY()
);
flowElementNode.set("childShapes", subProcessShapesArrayNode);
if (subProcess instanceof Transaction) {
propertiesNode.put("istransaction", true);
}
BpmnJsonConverterUtil.convertDataPropertiesToJson(subProcess.getDataObjects(), propertiesNode);
}
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
) {
SubProcess subProcess = null;
if (getPropertyValueAsBoolean("istransaction", elementNode)) {
subProcess = new Transaction();
} else {
subProcess = new SubProcess();
}
JsonNode childShapesArray = elementNode.get(EDITOR_CHILD_SHAPES);
processor.processJsonElements(
childShapesArray,
modelNode,
subProcess,
shapeMap,
formMap,
decisionTableMap,
model
);
JsonNode processDataPropertiesNode = elementNode.get(EDITOR_SHAPE_PROPERTIES).get(PROPERTY_DATA_PROPERTIES);
if (processDataPropertiesNode != null) {
List<ValuedDataObject> dataObjects = BpmnJsonConverterUtil.convertJsonToDataProperties(
processDataPropertiesNode,
subProcess
);
subProcess.setDataObjects(dataObjects);
subProcess.getFlowElements().addAll(dataObjects); | }
return subProcess;
}
@Override
public void setFormMap(Map<String, String> formMap) {
this.formMap = formMap;
}
@Override
public void setFormKeyMap(Map<String, ModelInfo> formKeyMap) {
this.formKeyMap = formKeyMap;
}
@Override
public void setDecisionTableMap(Map<String, String> decisionTableMap) {
this.decisionTableMap = decisionTableMap;
}
@Override
public void setDecisionTableKeyMap(Map<String, ModelInfo> decisionTableKeyMap) {
this.decisionTableKeyMap = decisionTableKeyMap;
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\SubProcessJsonConverter.java | 1 |
请完成以下Java代码 | public class RememberMeAuthenticationProvider implements AuthenticationProvider, InitializingBean, MessageSourceAware {
protected MessageSourceAccessor messages = SpringSecurityMessageSource.getAccessor();
private String key;
public RememberMeAuthenticationProvider(String key) {
Assert.hasLength(key, "key must have a length");
this.key = key;
}
@Override
public void afterPropertiesSet() {
Assert.notNull(this.messages, "A message source must be set");
}
@Override
public @Nullable Authentication authenticate(Authentication authentication) throws AuthenticationException {
if (!supports(authentication.getClass())) {
return null;
}
if (this.key.hashCode() != ((RememberMeAuthenticationToken) authentication).getKeyHash()) {
throw new BadCredentialsException(this.messages.getMessage("RememberMeAuthenticationProvider.incorrectKey",
"The presented RememberMeAuthenticationToken does not contain the expected key"));
}
return authentication;
} | public String getKey() {
return this.key;
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
@Override
public boolean supports(Class<?> authentication) {
return (RememberMeAuthenticationToken.class.isAssignableFrom(authentication));
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\RememberMeAuthenticationProvider.java | 1 |
请完成以下Java代码 | public String getBodyAsString()
{
if (body == null)
{
return null;
}
else if (isJson())
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(body);
}
catch (JsonProcessingException e)
{
throw AdempiereException.wrapIfNeeded(e); | }
}
else if (body instanceof String)
{
return (String)body;
}
else if (body instanceof byte[])
{
return new String((byte[])body, charset);
}
else
{
return body.toString();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\dto\ApiResponse.java | 1 |
请完成以下Java代码 | public static String getExtension(String language) {
language = language.toLowerCase();
if("ecmascript".equals(language)) {
language = "javascript";
}
return extensions.get(language);
}
/**
* Get the spin scripting environment
*
* @param language the language name
* @return the environment script as string or null if the language is
* not in the set of languages supported by spin.
*/
public static String get(String language) {
language = language.toLowerCase();
if("ecmascript".equals(language)) {
language = "javascript";
}
String extension = extensions.get(language);
if(extension == null) {
return null;
} else {
return loadScriptEnv(language, extension);
}
}
protected static String loadScriptEnv(String language, String extension) { | String scriptEnvPath = String.format(ENV_PATH_TEMPLATE, language, extension);
InputStream envResource = SpinScriptException.class.getClassLoader().getResourceAsStream(scriptEnvPath);
if(envResource == null) {
throw LOG.noScriptEnvFoundForLanguage(language, scriptEnvPath);
} else {
try {
return SpinIoUtil.inputStreamAsString(envResource);
} finally {
SpinIoUtil.closeSilently(envResource);
}
}
}
} | repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\scripting\SpinScriptEnv.java | 1 |
请完成以下Java代码 | public class M_Shipment_Constraint
{
@ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE })
public void invalidateShipmentSchedules(final I_M_Shipment_Constraint constraint, final ModelChangeType changeType)
{
final Set<IShipmentScheduleSegment> affectedStorageSegments = extractAffectedStorageSegments(constraint, changeType);
if (affectedStorageSegments.isEmpty())
{
return;
}
final IShipmentScheduleInvalidateBL invalidSchedulesInvalidator = Services.get(IShipmentScheduleInvalidateBL.class);
invalidSchedulesInvalidator.flagSegmentForRecompute(affectedStorageSegments);
}
private static final Set<IShipmentScheduleSegment> extractAffectedStorageSegments(final I_M_Shipment_Constraint constraint, final ModelChangeType changeType)
{
final Set<IShipmentScheduleSegment> storageSegments = new LinkedHashSet<>();
if (changeType.isNewOrChange())
{
if (constraint.isActive())
{
storageSegments.add(createStorageSegment(constraint));
}
}
if (changeType.isChangeOrDelete()) | {
final I_M_Shipment_Constraint constraintOld = InterfaceWrapperHelper.createOld(constraint, I_M_Shipment_Constraint.class);
if (constraintOld.isActive())
{
storageSegments.add(createStorageSegment(constraintOld));
}
}
return storageSegments;
}
private static IShipmentScheduleSegment createStorageSegment(final I_M_Shipment_Constraint constraint)
{
return ImmutableShipmentScheduleSegment.builder()
.anyBPartner()
.billBPartnerId(constraint.getBill_BPartner_ID())
.anyProduct()
.anyLocator()
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\M_Shipment_Constraint.java | 1 |
请完成以下Java代码 | private DocTypeId getVirtualInventoryDocTypeId(@NonNull final ClientId clientId, @NonNull final OrgId orgId)
{
return docTypeDAO.getDocTypeId(DocTypeQuery.builder()
.docBaseType(DocBaseType.MaterialPhysicalInventory)
.docSubType(DocSubType.VirtualInventory)
.adClientId(clientId.getRepoId())
.adOrgId(orgId.getRepoId())
.build());
}
private static DocBaseAndSubType getDocBaseAndSubType(@Nullable final HUAggregationType huAggregationType)
{
if (huAggregationType == null)
{
// #10656 There is no inventory doctype without a subtype. Consider the AggregatedHUInventory as a default
return AggregationType.MULTIPLE_HUS.getDocBaseAndSubType();
}
else
{
return AggregationType.getByHUAggregationType(huAggregationType).getDocBaseAndSubType();
}
}
public void distributeQuantityToHUs(@NonNull final I_M_InventoryLine inventoryLineRecord)
{
inventoryRepository.updateInventoryLineByRecord(inventoryLineRecord, InventoryLine::distributeQtyCountToHUs);
}
public void deleteInventoryLineHUs(@NonNull final InventoryLineId inventoryLineId)
{
inventoryRepository.deleteInventoryLineHUs(inventoryLineId);
}
public InventoryLine toInventoryLine(final I_M_InventoryLine inventoryLineRecord)
{
return inventoryRepository.toInventoryLine(inventoryLineRecord);
}
public Collection<I_M_InventoryLine> retrieveAllLinesForHU(final HuId huId)
{ | return inventoryRepository.retrieveAllLinesForHU(huId);
}
public void saveInventoryLineHURecords(final InventoryLine inventoryLine, final @NonNull InventoryId inventoryId)
{
inventoryRepository.saveInventoryLineHURecords(inventoryLine, inventoryId);
}
public Stream<InventoryReference> streamReferences(@NonNull final InventoryQuery query)
{
return inventoryRepository.streamReferences(query);
}
public Inventory updateById(@NonNull final InventoryId inventoryId, @NonNull final UnaryOperator<Inventory> updater)
{
return inventoryRepository.updateById(inventoryId, updater);
}
public void updateByQuery(@NonNull final InventoryQuery query, @NonNull final UnaryOperator<Inventory> updater)
{
inventoryRepository.updateByQuery(query, updater);
}
public DraftInventoryLinesCreateResponse createDraftLines(@NonNull final DraftInventoryLinesCreateRequest request)
{
return DraftInventoryLinesCreateCommand.builder()
.inventoryRepository(inventoryRepository)
.huForInventoryLineFactory(huForInventoryLineFactory)
.request(request)
.build()
.execute();
}
public void setQtyCountToQtyBookForInventory(@NonNull final InventoryId inventoryId)
{
inventoryRepository.setQtyCountToQtyBookForInventory(inventoryId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\InventoryService.java | 1 |
请完成以下Java代码 | private static void usingCountDownLatch() throws InterruptedException {
System.out.println("===============================================");
System.out.println(" >>> Using CountDownLatch <<<<");
System.out.println("===============================================");
CountDownLatch latch = new CountDownLatch(1);
WorkerWithCountDownLatch worker1 = new WorkerWithCountDownLatch("Worker with latch 1", latch);
WorkerWithCountDownLatch worker2 = new WorkerWithCountDownLatch("Worker with latch 2", latch);
worker1.start();
worker2.start();
Thread.sleep(10);//simulation of some actual work
System.out.println("-----------------------------------------------");
System.out.println(" Now release the latch:");
System.out.println("-----------------------------------------------");
latch.countDown();
}
private static void usingCyclicBarrier() throws BrokenBarrierException, InterruptedException {
System.out.println("\n===============================================");
System.out.println(" >>> Using CyclicBarrier <<<<");
System.out.println("===============================================");
CyclicBarrier barrier = new CyclicBarrier(3);
WorkerWithCyclicBarrier worker1 = new WorkerWithCyclicBarrier("Worker with barrier 1", barrier);
WorkerWithCyclicBarrier worker2 = new WorkerWithCyclicBarrier("Worker with barrier 2", barrier);
worker1.start();
worker2.start();
Thread.sleep(10);//simulation of some actual work
System.out.println("-----------------------------------------------");
System.out.println(" Now open the barrier:");
System.out.println("-----------------------------------------------");
barrier.await();
} | private static void usingPhaser() throws InterruptedException {
System.out.println("\n===============================================");
System.out.println(" >>> Using Phaser <<<");
System.out.println("===============================================");
Phaser phaser = new Phaser();
phaser.register();
WorkerWithPhaser worker1 = new WorkerWithPhaser("Worker with phaser 1", phaser);
WorkerWithPhaser worker2 = new WorkerWithPhaser("Worker with phaser 2", phaser);
worker1.start();
worker2.start();
Thread.sleep(10);//simulation of some actual work
System.out.println("-----------------------------------------------");
System.out.println(" Now open the phaser barrier:");
System.out.println("-----------------------------------------------");
phaser.arriveAndAwaitAdvance();
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-4\src\main\java\com\baeldung\threadsstartatsametime\ThreadsStartAtSameTime.java | 1 |
请完成以下Java代码 | public void propertyChange(final PropertyChangeEvent evt)
{
final Object parentNew = evt.getNewValue();
if (parentNew != null)
{
editorComp.requestFocus();
}
}
});
}
// private final TableColumnInfo columnInfo;
private final VEditor m_editor;
private final Class<?> modelValueClass;
private final Class<?> editorValueClass;
@Override
public Component getTableCellEditorComponent(final JTable table,
final Object valueModel,
final boolean isSelected,
int rowIndexView,
int columnIndexView)
{
// Set Value
final Object valueEditor = convertToEditorValue(valueModel);
m_editor.setValue(valueEditor);
// Set UI
m_editor.setBorder(null);
// m_editor.setBorder(UIManager.getBorder("Table.focusCellHighlightBorder"));
m_editor.setFont(table.getFont());
final Component editorComp = (Component)m_editor;
return editorComp;
}
@Override
public Object getCellEditorValue()
{
if (m_editor == null)
{
return null;
}
final Object valueEditor = m_editor.getValue();
//
// Check and convert the value if needed
final Object valueModel;
if (valueEditor instanceof Number && modelValueClass == KeyNamePair.class)
{
final int key = ((Number)valueEditor).intValue();
final String name = m_editor.getDisplay();
valueModel = new KeyNamePair(key, name);
}
else
{
valueModel = valueEditor;
}
return valueModel;
}
@Override
public boolean stopCellEditing()
{
try | {
return super.stopCellEditing();
}
catch (Exception e)
{
final Component comp = (Component)m_editor;
final int windowNo = Env.getWindowNo(comp);
Services.get(IClientUI.class).warn(windowNo, e);
}
return false;
}
@Override
public void cancelCellEditing()
{
super.cancelCellEditing();
}
private Object convertToEditorValue(final Object valueModel)
{
final Object valueEditor;
if (valueModel instanceof KeyNamePair && editorValueClass == Integer.class)
{
valueEditor = ((KeyNamePair)valueModel).getKey();
}
else
{
valueEditor = valueModel;
}
return valueEditor;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableModelCellEditor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProcessDefinitionRestService extends AbstractPluginResource {
public static final String PATH = "/process-definition";
public ProcessDefinitionRestService(String engineName) {
super(engineName);
}
@Path("/{id}")
public ProcessDefinitionResource getProcessDefinition(@PathParam("id") String id) {
return new ProcessDefinitionResource(getProcessEngine().getName(), id);
}
@GET
@Path("/statistics-count")
@Produces(MediaType.APPLICATION_JSON)
public CountResultDto getStatisticsCount(@Context UriInfo uriInfo) {
QueryParameters queryDto = new ProcessDefinitionStatisticsQueryDto(uriInfo.getQueryParameters());
configureExecutionQuery(queryDto);
long count = getQueryService().executeQueryRowCount("selectPDStatisticsCount", queryDto);
return new CountResultDto(count);
}
@GET
@Path("/statistics")
@Produces(MediaType.APPLICATION_JSON) | @Consumes(MediaType.APPLICATION_JSON)
public List<ProcessDefinitionStatisticsDto> queryStatistics(@Context UriInfo uriInfo,
@QueryParam("firstResult") Integer firstResult,
@QueryParam("maxResults") Integer maxResults) {
QueryParameters queryDto = new ProcessDefinitionStatisticsQueryDto(uriInfo.getQueryParameters());
configureExecutionQuery(queryDto);
queryDto.setFirstResult(firstResult != null && firstResult >= 0 ? firstResult : 0);
queryDto.setMaxResults(maxResults != null && maxResults > 0 ? maxResults : Integer.MAX_VALUE);
return getQueryService().executeQuery("selectPDStatistics", queryDto);
}
protected void configureExecutionQuery(QueryParameters query) {
configureAuthorizationCheck(query);
configureTenantCheck(query);
addPermissionCheck(query, PROCESS_DEFINITION, "RES.KEY_", READ);
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\resources\ProcessDefinitionRestService.java | 2 |
请完成以下Java代码 | public void createLink(HalRelation rel, String... pathParams) {
if(pathParams != null && pathParams.length > 0 && pathParams[0] != null) {
Set<String> linkedResourceIds = linkedResources.get(rel);
if(linkedResourceIds == null) {
linkedResourceIds = new HashSet<String>();
linkedResources.put(rel, linkedResourceIds);
}
// Hmm... use the last id in the pathParams as linked resource id
linkedResourceIds.add(pathParams[pathParams.length - 1]);
resource.addLink(rel.relName, rel.uriTemplate.build((Object[])pathParams));
}
}
public Set<HalRelation> getLinkedRelations() {
return linkedResources.keySet();
}
public Set<String> getLinkedResourceIdsByRelation(HalRelation relation) {
Set<String> result = linkedResources.get(relation);
if(result != null) {
return result;
} else {
return Collections.emptySet();
}
}
/**
* Resolves a relation. Locates a HalLinkResolver for resolving the set of all linked resources in the relation.
*
* @param relation the relation to resolve
* @param processEngine the process engine to use
* @return the list of resolved resources
* @throws RuntimeException if no HalLinkResolver can be found for the linked resource type.
*/ | public List<HalResource<?>> resolve(HalRelation relation, ProcessEngine processEngine) {
HalLinkResolver linkResolver = hal.getLinkResolver(relation.resourceType);
if(linkResolver != null) {
Set<String> linkedIds = getLinkedResourceIdsByRelation(relation);
if(!linkedIds.isEmpty()) {
return linkResolver.resolveLinks(linkedIds.toArray(new String[linkedIds.size()]), processEngine);
} else {
return Collections.emptyList();
}
} else {
throw new RuntimeException("Cannot find HAL link resolver for resource type '"+relation.resourceType+"'.");
}
}
/**
* merge the links of an embedded resource into this linker.
* This is useful when building resources which are actually resource collections.
* You can then merge the relations of all resources in the collection and the unique the set of linked resources to embed.
*
* @param embedded the embedded resource for which the links should be merged into this linker.
*/
public void mergeLinks(HalResource<?> embedded) {
for (Entry<HalRelation, Set<String>> linkentry : embedded.linker.linkedResources.entrySet()) {
Set<String> linkedIdSet = linkedResources.get(linkentry.getKey());
if(linkedIdSet != null) {
linkedIdSet.addAll(linkentry.getValue());
}else {
linkedResources.put(linkentry.getKey(), linkentry.getValue());
}
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\HalLinker.java | 1 |
请完成以下Java代码 | public UIComponent getUIComponent(
final @NonNull WFProcess wfProcess,
final @NonNull WFActivity wfActivity,
final @NonNull JsonOpts jsonOpts)
{
final PickingJob pickingJob = getPickingJob(wfProcess);
final JsonQRCode currentPickingSlot = pickingJob
.getPickingSlot()
.map(SetPickingSlotWFActivityHandler::toJsonQRCode)
.orElse(null);
return SetScannedBarcodeSupportHelper.uiComponent()
.currentValue(currentPickingSlot)
.alwaysAvailableToUser(wfActivity.getAlwaysAvailableToUser())
.displaySuggestions(pickingJob.isDisplayPickingSlotSuggestions())
.build();
}
public static JsonQRCode toJsonQRCode(final PickingSlotIdAndCaption pickingSlotIdAndCaption)
{
return JsonPickingJobLine.toJsonQRCode(pickingSlotIdAndCaption);
}
@Override
public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity wfActivity)
{
final PickingJob pickingJob = getPickingJob(wfProcess);
return computeActivityState(pickingJob);
}
public static WFActivityStatus computeActivityState(final PickingJob pickingJob)
{
return pickingJob.getPickingSlot().isPresent() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED;
}
@Override
public WFProcess setScannedBarcode(@NonNull final SetScannedBarcodeRequest request)
{
final PickingSlotQRCode pickingSlotQRCode = PickingSlotQRCode.ofGlobalQRCodeJsonString(request.getScannedBarcode());
return PickingMobileApplication.mapPickingJob(
request.getWfProcess(),
pickingJob -> pickingJobRestService.allocateAndSetPickingSlot(pickingJob, pickingSlotQRCode)
); | }
@Override
public JsonScannedBarcodeSuggestions getScannedBarcodeSuggestions(@NonNull GetScannedBarcodeSuggestionsRequest request)
{
final PickingJob pickingJob = getPickingJob(request.getWfProcess());
final PickingSlotSuggestions pickingSlotSuggestions = pickingJobRestService.getPickingSlotsSuggestions(pickingJob);
return toJson(pickingSlotSuggestions);
}
private static JsonScannedBarcodeSuggestions toJson(final PickingSlotSuggestions pickingSlotSuggestions)
{
if (pickingSlotSuggestions.isEmpty())
{
return JsonScannedBarcodeSuggestions.EMPTY;
}
return pickingSlotSuggestions.stream()
.map(SetPickingSlotWFActivityHandler::toJson)
.collect(JsonScannedBarcodeSuggestions.collect());
}
private static JsonScannedBarcodeSuggestion toJson(final PickingSlotSuggestion pickingSlotSuggestion)
{
return JsonScannedBarcodeSuggestion.builder()
.caption(pickingSlotSuggestion.getCaption())
.detail(pickingSlotSuggestion.getDeliveryAddress())
.qrCode(pickingSlotSuggestion.getQRCode().toGlobalQRCodeJsonString())
.property1("HU")
.value1(String.valueOf(pickingSlotSuggestion.getCountHUs()))
.additionalProperty("bpartnerLocationId", BPartnerLocationId.toRepoId(pickingSlotSuggestion.getDeliveryBPLocationId())) // for testing
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\handlers\activity_handlers\SetPickingSlotWFActivityHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserController {
@Autowired
private UserRepository userRepository;
@GetMapping("/users")
public List<User> getAllUsers() {
return userRepository.findAll();
}
@GetMapping("/users/{id}")
public ResponseEntity<User> getUserById(
@PathVariable(value = "id") Long userId) throws ResourceNotFoundException {
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found :: " + userId));
return ResponseEntity.ok().body(user);
}
@PostMapping("/users")
public User createUser(@Valid @RequestBody User user) {
return userRepository.save(user);
}
@PutMapping("/users/{id}")
public ResponseEntity<User> updateUser(
@PathVariable(value = "id") Long userId, | @Valid @RequestBody User userDetails) throws ResourceNotFoundException {
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found :: " + userId));
user.setEmailId(userDetails.getEmailId());
user.setLastName(userDetails.getLastName());
user.setFirstName(userDetails.getFirstName());
user.setUpdatedAt(new Date());
final User updatedUser = userRepository.save(user);
return ResponseEntity.ok(updatedUser);
}
@DeleteMapping("/users/{id}")
public Map<String, Boolean> deleteUser(
@PathVariable(value = "id") Long userId) throws ResourceNotFoundException {
User user = userRepository.findById(userId)
.orElseThrow(() -> new ResourceNotFoundException("User not found :: " + userId));
userRepository.delete(user);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
} | repos\Spring-Boot-Advanced-Projects-main\spring-boot-crud-rest\src\main\java\com\alanbinu\springbootcrudrest\controller\UserController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public ResponseEntity<?> handleReqSync(Model model) {
// ...
return ResponseEntity.ok("ok");
}
@GetMapping("/async-deferredresult-timeout")
public DeferredResult<ResponseEntity<?>> handleReqWithTimeouts(Model model) {
LOG.info("Received async request with a configured timeout");
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>(500l);
deferredResult.onTimeout(() -> deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.REQUEST_TIMEOUT)
.body("Request timeout occurred.")));
CompletableFuture.supplyAsync(() -> {
LOG.info("Processing in separate thread");
try {
Thread.sleep(6000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return "error";
})
.whenCompleteAsync((result, exc) -> deferredResult.setResult(ResponseEntity.ok(result)));
LOG.info("servlet thread freed");
return deferredResult;
} | @GetMapping("/async-deferredresult-error")
public DeferredResult<ResponseEntity<?>> handleAsyncFailedRequest(Model model) {
LOG.info("Received async request with a configured error handler");
DeferredResult<ResponseEntity<?>> deferredResult = new DeferredResult<>();
deferredResult.onError(new Consumer<Throwable>() {
@Override
public void accept(Throwable t) {
deferredResult.setErrorResult(ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
.body("An error occurred."));
}
});
LOG.info("servlet thread freed");
return deferredResult;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\java\com\baeldung\sampleapp\web\controller\DeferredResultController.java | 2 |
请完成以下Java代码 | public String cgformPostCrazyForm(String tableName, JSONObject jsonObject) {
return null;
}
@Override
public String cgformPutCrazyForm(String tableName, JSONObject jsonObject) {
return null;
}
@Override
public JSONObject cgformQueryAllDataByTableName(String tableName, String dataIds) {
return null;
}
@Override | public String cgformDeleteDataByCode(String cgformCode, String dataIds) {
return null;
}
@Override
public Map<String, Object> cgreportGetData(String code, String forceKey, String dataList) {
return null;
}
@Override
public List<DictModel> cgreportGetDataPackage(String code, String dictText, String dictCode, String dataList) {
return null;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-api\jeecg-system-cloud-api\src\main\java\org\jeecg\common\online\api\fallback\OnlineBaseExtApiFallback.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_C_Order getC_Order()
{
return get_ValueAsPO(COLUMNNAME_C_Order_ID, org.compiere.model.I_C_Order.class);
}
@Override
public void setC_Order(final org.compiere.model.I_C_Order C_Order)
{
set_ValueFromPO(COLUMNNAME_C_Order_ID, org.compiere.model.I_C_Order.class, C_Order);
}
@Override
public void setC_Order_ID (final int C_Order_ID)
{
if (C_Order_ID < 1)
set_Value (COLUMNNAME_C_Order_ID, null);
else
set_Value (COLUMNNAME_C_Order_ID, C_Order_ID);
}
@Override
public int getC_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Order_ID);
}
@Override
public void setDateOrdered (final @Nullable java.sql.Timestamp DateOrdered)
{
set_Value (COLUMNNAME_DateOrdered, DateOrdered);
}
@Override
public java.sql.Timestamp getDateOrdered()
{
return get_ValueAsTimestamp(COLUMNNAME_DateOrdered);
}
@Override
public void setEDI_cctop_111_v_ID (final int EDI_cctop_111_v_ID)
{
if (EDI_cctop_111_v_ID < 1)
set_ValueNoCheck (COLUMNNAME_EDI_cctop_111_v_ID, null);
else
set_ValueNoCheck (COLUMNNAME_EDI_cctop_111_v_ID, EDI_cctop_111_v_ID);
}
@Override
public int getEDI_cctop_111_v_ID()
{
return get_ValueAsInt(COLUMNNAME_EDI_cctop_111_v_ID);
}
@Override
public org.compiere.model.I_M_InOut getM_InOut()
{
return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class);
}
@Override
public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut)
{
set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut);
}
@Override
public void setM_InOut_ID (final int M_InOut_ID)
{
if (M_InOut_ID < 1)
set_Value (COLUMNNAME_M_InOut_ID, null);
else
set_Value (COLUMNNAME_M_InOut_ID, M_InOut_ID);
}
@Override
public int getM_InOut_ID()
{
return get_ValueAsInt(COLUMNNAME_M_InOut_ID);
}
@Override | public void setMovementDate (final @Nullable java.sql.Timestamp MovementDate)
{
set_Value (COLUMNNAME_MovementDate, MovementDate);
}
@Override
public java.sql.Timestamp getMovementDate()
{
return get_ValueAsTimestamp(COLUMNNAME_MovementDate);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setShipment_DocumentNo (final @Nullable java.lang.String Shipment_DocumentNo)
{
set_Value (COLUMNNAME_Shipment_DocumentNo, Shipment_DocumentNo);
}
@Override
public java.lang.String getShipment_DocumentNo()
{
return get_ValueAsString(COLUMNNAME_Shipment_DocumentNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_111_v.java | 1 |
请完成以下Java代码 | public B authorizationGrant(Authentication authorizationGrant) {
return put(AUTHORIZATION_GRANT_AUTHENTICATION_KEY, authorizationGrant);
}
/**
* Associates an attribute.
* @param key the key for the attribute
* @param value the value of the attribute
* @return the {@link AbstractBuilder} for further configuration
*/
public B put(Object key, Object value) {
Assert.notNull(key, "key cannot be null");
Assert.notNull(value, "value cannot be null");
this.context.put(key, value);
return getThis();
}
/**
* A {@code Consumer} of the attributes {@code Map} allowing the ability to add,
* replace, or remove.
* @param contextConsumer a {@link Consumer} of the attributes {@code Map}
* @return the {@link AbstractBuilder} for further configuration
*/
public B context(Consumer<Map<Object, Object>> contextConsumer) {
contextConsumer.accept(this.context);
return getThis();
}
@SuppressWarnings("unchecked")
protected <V> V get(Object key) {
return (V) this.context.get(key);
}
protected Map<Object, Object> getContext() {
return this.context; | }
@SuppressWarnings("unchecked")
protected final B getThis() {
return (B) this;
}
/**
* Builds a new {@link OAuth2TokenContext}.
* @return the {@link OAuth2TokenContext}
*/
public abstract T build();
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2TokenContext.java | 1 |
请完成以下Java代码 | public DocumentValidStatus checkAndGetValidStatus(final OnValidStatusChanged onValidStatusChanged)
{
return DocumentValidStatus.documentValid();
}
@Override
public boolean hasChangesRecursivelly()
{
return false;
}
@Override
public void saveIfHasChanges()
{
}
@Override
public void markStaleAll()
{ | }
@Override
public void markStale(final DocumentIdsSelection rowIds)
{
}
@Override
public boolean isStale()
{
return false;
}
@Override
public int getNextLineNo()
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\HighVolumeReadonlyIncludedDocumentsCollection.java | 1 |
请完成以下Java代码 | public class License {
private UUID id;
private OffsetDateTime startDate;
private OffsetDateTime endDate;
private boolean active;
private boolean renewalRequired;
private LicenseType licenseType;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public OffsetDateTime getStartDate() {
return startDate;
}
public void setStartDate(OffsetDateTime startDate) {
this.startDate = startDate;
}
public OffsetDateTime getEndDate() {
return endDate;
} | public void setEndDate(OffsetDateTime endDate) {
this.endDate = endDate;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public boolean isRenewalRequired() {
return renewalRequired;
}
public void setRenewalRequired(boolean renewalRequired) {
this.renewalRequired = renewalRequired;
}
public enum LicenseType {
INDIVIDUAL, FAMILY
}
public LicenseType getLicenseType() {
return licenseType;
}
public void setLicenseType(LicenseType licenseType) {
this.licenseType = licenseType;
}
} | repos\tutorials-master\mapstruct\src\main\java\com\baeldung\expression\model\License.java | 1 |
请完成以下Java代码 | List<URL> getUrls() {
return this.lines.stream().map(this::asUrl).toList();
}
private URL asUrl(String line) {
try {
return new File(this.root, line).toURI().toURL();
}
catch (MalformedURLException ex) {
throw new IllegalStateException(ex);
}
}
static ClassPathIndexFile loadIfPossible(File root, String location) throws IOException {
return loadIfPossible(root, new File(root, location));
}
private static ClassPathIndexFile loadIfPossible(File root, File indexFile) throws IOException { | if (indexFile.exists() && indexFile.isFile()) {
List<String> lines = Files.readAllLines(indexFile.toPath())
.stream()
.filter(ClassPathIndexFile::lineHasText)
.toList();
return new ClassPathIndexFile(root, lines);
}
return null;
}
private static boolean lineHasText(String line) {
return !line.trim().isEmpty();
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\ClassPathIndexFile.java | 1 |
请完成以下Java代码 | protected ObjectMapper getObjectMapper() {
return this.objectMapper;
}
@Override
protected Headers initialRecordHeaders(Message<?> message) {
RecordHeaders headers = new RecordHeaders();
this.typeMapper.fromClass(message.getPayload().getClass(), headers);
return headers;
}
@Override
protected @Nullable Object convertPayload(Message<?> message) {
throw new UnsupportedOperationException("Select a subclass that creates a ProducerRecord value "
+ "corresponding to the configured Kafka Serializer");
}
@Override
protected Object extractAndConvertValue(ConsumerRecord<?, ?> record, @Nullable Type type) {
Object value = record.value();
if (record.value() == null) {
return KafkaNull.INSTANCE;
}
JavaType javaType = determineJavaType(record, type);
if (value instanceof Bytes) {
value = ((Bytes) value).get();
}
if (value instanceof String) {
try {
return this.objectMapper.readValue((String) value, javaType);
}
catch (IOException e) {
throw new ConversionException("Failed to convert from JSON", record, e);
}
}
else if (value instanceof byte[]) {
try {
return this.objectMapper.readValue((byte[]) value, javaType);
}
catch (IOException e) { | throw new ConversionException("Failed to convert from JSON", record, e);
}
}
else {
throw new IllegalStateException("Only String, Bytes, or byte[] supported");
}
}
private JavaType determineJavaType(ConsumerRecord<?, ?> record, @Nullable Type type) {
JavaType javaType = this.typeMapper.getTypePrecedence()
.equals(org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper.TypePrecedence.INFERRED) && type != null
? TypeFactory.defaultInstance().constructType(type)
: this.typeMapper.toJavaType(record.headers());
if (javaType == null) { // no headers
if (type != null) {
javaType = TypeFactory.defaultInstance().constructType(type);
}
else {
javaType = OBJECT;
}
}
return javaType;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\converter\JsonMessageConverter.java | 1 |
请完成以下Java代码 | public IReturnsInOutProducer setC_BPartner(final I_C_BPartner bpartner)
{
assertConfigurable();
_bpartner = bpartner;
return this;
}
private int getC_BPartner_ID_ToUse()
{
if (_bpartner != null)
{
return _bpartner.getC_BPartner_ID();
}
return -1;
}
@Override
public IReturnsInOutProducer setC_BPartner_Location(final I_C_BPartner_Location bpLocation)
{
assertConfigurable();
Check.assumeNotNull(bpLocation, "bpLocation not null");
_bpartnerLocationId = bpLocation.getC_BPartner_Location_ID();
return this;
}
private int getC_BPartner_Location_ID_ToUse()
{
if (_bpartnerLocationId > 0)
{
return _bpartnerLocationId;
}
final I_C_BPartner bpartner = _bpartner;
if (bpartner != null)
{
final I_C_BPartner_Location bpLocation = bpartnerDAO.retrieveShipToLocation(getCtx(), bpartner.getC_BPartner_ID(), ITrx.TRXNAME_None);
if (bpLocation != null)
{
return bpLocation.getC_BPartner_Location_ID();
}
}
return -1;
}
@Override
public IReturnsInOutProducer setMovementType(final String movementType)
{
assertConfigurable();
_movementType = movementType;
return this;
}
public IReturnsInOutProducer setManualReturnInOut(final I_M_InOut manualReturnInOut)
{
assertConfigurable();
_manualReturnInOut = manualReturnInOut;
return this;
}
private String getMovementTypeToUse()
{
Check.assumeNotNull(_movementType, "movementType not null");
return _movementType;
}
@Override
public IReturnsInOutProducer setM_Warehouse(final I_M_Warehouse warehouse)
{
assertConfigurable();
_warehouse = warehouse;
return this;
}
private final int getM_Warehouse_ID_ToUse()
{
if (_warehouse != null)
{
return _warehouse.getM_Warehouse_ID();
}
return -1;
}
@Override
public IReturnsInOutProducer setMovementDate(final Date movementDate)
{
Check.assumeNotNull(movementDate, "movementDate not null");
_movementDate = movementDate; | return this;
}
protected final Timestamp getMovementDateToUse()
{
if (_movementDate != null)
{
return TimeUtil.asTimestamp(_movementDate);
}
final Properties ctx = getCtx();
final Timestamp movementDate = Env.getDate(ctx); // use Login date (08306)
return movementDate;
}
@Override
public IReturnsInOutProducer setC_Order(final I_C_Order order)
{
assertConfigurable();
_order = order;
return this;
}
protected I_C_Order getC_Order()
{
return _order;
}
@Override
public IReturnsInOutProducer dontComplete()
{
_complete = false;
return this;
}
protected boolean isComplete()
{
return _complete;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\AbstractReturnsInOutProducer.java | 1 |
请完成以下Java代码 | private static final class ReactorBatchLoader<K, V> implements BatchLoaderWithContext<K, V> {
private final String name;
private final BiFunction<List<K>, BatchLoaderEnvironment, Flux<V>> loader;
private final Supplier<DataLoaderOptions> optionsSupplier;
private ReactorBatchLoader(String name,
BiFunction<List<K>, BatchLoaderEnvironment, Flux<V>> loader,
Supplier<DataLoaderOptions> optionsSupplier) {
this.name = name;
this.loader = loader;
this.optionsSupplier = optionsSupplier;
}
String getName() {
return this.name;
}
DataLoaderOptions getOptions() {
return this.optionsSupplier.get();
}
@Override
public CompletionStage<List<V>> load(List<K> keys, BatchLoaderEnvironment environment) {
GraphQLContext graphQLContext = environment.getContext();
Assert.state(graphQLContext != null, "No GraphQLContext available");
ContextSnapshot snapshot = ContextPropagationHelper.captureFrom(graphQLContext);
try {
return snapshot.wrap(() ->
this.loader.apply(keys, environment)
.collectList()
.contextWrite(snapshot::updateContext)
.toFuture())
.call();
}
catch (Exception ex) {
return CompletableFuture.failedFuture(ex);
}
}
}
/**
* {@link MappedBatchLoaderWithContext} that delegates to a {@link Mono}
* batch loading function and exposes Reactor context to it.
*/
private static final class ReactorMappedBatchLoader<K, V> implements MappedBatchLoaderWithContext<K, V> { | private final String name;
private final BiFunction<Set<K>, BatchLoaderEnvironment, Mono<Map<K, V>>> loader;
private final Supplier<DataLoaderOptions> optionsSupplier;
private ReactorMappedBatchLoader(String name,
BiFunction<Set<K>, BatchLoaderEnvironment, Mono<Map<K, V>>> loader,
Supplier<DataLoaderOptions> optionsSupplier) {
this.name = name;
this.loader = loader;
this.optionsSupplier = optionsSupplier;
}
String getName() {
return this.name;
}
DataLoaderOptions getOptions() {
return this.optionsSupplier.get();
}
@Override
public CompletionStage<Map<K, V>> load(Set<K> keys, BatchLoaderEnvironment environment) {
GraphQLContext graphQLContext = environment.getContext();
Assert.state(graphQLContext != null, "No GraphQLContext available");
ContextSnapshot snapshot = ContextPropagationHelper.captureFrom(graphQLContext);
try {
return snapshot.wrap(() ->
this.loader.apply(keys, environment)
.contextWrite(snapshot::updateContext)
.toFuture())
.call();
}
catch (Exception ex) {
return CompletableFuture.failedFuture(ex);
}
}
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\DefaultBatchLoaderRegistry.java | 1 |
请完成以下Java代码 | public static synchronized void installDataSearchConditon(HttpServletRequest request, List<SysPermissionDataRuleModel> dataRules) {
@SuppressWarnings("unchecked")
// 1.先从request获取MENU_DATA_AUTHOR_RULES,如果存则获取到LIST
List<SysPermissionDataRuleModel> list = (List<SysPermissionDataRuleModel>)loadDataSearchConditon();
if (list==null) {
// 2.如果不存在,则new一个list
list = new ArrayList<SysPermissionDataRuleModel>();
}
for (SysPermissionDataRuleModel tsDataRule : dataRules) {
list.add(tsDataRule);
}
// 3.往list里面增量存指
request.setAttribute(MENU_DATA_AUTHOR_RULES, list);
}
/**
* 获取请求对应的数据权限规则
*
* @return
*/
@SuppressWarnings("unchecked")
public static synchronized List<SysPermissionDataRuleModel> loadDataSearchConditon() {
return (List<SysPermissionDataRuleModel>) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULES);
}
/**
* 获取请求对应的数据权限SQL
*
* @return
*/
public static synchronized String loadDataSearchConditonSqlString() {
return (String) SpringContextUtils.getHttpServletRequest().getAttribute(MENU_DATA_AUTHOR_RULE_SQL);
}
/**
* 往链接请求里面,传入数据查询条件 | *
* @param request
* @param sql
*/
public static synchronized void installDataSearchConditon(HttpServletRequest request, String sql) {
String ruleSql = (String) loadDataSearchConditonSqlString();
if (!StringUtils.hasText(ruleSql)) {
request.setAttribute(MENU_DATA_AUTHOR_RULE_SQL,sql);
}
}
/**
* 将用户信息存到request
* @param request
* @param userinfo
*/
public static synchronized void installUserInfo(HttpServletRequest request, SysUserCacheInfo userinfo) {
request.setAttribute(SYS_USER_INFO, userinfo);
}
/**
* 将用户信息存到request
* @param userinfo
*/
public static synchronized void installUserInfo(SysUserCacheInfo userinfo) {
SpringContextUtils.getHttpServletRequest().setAttribute(SYS_USER_INFO, userinfo);
}
/**
* 从request获取用户信息
* @return
*/
public static synchronized SysUserCacheInfo loadUserInfo() {
return (SysUserCacheInfo) SpringContextUtils.getHttpServletRequest().getAttribute(SYS_USER_INFO);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\util\JeecgDataAutorUtils.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o) { | return true;
}
if (getClass() != o.getClass()) {
return false;
}
Book other = (Book) o;
return Objects.equals(isbn, other.getIsbn());
}
@Override
public int hashCode() {
return Objects.hash(isbn);
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title
+ ", isbn=" + isbn + ", price=" + price + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootNaturalIdCache\src\main\java\com\bookstore\entity\Book.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getLineItemAmount() {
return lineItemAmount;
}
/**
* Sets the value of the lineItemAmount property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setLineItemAmount(BigDecimal value) {
this.lineItemAmount = value;
}
/**
* Gets the value of the listLineItemExtension property.
*
* @return
* possible object is
* {@link ListLineItemExtensionType }
*
*/
public ListLineItemExtensionType getListLineItemExtension() { | return listLineItemExtension;
}
/**
* Sets the value of the listLineItemExtension property.
*
* @param value
* allowed object is
* {@link ListLineItemExtensionType }
*
*/
public void setListLineItemExtension(ListLineItemExtensionType value) {
this.listLineItemExtension = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ListLineItemType.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http
.oauth2Login(oauth2Login ->
oauth2Login
.tokenEndpoint(tokenEndpoint ->
tokenEndpoint.accessTokenResponseClient(accessTokenResponseClient())
)
.userInfoEndpoint(userInfoEndpoint ->
userInfoEndpoint.userService(customOAuth2UserService())
)
)
.oauth2Client(oauth2Client ->
oauth2Client
.authorizationCodeGrant(codeGrant ->
codeGrant.accessTokenResponseClient(accessTokenResponseClient())
)
)
.sessionManagement(sessionManagement ->
sessionManagement.sessionCreationPolicy(SessionCreationPolicy.ALWAYS)
)
.authorizeHttpRequests(authorizeRequests -> | authorizeRequests
.requestMatchers("/unauthenticated", "/oauth2/**", "/login/**").permitAll()
.anyRequest().fullyAuthenticated()
)
.logout(logout ->
logout.logoutSuccessUrl("http://localhost:8080/realms/tom/protocol/openid-connect/logout?redirect_uri=http://localhost:8081/")
);
return http.build();
}
@Bean
public OAuth2UserService<OAuth2UserRequest, OAuth2User> customOAuth2UserService() {
return new CustomOAuth2UserService();
}
@Bean
public OAuth2AccessTokenResponseClient<OAuth2AuthorizationCodeGrantRequest> accessTokenResponseClient() {
return new DefaultAuthorizationCodeTokenResponseClient(); // 使用默认的令牌响应客户端
}
} | repos\springboot-demo-master\keycloak\src\main\java\com\et\config\SecurityConfiguration.java | 2 |
请完成以下Java代码 | public void setSourceClassName (String SourceClassName)
{
set_Value (COLUMNNAME_SourceClassName, SourceClassName);
}
/** Get Source Class.
@return Source Class Name
*/
public String getSourceClassName ()
{
return (String)get_Value(COLUMNNAME_SourceClassName);
}
/** Set Source Method.
@param SourceMethodName | Source Method Name
*/
public void setSourceMethodName (String SourceMethodName)
{
set_Value (COLUMNNAME_SourceMethodName, SourceMethodName);
}
/** Get Source Method.
@return Source Method Name
*/
public String getSourceMethodName ()
{
return (String)get_Value(COLUMNNAME_SourceMethodName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueKnown.java | 1 |
请完成以下Java代码 | public class CS_Creditpass_TransactionFrom_C_Order extends JavaProcess implements IProcessPrecondition
{
private final CreditPassTransactionService creditPassTransactionService = SpringContextHolder.instance.getBean(CreditPassTransactionService.class);
private final IOrderDAO orderDAO = Services.get(IOrderDAO.class);
@Override protected String doIt() throws Exception
{
final OrderId orderId = OrderId.ofRepoId(getRecord_ID());
final I_C_Order order = orderDAO.getById(orderId, de.metas.vertical.creditscore.creditpass.model.extended.I_C_Order.class);
final BPartnerId bPartnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID());
final String paymentRule = order.getPaymentRule();
final List<TransactionResult> transactionResults = creditPassTransactionService.getAndSaveCreditScore(paymentRule, orderId, bPartnerId);
final TransactionResult transactionResult = transactionResults.stream().findFirst().get();
if (transactionResult.getResultCodeEffective() == ResultCode.P)
{
order.setCreditpassFlag(false);
final ITranslatableString message = Services.get(IMsgBL.class).getTranslatableMsgText(CreditPassConstants.CREDITPASS_STATUS_SUCCESS_MESSAGE_KEY);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
else
{
order.setCreditpassFlag(true);
final String paymentRuleName = ADReferenceService.get().retrieveListNameTrl(X_C_Order.PAYMENTRULE_AD_Reference_ID, paymentRule);
final ITranslatableString message = Services.get(IMsgBL.class).getTranslatableMsgText(CreditPassConstants.CREDITPASS_STATUS_FAILURE_MESSAGE_KEY, paymentRuleName);
order.setCreditpassStatus(message.translate(Env.getAD_Language()));
}
save(order);
final List<Integer> tableRecordReferences = transactionResults.stream()
.map(tr -> tr.getTransactionResultId().getRepoId())
.collect(Collectors.toList());
getResult().setRecordsToOpen(I_CS_Transaction_Result.Table_Name, tableRecordReferences, null);
return MSG_OK;
}
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
} | if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final OrderId orderId = OrderId.ofRepoId(context.getSingleSelectedRecordId());
final I_C_Order order = orderDAO.getById(orderId, de.metas.vertical.creditscore.creditpass.model.extended.I_C_Order.class);
if (order.getC_BPartner_ID() < 0)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("The order has no business partner");
}
if (!order.getCreditpassFlag())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Creditpass request not needed");
}
return ProcessPreconditionsResolution.accept();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java\de\metas\vertical\creditscore\creditpass\process\CS_Creditpass_TransactionFrom_C_Order.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BPartnerBankAccountId implements RepoIdAware
{
int repoId;
@NonNull
BPartnerId bpartnerId;
public static BPartnerBankAccountId ofRepoId(@NonNull final BPartnerId bpartnerId, final int bpBankAccountId)
{
return new BPartnerBankAccountId(bpartnerId, bpBankAccountId);
}
public static BPartnerBankAccountId ofRepoId(final int bpartnerId, final int bpBankAccountId)
{
return new BPartnerBankAccountId(BPartnerId.ofRepoId(bpartnerId), bpBankAccountId);
}
public static BPartnerBankAccountId ofRepoIdOrNull(
@Nullable final Integer bpartnerId,
@Nullable final Integer bpBankAccountId)
{
return bpartnerId != null && bpartnerId > 0 && bpBankAccountId != null && bpBankAccountId > 0
? ofRepoId(bpartnerId, bpBankAccountId)
: null;
}
public static BPartnerBankAccountId ofRepoIdOrNull( | @Nullable final BPartnerId bpartnerId,
final int bpBankAccountId)
{
return bpartnerId != null && bpBankAccountId > 0 ? ofRepoId(bpartnerId, bpBankAccountId) : null;
}
private BPartnerBankAccountId(@NonNull final BPartnerId bpartnerId, final int bpBankAccountId)
{
this.repoId = Check.assumeGreaterThanZero(bpBankAccountId, "C_BP_BankAccount_ID");
this.bpartnerId = bpartnerId;
}
public static int toRepoId(@Nullable final BPartnerBankAccountId id)
{
return id != null ? id.getRepoId() : -1;
}
public static boolean equals(@Nullable final BPartnerBankAccountId id1, @Nullable final BPartnerBankAccountId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerBankAccountId.java | 2 |
请完成以下Java代码 | private static final ITranslatableString buildMsg(final String attributeStr, final Object attributeSetObj)
{
final TranslatableStringBuilder builder = TranslatableStrings.builder();
builder.append("Attribute ");
if (attributeStr == null)
{
builder.append("<NULL>");
}
else
{
builder.append("'").append(attributeStr).append("'");
}
builder.append(" was not found");
if (attributeSetObj != null)
{
builder.append(" for ").append(attributeSetObj.toString()); | }
return builder.build();
}
public I_M_Attribute getM_Attribute()
{
return attribute;
}
public IAttributeSet getAttributeSet()
{
return attributeSet;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\exceptions\AttributeNotFoundException.java | 1 |
请完成以下Java代码 | public Collection<String> getFunctionNames() {
Collection<String> functionNames = new LinkedHashSet<>();
for (String functionPrefix : prefixes()) {
for (String functionNameOption : localNames()) {
functionNames.add(functionPrefix + ":" + functionNameOption);
}
}
return functionNames;
}
@Override
public AstFunction createFunction(String name, int index, AstParameters parameters, boolean varargs, FlowableExpressionParser parser) {
Method method = functionMethod();
int parametersCardinality = parameters.getCardinality();
int methodParameterCount = method.getParameterCount();
if (method.isVarArgs() || parametersCardinality < methodParameterCount) {
// If the method is a varargs or the number of parameters is less than the defined in the method
// then create an identifier for the variableContainer
// and analyze the parameters
List<AstNode> newParameters = new ArrayList<>(parametersCardinality + 1);
newParameters.add(parser.createIdentifier(variableScopeName));
if (methodParameterCount >= 1) {
// If the first parameter is an identifier we have to convert it to a text node
// We want to allow writing variables:get(varName) where varName is without quotes
newParameters.add(createVariableNameNode(parameters.getChild(0)));
for (int i = 1; i < parametersCardinality; i++) { | // the rest of the parameters should be treated as is
newParameters.add(parameters.getChild(i));
}
}
return new AstFunction(name, index, new AstParameters(newParameters), varargs);
} else {
// If the resolved parameters are of the same size as the current method then nothing to do
return new AstFunction(name, index, parameters, varargs);
}
}
protected AstNode createVariableNameNode(AstNode variableNode) {
if (variableNode instanceof AstIdentifier) {
return new AstText(((AstIdentifier) variableNode).getName());
} else {
return variableNode;
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\el\function\AbstractFlowableVariableExpressionFunction.java | 1 |
请完成以下Java代码 | public String getWay() {
return way;
}
public void setWay(String way) {
this.way = way;
}
/** 描述 */
private String desc;
private PayTypeEnum(String way,String desc) {
this.desc = desc;
this.way = way;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public static Map<String, Map<String, Object>> toMap() {
PayTypeEnum[] ary = PayTypeEnum.values();
Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>();
for (int num = 0; num < ary.length; num++) {
Map<String, Object> map = new HashMap<String, Object>();
String key = ary[num].name();
map.put("desc", ary[num].getDesc());
enumMap.put(key, map);
}
return enumMap;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List toList() {
PayTypeEnum[] ary = PayTypeEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("desc", ary[i].getDesc());
map.put("name", ary[i].name());
list.add(map);
}
return list;
}
public static PayTypeEnum getEnum(String name) {
PayTypeEnum[] arry = PayTypeEnum.values();
for (int i = 0; i < arry.length; i++) {
if (arry[i].name().equalsIgnoreCase(name)) {
return arry[i];
}
}
return null;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List getWayList(String way) {
PayTypeEnum[] ary = PayTypeEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) { | if(ary[i].way.equals(way)){
Map<String, String> map = new HashMap<String, String>();
map.put("desc", ary[i].getDesc());
map.put("name", ary[i].name());
list.add(map);
}
}
return list;
}
/**
* 取枚举的json字符串
*
* @return
*/
public static String getJsonStr() {
PayTypeEnum[] enums = PayTypeEnum.values();
StringBuffer jsonStr = new StringBuffer("[");
for (PayTypeEnum senum : enums) {
if (!"[".equals(jsonStr.toString())) {
jsonStr.append(",");
}
jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}");
}
jsonStr.append("]");
return jsonStr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\enums\PayTypeEnum.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int hashCode() {
return Objects.hash(gender, title, name, address, additionalAddress, additionalAddress2, postalCode, city);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class OrderDeliveryAddress {\n");
sb.append(" gender: ").append(toIndentedString(gender)).append("\n");
sb.append(" title: ").append(toIndentedString(title)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" address: ").append(toIndentedString(address)).append("\n");
sb.append(" additionalAddress: ").append(toIndentedString(additionalAddress)).append("\n");
sb.append(" additionalAddress2: ").append(toIndentedString(additionalAddress2)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n"); | sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-orders-api\src\main\java\io\swagger\client\model\OrderDeliveryAddress.java | 2 |
请完成以下Java代码 | public CashAccountSEPA2 getOrgnlDbtrAcct() {
return orgnlDbtrAcct;
}
/**
* Sets the value of the orgnlDbtrAcct property.
*
* @param value
* allowed object is
* {@link CashAccountSEPA2 }
*
*/
public void setOrgnlDbtrAcct(CashAccountSEPA2 value) {
this.orgnlDbtrAcct = value;
}
/**
* Gets the value of the orgnlDbtrAgt property.
*
* @return
* possible object is
* {@link BranchAndFinancialInstitutionIdentificationSEPA2 }
*
*/ | public BranchAndFinancialInstitutionIdentificationSEPA2 getOrgnlDbtrAgt() {
return orgnlDbtrAgt;
}
/**
* Sets the value of the orgnlDbtrAgt property.
*
* @param value
* allowed object is
* {@link BranchAndFinancialInstitutionIdentificationSEPA2 }
*
*/
public void setOrgnlDbtrAgt(BranchAndFinancialInstitutionIdentificationSEPA2 value) {
this.orgnlDbtrAgt = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\AmendmentInformationDetailsSDD.java | 1 |
请完成以下Java代码 | public final void setClazz(final Class<T> clazzToSet) {
clazz = Preconditions.checkNotNull(clazzToSet);
}
// API
public T findOne(final long id) {
return (T) getCurrentSession().get(clazz, id);
}
public List<T> findAll() {
return getCurrentSession().createQuery("from " + clazz.getName()).list();
}
public T create(final T entity) {
Preconditions.checkNotNull(entity);
getCurrentSession().saveOrUpdate(entity);
return entity;
}
public T update(final T entity) {
Preconditions.checkNotNull(entity);
return (T) getCurrentSession().merge(entity);
} | public void delete(final T entity) {
Preconditions.checkNotNull(entity);
getCurrentSession().delete(entity);
}
public void deleteById(final long entityId) {
final T entity = findOne(entityId);
Preconditions.checkState(entity != null);
delete(entity);
}
protected Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
} | repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\spring\hibernate\AbstractHibernateDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SpringBootAdminServletApplication {
private static final Logger log = LoggerFactory.getLogger(SpringBootAdminServletApplication.class);
public static void main(String[] args) {
SpringApplication app = new SpringApplication(SpringBootAdminServletApplication.class);
app.setApplicationStartup(new BufferingApplicationStartup(1500));
app.run(args);
}
@Bean
public CacheManager cacheManager() {
return new ConcurrentMapCacheManager("books");
}
// tag::customization-instance-exchange-filter-function[]
@Bean
public InstanceExchangeFilterFunction auditLog() {
return (instance, request, next) -> next.exchange(request).doOnSubscribe((s) -> {
if (HttpMethod.DELETE.equals(request.method()) || HttpMethod.POST.equals(request.method())) {
log.info("{} for {} on {}", request.method(), instance.getId(), request.url());
}
});
}
// end::customization-instance-exchange-filter-function[]
@Bean
public CustomNotifier customNotifier(InstanceRepository repository) {
return new CustomNotifier(repository);
}
@Bean
public CustomEndpoint customEndpoint() {
return new CustomEndpoint(); | }
// tag::customization-http-headers-providers[]
@Bean
public HttpHeadersProvider customHttpHeadersProvider() {
return (instance) -> {
HttpHeaders httpHeaders = new HttpHeaders();
httpHeaders.add("X-CUSTOM", "My Custom Value");
return httpHeaders;
};
}
// end::customization-http-headers-providers[]
@Bean
public HttpExchangeRepository httpTraceRepository() {
return new InMemoryHttpExchangeRepository();
}
@Bean
public AuditEventRepository auditEventRepository() {
return new InMemoryAuditEventRepository();
}
@Bean
public EmbeddedDatabase dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.HSQL)
.addScript("org/springframework/session/jdbc/schema-hsqldb.sql")
.build();
}
} | repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-servlet\src\main\java\de\codecentric\boot\admin\sample\SpringBootAdminServletApplication.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class EmployeeServicesWithKeyValueTemplate implements EmployeeService {
@Autowired
@Qualifier("keyValueTemplate")
KeyValueTemplate keyValueTemplate;
@Override
public void save(Employee employee) {
keyValueTemplate.insert(employee);
}
@Override
public Optional<Employee> get(Integer id) {
return keyValueTemplate.findById(id, Employee.class);
}
@Override
public Iterable<Employee> fetchAll() {
return keyValueTemplate.findAll(Employee.class);
}
@Override
public void update(Employee employee) {
keyValueTemplate.update(employee); | }
@Override
public void delete(Integer id) {
keyValueTemplate.delete(id, Employee.class);
}
@Override
public Iterable<Employee> getSortedListOfEmployeesBySalary() {
KeyValueQuery query = new KeyValueQuery();
query.setSort(Sort.by(Sort.Direction.DESC, "salary"));
return keyValueTemplate.find(query, Employee.class);
}
} | repos\tutorials-master\persistence-modules\spring-data-keyvalue\src\main\java\com\baeldung\spring\data\keyvalue\services\impl\EmployeeServicesWithKeyValueTemplate.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Class<? extends BatchPartEntity> getManagedEntityClass() {
return BatchPartEntityImpl.class;
}
@Override
public BatchPartEntity create() {
return new BatchPartEntityImpl();
}
@Override
@SuppressWarnings("unchecked")
public List<BatchPart> findBatchPartsByBatchId(String batchId) {
HashMap<String, Object> params = new HashMap<>();
params.put("batchId", batchId);
return getDbSqlSession().selectList("selectBatchPartsByBatchId", params);
}
@Override
@SuppressWarnings("unchecked")
public List<BatchPart> findBatchPartsByBatchIdAndStatus(String batchId, String status) {
HashMap<String, Object> params = new HashMap<>();
params.put("batchId", batchId);
params.put("status", status);
return getDbSqlSession().selectList("selectBatchPartsByBatchIdAndStatus", params);
}
@Override
@SuppressWarnings("unchecked")
public List<BatchPart> findBatchPartsByScopeIdAndType(String scopeId, String scopeType) {
HashMap<String, Object> params = new HashMap<>();
params.put("scopeId", scopeId);
params.put("scopeType", scopeType); | return getDbSqlSession().selectList("selectBatchPartsByScopeIdAndScopeType", params);
}
@Override
@SuppressWarnings("unchecked")
public List<BatchPart> findBatchPartsByQueryCriteria(BatchPartQueryImpl batchPartQuery) {
return getDbSqlSession().selectList("selectBatchPartsByQueryCriteria", batchPartQuery, getManagedEntityClass());
}
@Override
public long findBatchPartCountByQueryCriteria(BatchPartQueryImpl batchPartQuery) {
return (Long) getDbSqlSession().selectOne("selectBatchPartCountByQueryCriteria", batchPartQuery);
}
@Override
protected IdGenerator getIdGenerator() {
return batchServiceConfiguration.getIdGenerator();
}
} | repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\data\impl\MybatisBatchPartDataManager.java | 2 |
请完成以下Java代码 | public final class BearerTokenError extends OAuth2Error {
@Serial
private static final long serialVersionUID = 4521118368930341766L;
private final HttpStatus httpStatus;
private final String scope;
/**
* Create a {@code BearerTokenError} using the provided parameters
* @param errorCode the error code
* @param httpStatus the HTTP status
*/
public BearerTokenError(String errorCode, HttpStatus httpStatus, String description, String errorUri) {
this(errorCode, httpStatus, description, errorUri, null);
}
/**
* Create a {@code BearerTokenError} using the provided parameters
* @param errorCode the error code
* @param httpStatus the HTTP status
* @param description the description
* @param errorUri the URI
* @param scope the scope
*/
public BearerTokenError(String errorCode, HttpStatus httpStatus, String description, String errorUri,
String scope) {
super(errorCode, description, errorUri);
Assert.notNull(httpStatus, "httpStatus cannot be null");
Assert.isTrue(isDescriptionValid(description),
"description contains invalid ASCII characters, it must conform to RFC 6750");
Assert.isTrue(isErrorCodeValid(errorCode),
"errorCode contains invalid ASCII characters, it must conform to RFC 6750");
Assert.isTrue(isErrorUriValid(errorUri),
"errorUri contains invalid ASCII characters, it must conform to RFC 6750");
Assert.isTrue(isScopeValid(scope), "scope contains invalid ASCII characters, it must conform to RFC 6750");
this.httpStatus = httpStatus;
this.scope = scope;
}
/**
* Return the HTTP status.
* @return the HTTP status
*/
public HttpStatus getHttpStatus() {
return this.httpStatus;
}
/**
* Return the scope.
* @return the scope
*/
public String getScope() {
return this.scope;
} | private static boolean isDescriptionValid(String description) {
// @formatter:off
return description == null || description.chars().allMatch((c) ->
withinTheRangeOf(c, 0x20, 0x21) ||
withinTheRangeOf(c, 0x23, 0x5B) ||
withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:on
}
private static boolean isErrorCodeValid(String errorCode) {
// @formatter:off
return errorCode.chars().allMatch((c) ->
withinTheRangeOf(c, 0x20, 0x21) ||
withinTheRangeOf(c, 0x23, 0x5B) ||
withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:on
}
private static boolean isErrorUriValid(String errorUri) {
return errorUri == null || errorUri.chars()
.allMatch((c) -> c == 0x21 || withinTheRangeOf(c, 0x23, 0x5B) || withinTheRangeOf(c, 0x5D, 0x7E));
}
private static boolean isScopeValid(String scope) {
// @formatter:off
return scope == null || scope.chars().allMatch((c) ->
withinTheRangeOf(c, 0x20, 0x21) ||
withinTheRangeOf(c, 0x23, 0x5B) ||
withinTheRangeOf(c, 0x5D, 0x7E));
// @formatter:on
}
private static boolean withinTheRangeOf(int c, int min, int max) {
return c >= min && c <= max;
}
} | repos\spring-security-main\oauth2\oauth2-resource-server\src\main\java\org\springframework\security\oauth2\server\resource\BearerTokenError.java | 1 |
请完成以下Java代码 | public ReportResultData createCSV_FileForSSCC18_Labels( final Collection<EDIDesadvPackId> desadvPackIds,
final ZebraConfigId zebraConfigId,
final PInstanceId pInstanceId )
{
final ZebraConfigId zebraConfigToUse = zebraConfigId != null ? zebraConfigId : zebraConfigRepository.getDefaultZebraConfigId();
final I_AD_Zebra_Config zebraConfig = zebraConfigRepository.getById(zebraConfigToUse);
DB.createT_Selection(pInstanceId, desadvPackIds, ITrx.TRXNAME_ThreadInherited);
final ImmutableList<List<String>> resultRows = DB.getSQL_ResultRowsAsListsOfStrings(zebraConfig.getSQL_Select(),
Collections.singletonList(pInstanceId), ITrx.TRXNAME_ThreadInherited);
Check.assumeNotEmpty(resultRows, "SSCC information records must be available!");
final StringBuilder ssccLabelsInformationAsCSV = new StringBuilder(zebraConfig.getHeader_Line1());
ssccLabelsInformationAsCSV.append("\n").append(zebraConfig.getHeader_Line2());
final Joiner joiner = Joiner.on(",");
resultRows.stream()
.map(row -> row.stream().map(this::escapeCSV).collect(Collectors.toList()))
.map(joiner::join)
.forEach(row -> ssccLabelsInformationAsCSV.append("\n").append(row));
return buildResult(ssccLabelsInformationAsCSV.toString(), zebraConfig.getEncoding());
} | private String escapeCSV(final String valueToEscape)
{
final String escapedQuote = "\"";
return escapedQuote
+ StringUtils.nullToEmpty(valueToEscape).replace(escapedQuote, escapedQuote + escapedQuote)
+ escapedQuote;
}
private ReportResultData buildResult(final String fileData, final String fileEncoding)
{
final byte[] fileDataBytes = fileData.getBytes(Charset.forName(fileEncoding));
return ReportResultData.builder()
.reportData(new ByteArrayResource(fileDataBytes))
.reportFilename(SSCC18_FILE_NAME_TEMPLATE.replace(TIMESTAMP_PLACEHOLDER, String.valueOf(System.currentTimeMillis())))
.reportContentType(CSV_FORMAT)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\api\ZebraPrinterService.java | 1 |
请完成以下Java代码 | public int characteristics()
{
return source.characteristics();
}
private static final class GroupCollector<E>
{
private final Object classifierValue;
private final ImmutableList.Builder<E> items = ImmutableList.builder();
public GroupCollector(final Object classifierValue)
{
this.classifierValue = classifierValue;
}
public boolean isMatchingClassifier(final Object classifierValueToMatch) | {
return Objects.equals(this.classifierValue, classifierValueToMatch);
}
public void collect(final E item)
{
items.add(item);
}
public List<E> finish()
{
return items.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\GroupByClassifierSpliterator.java | 1 |
请完成以下Java代码 | private boolean isAlreadyExisting(final int currentId, final int productPriceId, final BigDecimal qty, final String trxName)
{
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(SQL_SELECT_EXISTING, trxName);
pstmt.setInt(1, productPriceId);
pstmt.setBigDecimal(2, qty);
rs = pstmt.executeQuery();
if (rs.next())
{
final int existingId = rs.getInt(1);
if (existingId == currentId)
{
// there is already a scaleprice in the DB, but it is the
// one we are currently validating.
return false;
} | // there is a different scalePrice with the same priceList and
// quantity.
return true;
}
return false;
}
catch (SQLException e)
{
final String msg = "Unable to check if a M_ProductScalePrice for M_ProductPrice with id "
+ productPriceId + " and quantity " + qty + " already exists";
MetasfreshLastError.saveError(logger, msg, e);
throw new DBException(msg, e);
}
finally
{
DB.close(pstmt);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\modelvalidator\MProductScalePriceValidator.java | 1 |
请完成以下Java代码 | default boolean isFieldEmpty(@NonNull final String fieldName) {return getFieldNameAndJsonValues().isEmpty(fieldName);}
default Map<String, DocumentFieldWidgetType> getWidgetTypesByFieldName()
{
return ImmutableMap.of();
}
default Map<String, ViewEditorRenderMode> getViewEditorRenderModeByFieldName()
{
return ImmutableMap.of();
}
//
// Included documents (children)
// @formatter:off
default Collection<? extends IViewRow> getIncludedRows() { return ImmutableList.of(); }
// @formatter:on
//
// Attributes
// @formatter:off
default boolean hasAttributes() { return false; }
default IViewRowAttributes getAttributes() { throw new EntityNotFoundException("Row does not support attributes"); }
// @formatter:on
//
// IncludedView
// @formatter:off
default ViewId getIncludedViewId() { return null; }
// @formatter:on
//
// Single column row
// @formatter:off
/** @return true if frontend shall display one single column */ | default boolean isSingleColumn() { return false; }
/** @return text to be displayed if {@link #isSingleColumn()} */
default ITranslatableString getSingleColumnCaption() { return TranslatableStrings.empty(); }
// @formatter:on
/**
* @return a stream of given row and all it's included rows recursively
*/
default Stream<IViewRow> streamRecursive()
{
return this.getIncludedRows()
.stream()
.map(IViewRow::streamRecursive)
.reduce(Stream.of(this), Stream::concat);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\IViewRow.java | 1 |
请完成以下Java代码 | public WorkPackageQuery setReadyForProcessing(final Boolean readyForProcessing)
{
this.readyForProcessing = readyForProcessing;
return this;
}
/*
* (non-Javadoc)
*
* @see de.metas.async.api.IWorkPackageQuery#getError()
*/
@Override
public Boolean getError()
{
return error;
}
/**
* @param error the error to set
*/
public void setError(final Boolean error)
{
this.error = error;
}
/*
* (non-Javadoc)
*
* @see de.metas.async.api.IWorkPackageQuery#getSkippedTimeoutMillis()
*/
@Override
public long getSkippedTimeoutMillis()
{
return skippedTimeoutMillis;
}
/**
* @param skippedTimeoutMillis the skippedTimeoutMillis to set
*/
public void setSkippedTimeoutMillis(final long skippedTimeoutMillis)
{
Check.assume(skippedTimeoutMillis >= 0, "skippedTimeoutMillis >= 0");
this.skippedTimeoutMillis = skippedTimeoutMillis;
}
/*
* (non-Javadoc)
*
* @see de.metas.async.api.IWorkPackageQuery#getPackageProcessorIds()
*/
@Override
@Nullable
public Set<QueuePackageProcessorId> getPackageProcessorIds()
{
return packageProcessorIds;
}
/**
* @param packageProcessorIds the packageProcessorIds to set
*/
public void setPackageProcessorIds(@Nullable final Set<QueuePackageProcessorId> packageProcessorIds)
{
if (packageProcessorIds != null)
{
Check.assumeNotEmpty(packageProcessorIds, "packageProcessorIds cannot be empty!");
} | this.packageProcessorIds = packageProcessorIds;
}
/*
* (non-Javadoc)
*
* @see de.metas.async.api.IWorkPackageQuery#getPriorityFrom()
*/
@Override
public String getPriorityFrom()
{
return priorityFrom;
}
/**
* @param priorityFrom the priorityFrom to set
*/
public void setPriorityFrom(final String priorityFrom)
{
this.priorityFrom = priorityFrom;
}
@Override
public String toString()
{
return "WorkPackageQuery ["
+ "processed=" + processed
+ ", readyForProcessing=" + readyForProcessing
+ ", error=" + error
+ ", skippedTimeoutMillis=" + skippedTimeoutMillis
+ ", packageProcessorIds=" + packageProcessorIds
+ ", priorityFrom=" + priorityFrom
+ "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageQuery.java | 1 |
请完成以下Java代码 | private CurrencyId getDocumentCurrencyId(final I_C_PaySelectionLine paySelectionLine)
{
final InvoiceId invoiceId = InvoiceId.ofRepoIdOrNull(paySelectionLine.getC_Invoice_ID());
final OrderId orderId = OrderId.ofRepoIdOrNull(paySelectionLine.getC_Order_ID());
if (invoiceId != null)
{
final I_C_Invoice invoice = invoiceBL.getById(invoiceId);
return CurrencyId.ofRepoId(invoice.getC_Currency_ID());
}
else if (orderId != null)
{
final I_C_Order order = orderBL.getById(orderId);
return CurrencyId.ofRepoId(order.getC_Currency_ID());
}
else
{
throw new AdempiereException("No invoice or order found for " + paySelectionLine);
}
} | @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_AFTER_DELETE })
public void afterNewOrChangeOrDelete(final I_C_PaySelectionLine paySelectionLine)
{
updatePaySelectionAmount(paySelectionLine);
}
private void updatePaySelectionAmount(@NonNull final I_C_PaySelectionLine paySelectionLine)
{
final PaySelectionId paySelectionId = PaySelectionId.ofRepoId(paySelectionLine.getC_PaySelection_ID());
paySelectionDAO.updatePaySelectionTotalAmt(paySelectionId);
// make sure the is invalidated *after* the change is visible for everyone
trxManager
.getCurrentTrxListenerManagerOrAutoCommit()
.runAfterCommit(() -> modelCacheInvalidationService.invalidate(
CacheInvalidateMultiRequest.fromTableNameAndRecordId(I_C_PaySelection.Table_Name, paySelectionId.getRepoId()),
ModelCacheInvalidationTiming.AFTER_CHANGE));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\modelvalidator\C_PaySelectionLine.java | 1 |
请完成以下Java代码 | DataBlock getData() {
return this.data;
}
@Override
public void run() {
releaseAll();
}
private void releaseAll() {
IOException exception = null;
try {
this.data.close();
}
catch (IOException ex) {
exception = ex;
}
try { | this.zipContent.close();
}
catch (IOException ex) {
if (exception != null) {
ex.addSuppressed(exception);
}
exception = ex;
}
if (exception != null) {
throw new UncheckedIOException(exception);
}
}
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedByteChannel.java | 1 |
请完成以下Java代码 | SingleArticleResponse getArticle(AuthToken readersToken, @PathVariable String slug) {
var article = articleService.getArticle(slug);
if (this.isAnonymousUser(readersToken)) {
return new SingleArticleResponse(articleService.getArticleDetails(article));
}
var reader = userService.getUser(readersToken.userId());
return new SingleArticleResponse(articleService.getArticleDetails(reader, article));
}
@PutMapping("/api/articles/{slug}")
SingleArticleResponse updateArticle(
AuthToken authorsToken, @PathVariable String slug, @RequestBody EditArticleRequest request) {
var author = userService.getUser(authorsToken.userId());
var article = articleService.getArticle(slug);
if (request.article().title() != null) {
article =
articleService.editTitle(author, article, request.article().title());
}
if (request.article().description() != null) {
article = articleService.editDescription(
author, article, request.article().description());
}
if (request.article().body() != null) {
article = articleService.editContent(
author, article, request.article().body());
} | return new SingleArticleResponse(articleService.getArticleDetails(author, article));
}
@DeleteMapping("/api/articles/{slug}")
void deleteArticle(AuthToken authorsToken, @PathVariable String slug) {
var author = userService.getUser(authorsToken.userId());
var article = articleService.getArticle(slug);
articleService.delete(author, article);
}
@GetMapping("/api/articles/feed")
MultipleArticlesResponse getArticleFeeds(
AuthToken readersToken, // Must be verified
@RequestParam(value = "offset", required = false, defaultValue = "0") int offset,
@RequestParam(value = "limit", required = false, defaultValue = "20") int limit) {
var reader = userService.getUser(readersToken.userId());
var facets = new ArticleFacets(offset, limit);
var articleDetails = articleService.getFeeds(reader, facets);
return this.getArticlesResponse(articleDetails);
}
private MultipleArticlesResponse getArticlesResponse(List<ArticleDetails> articles) {
return articles.stream()
.map(ArticleResponse::new)
.collect(collectingAndThen(toList(), MultipleArticlesResponse::new));
}
} | repos\realworld-java21-springboot3-main\server\api\src\main\java\io\zhc1\realworld\api\ArticleController.java | 1 |
请完成以下Java代码 | public class DeleteHistoricVariableInstanceCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
private String variableInstanceId;
public DeleteHistoricVariableInstanceCmd(String variableInstanceId) {
this.variableInstanceId = variableInstanceId;
}
@Override
public Void execute(CommandContext commandContext) {
ensureNotEmpty(BadUserRequestException.class,"variableInstanceId", variableInstanceId);
HistoricVariableInstanceEntity variable = commandContext.getHistoricVariableInstanceManager().findHistoricVariableInstanceByVariableInstanceId(variableInstanceId);
ensureNotNull(NotFoundException.class, "No historic variable instance found with id: " + variableInstanceId, "variable", variable);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkDeleteHistoricVariableInstance(variable);
}
commandContext
.getHistoricDetailManager()
.deleteHistoricDetailsByVariableInstanceId(variableInstanceId);
commandContext
.getHistoricVariableInstanceManager()
.deleteHistoricVariableInstanceByVariableInstanceId(variableInstanceId); | // create user operation log
ResourceDefinitionEntity<?> definition = null;
try {
if (variable.getProcessDefinitionId() != null) {
definition = commandContext.getProcessEngineConfiguration().getDeploymentCache().findDeployedProcessDefinitionById(variable.getProcessDefinitionId());
} else if (variable.getCaseDefinitionId() != null) {
definition = commandContext.getProcessEngineConfiguration().getDeploymentCache().findDeployedCaseDefinitionById(variable.getCaseDefinitionId());
}
} catch (NotFoundException e) {
// definition has been deleted already
}
commandContext.getOperationLogManager().logHistoricVariableOperation(
UserOperationLogEntry.OPERATION_TYPE_DELETE_HISTORY, variable, definition, new PropertyChange("name", null, variable.getName()));
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\DeleteHistoricVariableInstanceCmd.java | 1 |
请完成以下Java代码 | public Serializable getIdentifier() {
return this.identifier;
}
@Override
public String getType() {
return this.type;
}
/**
* Important so caching operates properly.
* @return the hash
*/
@Override
public int hashCode() { | int result = this.type.hashCode();
result = 31 * result + this.identifier.hashCode();
return result;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(this.getClass().getName()).append("[");
sb.append("Type: ").append(this.type);
sb.append("; Identifier: ").append(this.identifier).append("]");
return sb.toString();
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\ObjectIdentityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HUQRCodeAssignment
{
@NonNull
public static HUQRCodeAssignment of(@NonNull final HUQRCodeUniqueId id, @NonNull final Collection<HuId> huIds)
{
return new HUQRCodeAssignment(id, huIds);
}
@NonNull HUQRCodeUniqueId id;
@NonNull ImmutableSet<HuId> huIds;
private HUQRCodeAssignment(@NonNull final HUQRCodeUniqueId id, @NonNull final Collection<HuId> huIds)
{
if (huIds.isEmpty())
{
throw new AdempiereException("huIds cannot be empty!")
.appendParametersToMessage()
.setParameter("HUQRCodeUniqueId", id);
}
this.id = id;
this.huIds = ImmutableSet.copyOf(huIds);
}
@NonNull
public HuId getSingleHUId()
{
Check.assume(huIds.size() == 1, "Expecting only one HU assigned to qrCode=" + id.getAsString()); | return huIds.iterator().next();
}
public boolean isAssignedToHuId(@NonNull final HuId huId)
{
return huIds.contains(huId);
}
@NonNull
public ImmutableSet<HuId> returnNotAssignedHUs(@NonNull final Set<HuId> huIdsToCheck)
{
return huIdsToCheck.stream()
.filter(huId -> !isAssignedToHuId(huId))
.collect(ImmutableSet.toImmutableSet());
}
public boolean isSingleHUAssigned()
{
return huIds.size() == 1;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\HUQRCodeAssignment.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void configure(StateMachineConfigurationConfigurer<String, String> config)
throws Exception {
config
.withConfiguration()
.autoStartup(true)
.listener(new StateMachineListener());
}
@Override
public void configure(StateMachineStateConfigurer<String, String> states) throws Exception {
states
.withStates()
.initial("SI")
.state("SI")
.end("SF")
.and()
.withStates() | .parent("SI")
.initial("SUB1")
.state("SUB2")
.end("SUBEND");
}
@Override
public void configure(StateMachineTransitionConfigurer<String, String> transitions) throws Exception {
transitions.withExternal()
.source("SI").target("SF").event("end")
.and().withExternal()
.source("SUB1").target("SUB2").event("se1")
.and().withExternal()
.source("SUB2").target("SUBEND").event("s-end");
}
} | repos\tutorials-master\spring-state-machine\src\main\java\com\baeldung\spring\statemachine\config\HierarchicalStateMachineConfiguration.java | 2 |
请完成以下Java代码 | public CommandExecutor getCommandExecutor() {
return commandExecutor;
}
public ProcessInstanceQuery getProcessInstanceQuery() {
return processInstanceQuery;
}
public HistoricProcessInstanceQuery getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public List<String> getProcessInstanceIds() {
return processInstanceIds;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public List<AbstractProcessInstanceModificationCommand> getInstructions() {
return instructions;
}
public void setInstructions(List<AbstractProcessInstanceModificationCommand> instructions) {
this.instructions = instructions; | }
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public boolean isSkipIoMappings() {
return skipIoMappings;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotationInternal(String annotation) {
this.annotation = annotation;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ModificationBuilderImpl.java | 1 |
请完成以下Java代码 | public static String determineSignalName(CommandContext commandContext, SignalEventDefinition signalEventDefinition, BpmnModel bpmnModel, DelegateExecution execution) {
String signalName = null;
if (StringUtils.isNotEmpty(signalEventDefinition.getSignalRef())) {
Signal signal = bpmnModel.getSignal(signalEventDefinition.getSignalRef());
if (signal != null) {
signalName = signal.getName();
} else {
signalName = signalEventDefinition.getSignalRef();
}
} else {
signalName = signalEventDefinition.getSignalExpression();
}
if (StringUtils.isNotEmpty(signalName)) {
Expression expression = CommandContextUtil.getProcessEngineConfiguration(commandContext).getExpressionManager().createExpression(signalName);
return expression.getValue(execution != null ? execution : NoExecutionVariableScope.getSharedInstance()).toString();
}
return signalName;
}
/**
* Determines the event name of the {@link org.flowable.bpmn.model.MessageEventDefinition} that is passed:
* - if a message ref is set, it has precedence
* - if a messageExpression is set, it is returned
* | * Note that, contrary to the determineSignalName method, the name of the message is never used.
* This is because of historical reasons (and it can't be changed now without breaking existing models/instances)
*/
public static String determineMessageName(CommandContext commandContext, MessageEventDefinition messageEventDefinition, DelegateExecution execution) {
String messageName = null;
if (StringUtils.isNotEmpty(messageEventDefinition.getMessageRef())) {
return messageEventDefinition.getMessageRef();
} else {
messageName = messageEventDefinition.getMessageExpression();
}
if (StringUtils.isNotEmpty(messageName)) {
Expression expression = CommandContextUtil.getProcessEngineConfiguration(commandContext).getExpressionManager().createExpression(messageName);
return expression.getValue(execution != null ? execution : NoExecutionVariableScope.getSharedInstance()).toString();
}
return messageName;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\event\EventDefinitionExpressionUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InfinispanAnnotatedCacheService {
public static final String CACHE_NAME = "anotherCache";
@CacheName(CACHE_NAME)
@Inject
Cache anotherCache;
@Embedded(CACHE_NAME)
@Inject
org.infinispan.Cache<String, String> embeddedCache;
@CacheResult(cacheName = CACHE_NAME)
String getValueFromCache(String key) {
// simulate a long running computation
try {
System.out.println("getting value for "+ key);
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace(System.err);
}
return key + "Value";
}
public org.infinispan.Cache<String, String> getEmbeddedCache() {
return embeddedCache;
}
public Cache getQuarkusCache() {
return anotherCache;
}
@CacheInvalidateAll(cacheName = CACHE_NAME) | public void clearAll() {
// simulate a long running computation
try {
System.out.println("clearing cache " + CACHE_NAME);
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@CacheInvalidate(cacheName = CACHE_NAME)
public void clear(String key) {
}
} | repos\tutorials-master\quarkus-modules\quarkus-infinispan-embedded\src\main\java\com\baeldung\quarkus\infinispan\InfinispanAnnotatedCacheService.java | 2 |
请完成以下Java代码 | protected @NonNull PdxInstance adapt(@NonNull Object target) {
return ObjectPdxInstanceAdapter.from(target);
}
/**
* Converts the given {@link String JSON} into a {@link Object} and then adapts the {@link Object}
* as a {@link PdxInstance}.
*
* @param json {@link String JSON} to convert into an {@link Object} into PDX.
* @return a {@link PdxInstance} converted from the given {@link String JSON}.
* @see org.apache.geode.pdx.PdxInstance
* @see #getJsonToObjectConverter()
* @see #adapt(Object)
*/
protected @NonNull PdxInstance convertJsonToObjectToPdx(@NonNull String json) {
return adapt(getJsonToObjectConverter().convert(json));
}
/**
* Converts the given {@link String JSON} to {@link PdxInstance PDX}.
*
* @param json {@link String} containing JSON to convert to PDX; must not be {@literal null}.
* @return JSON for the given {@link PdxInstance PDX}.
* @see org.apache.geode.pdx.PdxInstance
* @see #jsonFormatterFromJson(String)
* @see #wrap(PdxInstance)
*/
protected @NonNull PdxInstance convertJsonToPdx(@NonNull String json) {
return wrap(jsonFormatterFromJson(json));
}
/**
* Converts {@link String JSON} into {@link PdxInstance PDX} using {@link JSONFormatter#fromJSON(String)}.
*
* @param json {@link String JSON} to convert to {@link PdxInstance PDX}; must not be {@literal null}.
* @return {@link PdxInstance PDX} generated from the given, required {@link String JSON}; never {@literal null}.
* @see org.apache.geode.pdx.JSONFormatter#fromJSON(String)
* @see org.apache.geode.pdx.PdxInstance
*/ | protected @NonNull PdxInstance jsonFormatterFromJson(@NonNull String json) {
return JSONFormatter.fromJSON(json);
}
/**
* Wraps the given {@link PdxInstance} in a new instance of {@link PdxInstanceWrapper}.
*
* @param pdxInstance {@link PdxInstance} to wrap.
* @return a new instance of {@link PdxInstanceWrapper} wrapping the given {@link PdxInstance}.
* @see org.springframework.geode.pdx.PdxInstanceWrapper#from(PdxInstance)
* @see org.springframework.geode.pdx.PdxInstanceWrapper
* @see org.apache.geode.pdx.PdxInstance
*/
protected @NonNull PdxInstanceWrapper wrap(@NonNull PdxInstance pdxInstance) {
return PdxInstanceWrapper.from(pdxInstance);
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\data\json\converter\support\JSONFormatterJsonToPdxConverter.java | 1 |
请完成以下Java代码 | public class SplitStringPerformance {
@Param({"10", "1000", "100000"})
public int tokenCount;
private static final String DELIM = ",";
private String text;
private Pattern commaPattern;
@Setup(Level.Trial)
public void setup() {
StringBuilder sb = new StringBuilder(tokenCount * 8);
for (int i = 0; i < tokenCount; i++) {
sb.append("token").append(i);
if (i < tokenCount - 1) sb.append(DELIM);
}
text = sb.toString();
commaPattern = Pattern.compile(",");
}
@Benchmark
public void stringSplit(Blackhole bh) {
String[] parts = text.split(DELIM);
bh.consume(parts.length);
}
@Benchmark
public void patternSplit(Blackhole bh) {
String[] parts = commaPattern.split(text); | bh.consume(parts.length);
}
@Benchmark
public void manualSplit(Blackhole bh) {
List<String> tokens = new ArrayList<>(tokenCount);
int start = 0, idx;
while ((idx = text.indexOf(DELIM, start)) >= 0) {
tokens.add(text.substring(start, idx));
start = idx + 1;
}
tokens.add(text.substring(start));
bh.consume(tokens.size());
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations-12\src\main\java\com\baeldung\splitstringperformance\SplitStringPerformance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class FaunaUserDetailsService implements UserDetailsService {
private FaunaClient faunaClient;
public FaunaUserDetailsService(FaunaClient faunaClient) {
this.faunaClient = faunaClient;
}
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
try {
Value user = faunaClient.query(Map(
Paginate(Match(Index("users_by_username"), Value(username))),
Lambda(Value("user"), Get(Var("user")))))
.get();
Value userData = user.at("data").at(0).orNull(); | if (userData == null) {
throw new UsernameNotFoundException("User not found");
}
PasswordEncoder encoder = PasswordEncoderFactories.createDelegatingPasswordEncoder();
return User.builder().passwordEncoder(encoder::encode)
.username(userData.at("data", "username").to(String.class).orNull())
.password(userData.at("data", "password").to(String.class).orNull())
.roles("USER")
.build();
} catch (ExecutionException | InterruptedException e) {
throw new RuntimeException(e);
}
}
} | repos\tutorials-master\persistence-modules\fauna\src\main\java\com\baeldung\faunablog\users\FaunaUserDetailsService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class MailTemplateRepository
{
private final CCache<MailTemplateId, MailTemplate> templatesById = CCache.<MailTemplateId, MailTemplate> builder()
.tableName(I_R_MailText.Table_Name)
.build();
public MailTemplate getById(@NonNull final MailTemplateId id)
{
return templatesById.getOrLoad(id, this::retrieveById);
}
public MailTemplate retrieveById(@NonNull final MailTemplateId id)
{
final I_R_MailText record = loadOutOfTrx(id, I_R_MailText.class);
return toMailTemplate(record);
} | private static MailTemplate toMailTemplate(final I_R_MailText record)
{
final IModelTranslationMap trlMap = InterfaceWrapperHelper.getModelTranslationMap(record);
return MailTemplate.builder()
.id(MailTemplateId.ofRepoId(record.getR_MailText_ID()))
.name(record.getName())
.html(record.isHtml())
.mailHeader(trlMap.getColumnTrl(I_R_MailText.COLUMNNAME_MailHeader, record.getMailHeader()))
.mailText(trlMap.getColumnTrl(I_R_MailText.COLUMNNAME_MailText, record.getMailText()))
.mailText2(trlMap.getColumnTrl(I_R_MailText.COLUMNNAME_MailText2, record.getMailText2()))
.mailText3(trlMap.getColumnTrl(I_R_MailText.COLUMNNAME_MailText3, record.getMailText3()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\templates\MailTemplateRepository.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.