instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) {
Method method = getMethod(bindings, context, returnType, paramTypes);
return new MethodInfo(method.getName(), method.getReturnType(), paramTypes);
}
public Object invoke(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] params) {
Method method = getMethod(bindings, context, returnType, paramTypes);
try {
return method.invoke(null, params);
} catch (IllegalAccessException e) {
throw new ELException(LocalMessages.get("error.identifier.method.access", name));
} catch (IllegalArgumentException e) {
throw new ELException(LocalMessages.get("error.identifier.method.invocation", name, e));
} catch (InvocationTargetException e) {
throw new ELException(LocalMessages.get("error.identifier.method.invocation", name, e.getCause()));
}
}
@Override
public String toString() {
return name;
}
@Override
public void appendStructure(StringBuilder b, Bindings bindings) {
b.append(bindings != null && bindings.isVariableBound(index) ? "<var>" : name);
} | public int getIndex() {
return index;
}
public String getName() {
return name;
}
public int getCardinality() {
return 0;
}
public AstNode getChild(int i) {
return null;
}
} | repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\AstIdentifier.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected TbResource prepare(EntitiesImportCtx ctx, TbResource resource, TbResource oldResource, EntityExportData<TbResource> exportData, IdProvider idProvider) {
return resource;
}
@Override
protected TbResource findExistingEntity(EntitiesImportCtx ctx, TbResource resource, IdProvider idProvider) {
TbResource existingResource = super.findExistingEntity(ctx, resource, idProvider);
if (existingResource == null && ctx.isFindExistingByName()) {
existingResource = resourceService.findResourceByTenantIdAndKey(ctx.getTenantId(), resource.getResourceType(), resource.getResourceKey());
}
return existingResource;
}
@Override
protected TbResource deepCopy(TbResource resource) {
return new TbResource(resource);
}
@Override
protected void cleanupForComparison(TbResource resource) {
super.cleanupForComparison(resource);
resource.setSearchText(null);
if (resource.getDescriptor() != null && resource.getDescriptor().isNull()) {
resource.setDescriptor(null);
}
}
@Override
protected TbResource saveOrUpdate(EntitiesImportCtx ctx, TbResource resource, EntityExportData<TbResource> exportData, IdProvider idProvider, CompareResult compareResult) {
if (resource.getResourceType() == ResourceType.IMAGE) {
return new TbResource(imageService.saveImage(resource));
} else {
if (compareResult.isExternalIdChangedOnly()) { | resource = resourceService.saveResource(resource, false);
} else {
resource = resourceService.saveResource(resource);
}
resource.setData(null);
resource.setPreview(null);
return resource;
}
}
@Override
protected void onEntitySaved(User user, TbResource savedResource, TbResource oldResource) throws ThingsboardException {
super.onEntitySaved(user, savedResource, oldResource);
clusterService.onResourceChange(savedResource, null);
}
@Override
public EntityType getEntityType() {
return EntityType.TB_RESOURCE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\ResourceImportService.java | 2 |
请完成以下Java代码 | public String getGlueType() {
return glueType;
}
public void setGlueType(String glueType) {
this.glueType = glueType;
}
public String getGlueSource() {
return glueSource;
}
public void setGlueSource(String glueSource) {
this.glueSource = glueSource;
}
public String getGlueRemark() {
return glueRemark;
}
public void setGlueRemark(String glueRemark) {
this.glueRemark = glueRemark;
}
public Date getGlueUpdatetime() {
return glueUpdatetime;
}
public void setGlueUpdatetime(Date glueUpdatetime) {
this.glueUpdatetime = glueUpdatetime;
}
public String getChildJobId() {
return childJobId;
}
public void setChildJobId(String childJobId) {
this.childJobId = childJobId;
}
public int getTriggerStatus() {
return triggerStatus;
} | public void setTriggerStatus(int triggerStatus) {
this.triggerStatus = triggerStatus;
}
public long getTriggerLastTime() {
return triggerLastTime;
}
public void setTriggerLastTime(long triggerLastTime) {
this.triggerLastTime = triggerLastTime;
}
public long getTriggerNextTime() {
return triggerNextTime;
}
public void setTriggerNextTime(long triggerNextTime) {
this.triggerNextTime = triggerNextTime;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static String normalize(final String str)
{
if (str == null)
{
return null;
}
String normalizedString = Normalizer.normalize(str, Normalizer.Form.NFKD);
for (final Entry<CharSequence, CharSequence> charDuo : Util.notNormalizableChars.entrySet())
{
normalizedString = normalizedString.replace(charDuo.getKey(), charDuo.getValue());
}
// remove remaining special characters with "" (should not normally occur, as Normalize is enough)
return Util.DIACRITICS_AND_FRIENDS.matcher(normalizedString).replaceAll("");
}
/**
* @return resulting string with preceding zeros removed. Or null, if the input was <code>null</code>.
* @see <a href="http://stackoverflow.com/questions/2800739/how-to-remove-leading-zeros-from-alphanumeric-text">Reference</a>
*/
public static String removePrecedingZeros(final String str)
{
if (str == null)
{
return null;
}
return str.replaceFirst("^0+(?!$)", "");
}
public static String lpadZero(final String value, final int size)
{
if (value == null)
{
throw new IllegalArgumentException("value is null");
}
final String valueFixed = value.trim();
final String s = "0000000000000000000" + valueFixed;
return s.substring(s.length() - size);
}
public static String mkOwnOrderNumber(final String documentNo)
{ | final String sevenDigitString = documentNo.length() <= 7 ? documentNo : documentNo.substring(documentNo.length() - 7);
return "006" + lpadZero(sevenDigitString, 7);
}
/**
* Remove trailing zeros after decimal separator
*
* @return <code>bd</code> without trailing zeros after separator; if argument is NULL then NULL will be retu
*/
// NOTE: this is copy-paste of de.metas.util.NumberUtils.stripTrailingDecimalZeros(BigDecimal)
public static BigDecimal stripTrailingDecimalZeros(final BigDecimal bd)
{
if (bd == null)
{
return null;
}
//
// Remove all trailing zeros
BigDecimal result = bd.stripTrailingZeros();
// Fix very weird java 6 bug: stripTrailingZeros doesn't work on 0 itself
// http://stackoverflow.com/questions/5239137/clarification-on-behavior-of-bigdecimal-striptrailingzeroes
if (result.signum() == 0)
{
result = BigDecimal.ZERO;
}
//
// If after removing our scale is negative, we can safely set the scale to ZERO because we don't want to get rid of zeros before decimal point
if (result.scale() < 0)
{
result = result.setScale(0, RoundingMode.UNNECESSARY);
}
return result;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\Util.java | 2 |
请完成以下Java代码 | public final class OAuth2AccessTokenAuthenticationContext implements OAuth2AuthenticationContext {
private final Map<Object, Object> context;
private OAuth2AccessTokenAuthenticationContext(Map<Object, Object> context) {
this.context = Collections.unmodifiableMap(new HashMap<>(context));
}
@SuppressWarnings("unchecked")
@Nullable
@Override
public <V> V get(Object key) {
return hasKey(key) ? (V) this.context.get(key) : null;
}
@Override
public boolean hasKey(Object key) {
Assert.notNull(key, "key cannot be null");
return this.context.containsKey(key);
}
/**
* Returns the {@link OAuth2AccessTokenResponse.Builder access token response
* builder}.
* @return the {@link OAuth2AccessTokenResponse.Builder}
*/
public OAuth2AccessTokenResponse.Builder getAccessTokenResponse() {
return get(OAuth2AccessTokenResponse.Builder.class);
}
/**
* Constructs a new {@link Builder} with the provided
* {@link OAuth2AccessTokenAuthenticationToken}.
* @param authentication the {@link OAuth2AccessTokenAuthenticationToken}
* @return the {@link Builder}
*/
public static Builder with(OAuth2AccessTokenAuthenticationToken authentication) {
return new Builder(authentication);
}
/**
* A builder for {@link OAuth2AccessTokenAuthenticationContext}.
*/
public static final class Builder extends AbstractBuilder<OAuth2AccessTokenAuthenticationContext, Builder> {
private Builder(OAuth2AccessTokenAuthenticationToken authentication) {
super(authentication);
}
/** | * Sets the {@link OAuth2AccessTokenResponse.Builder access token response
* builder}.
* @param accessTokenResponse the {@link OAuth2AccessTokenResponse.Builder}
* @return the {@link Builder} for further configuration
*/
public Builder accessTokenResponse(OAuth2AccessTokenResponse.Builder accessTokenResponse) {
return put(OAuth2AccessTokenResponse.Builder.class, accessTokenResponse);
}
/**
* Builds a new {@link OAuth2AccessTokenAuthenticationContext}.
* @return the {@link OAuth2AccessTokenAuthenticationContext}
*/
@Override
public OAuth2AccessTokenAuthenticationContext build() {
Assert.notNull(get(OAuth2AccessTokenResponse.Builder.class), "accessTokenResponse cannot be null");
return new OAuth2AccessTokenAuthenticationContext(getContext());
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AccessTokenAuthenticationContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConfigurableListableBeanFactory beanFactory = context.getBeanFactory();
Assert.state(beanFactory != null, "'beanFactory' must not be null");
ConditionOutcome outcome = checkDefaultDispatcherName(beanFactory);
if (!outcome.isMatch()) {
return outcome;
}
return checkServletRegistration(beanFactory);
}
private ConditionOutcome checkDefaultDispatcherName(ConfigurableListableBeanFactory beanFactory) {
boolean containsDispatcherBean = beanFactory.containsBean(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME);
if (!containsDispatcherBean) {
return ConditionOutcome.match();
}
List<String> servlets = Arrays
.asList(beanFactory.getBeanNamesForType(DispatcherServlet.class, false, false));
if (!servlets.contains(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME)) {
return ConditionOutcome.noMatch(
startMessage().found("non dispatcher servlet").items(DEFAULT_DISPATCHER_SERVLET_BEAN_NAME));
}
return ConditionOutcome.match();
}
private ConditionOutcome checkServletRegistration(ConfigurableListableBeanFactory beanFactory) {
ConditionMessage.Builder message = startMessage();
List<String> registrations = Arrays
.asList(beanFactory.getBeanNamesForType(ServletRegistrationBean.class, false, false));
boolean containsDispatcherRegistrationBean = beanFactory
.containsBean(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME);
if (registrations.isEmpty()) {
if (containsDispatcherRegistrationBean) {
return ConditionOutcome.noMatch(message.found("non servlet registration bean")
.items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)); | }
return ConditionOutcome.match(message.didNotFind("servlet registration bean").atAll());
}
if (registrations.contains(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME)) {
return ConditionOutcome.noMatch(message.found("servlet registration bean")
.items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));
}
if (containsDispatcherRegistrationBean) {
return ConditionOutcome.noMatch(message.found("non servlet registration bean")
.items(DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));
}
return ConditionOutcome.match(message.found("servlet registration beans")
.items(Style.QUOTE, registrations)
.append("and none is named " + DEFAULT_DISPATCHER_SERVLET_REGISTRATION_BEAN_NAME));
}
private ConditionMessage.Builder startMessage() {
return ConditionMessage.forCondition("DispatcherServlet Registration");
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\DispatcherServletAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void configure()
{
errorHandler(noErrorHandler());
from("{{" + ExternalSystemCamelConstants.MF_UPSERT_BPARTNER_LOCATION_V2_CAMEL_URI + "}}")
.routeId(ROUTE_ID)
.streamCache("true")
.log("Route invoked!")
.process(exchange -> {
final var lookupRequest = exchange.getIn().getBody();
if (!(lookupRequest instanceof BPLocationCamelRequest))
{
throw new RuntimeCamelException("The route " + ROUTE_ID + " requires the body to be instanceof BPLocationCamelRequest V2."
+ " However, it is " + (lookupRequest == null ? "null" : lookupRequest.getClass().getName()));
} | exchange.getIn().setHeader(HEADER_ORG_CODE, ((BPLocationCamelRequest)lookupRequest).getOrgCode());
exchange.getIn().setHeader(HEADER_BPARTNER_IDENTIFIER, ((BPLocationCamelRequest)lookupRequest).getBPartnerIdentifier());
final JsonRequestLocationUpsert jsonRequestLocationUpsert = ((BPLocationCamelRequest)lookupRequest).getJsonRequestLocationUpsert();
exchange.getIn().setBody(jsonRequestLocationUpsert);
})
.marshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonRequestLocationUpsert.class))
.removeHeaders("CamelHttp*")
.setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.PUT))
.toD("{{metasfresh.upsert-bpartner-v2.api.uri}}/${header." + HEADER_ORG_CODE + "}/${header." + HEADER_BPARTNER_IDENTIFIER + "}/location")
.to(direct(UNPACK_V2_API_RESPONSE));
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\v2\BPartnerLocationRouteBuilder.java | 2 |
请完成以下Java代码 | public void contribute(Info.Builder builder) {
builder.withDetail("git", generateContent());
}
@Override
protected PropertySource<?> toSimplePropertySource() {
Properties props = new Properties();
copyIfSet(props, "branch");
String commitId = getProperties().getShortCommitId();
if (commitId != null) {
props.put("commit.id", commitId);
}
copyIfSet(props, "commit.time");
return new PropertiesPropertySource("git", props);
}
/**
* Post-process the content to expose. By default, well known keys representing dates
* are converted to {@link Instant} instances.
* @param content the content to expose
*/
@Override
protected void postProcessContent(Map<String, Object> content) {
replaceValue(getNestedMap(content, "commit"), "time", getProperties().getCommitTime()); | replaceValue(getNestedMap(content, "build"), "time", getProperties().getInstant("build.time"));
}
static class GitInfoContributorRuntimeHints implements RuntimeHintsRegistrar {
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.bindingRegistrar.registerReflectionHints(hints.reflection(), GitProperties.class);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\info\GitInfoContributor.java | 1 |
请完成以下Java代码 | 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 class UsageRequest {
private String customerId;
private String subscriptionId;
private PricingType pricingType;
private Integer quantity;
private BigDecimal price;
private Instant timestamp;
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb
.append("\nUsage: {")
.append("\n\tcustomer: ")
.append(this.customerId)
.append("\n\tsubscription: ")
.append(this.subscriptionId)
.append("\n\tquantity: ")
.append(this.quantity) | .append("\n\ttimestamp: ")
.append(this.timestamp)
.append("\n\tpricingType: ")
.append(this.pricingType);
if (PricingType.PRE_RATED == this.pricingType) {
sb
.append("\n\tpreRatedAt: ")
.append(this.price);
}
sb.append("\n}\n");
return sb.toString();
}
public enum PricingType {
PRE_RATED, UNRATED
}
} | repos\tutorials-master\libraries-cli\src\main\java\com\baeldung\jcommander\usagebilling\model\UsageRequest.java | 1 |
请完成以下Java代码 | public void addAdvancedSearchDescriptor(final AdvancedSearchDescriptor searchDescriptor)
{
advSearchDescriptorsByTableName.put(searchDescriptor.getTableName(), searchDescriptor);
logger.info("Registered {}", searchDescriptor);
}
public AdvancedSearchDescriptor getAdvancedSearchDescriptorOrNull(final String tableName)
{
return advSearchDescriptorsByTableName.get(tableName);
}
/**
* @param windowId the window ID of the Advanced Search window
* @return corresponding record descriptor from static map
*/
public AdvancedSearchDescriptor getAdvancedSearchDescriptor(final WindowId windowId)
{
return advSearchDescriptorsByTableName.values()
.stream()
.filter(descriptor -> WindowId.equals(windowId, descriptor.getWindowId()))
.findFirst()
.orElseThrow(() -> new AdempiereException("No advanced search quick input defined windowId=" + windowId));
}
@Nullable
public DocumentEntityDescriptor getAdvancedSearchDescriptorIfAvailable(final String tableName)
{ | final AdvancedSearchDescriptor descriptor = getAdvancedSearchDescriptorOrNull(tableName);
if (descriptor == null)
{
return null;
}
try
{
return documentDescriptors.getDocumentEntityDescriptor(descriptor.getWindowId());
}
catch (final Exception ex)
{
logger.warn("Failed fetching document entity descriptor for {}. Ignored", descriptor, ex);
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\AdvancedSearchDescriptorsProvider.java | 1 |
请完成以下Java代码 | void uselessNullCheckOnInferredAnnotation() {
if (StringUtils.isEmpty(null)) {
System.out.println("baeldung");
}
}
@Contract(pure = true)
String replace(String string, char oldChar, char newChar) {
return string.replace(oldChar, newChar);
}
@Contract(value = "true -> false; false -> true", pure = true)
boolean not(boolean input) {
return !input;
}
@Contract("true -> new")
void contractExpectsWrongParameterType(List<Integer> integers) {
}
@Contract("_, _ -> new")
void contractExpectsMoreParametersThanMethodHas(String s) {
}
@Contract("_ -> _; null -> !null")
String secondContractClauseNotReachable(String s) {
return "";
}
@Contract("_ -> true")
void contractExpectsWrongReturnType(String s) {
} | // NB: the following examples demonstrate how to use the mutates attribute of the annotation
// This attribute is currently experimental and could be changed or removed in the future
@Contract(mutates = "param")
void incrementArrayFirstElement(Integer[] integers) {
if (integers.length > 0) {
integers[0] = integers[0] + 1;
}
}
@Contract(pure = true, mutates = "param")
void impossibleToMutateParamInPureFunction(List<String> strings) {
if (strings != null) {
strings.forEach(System.out::println);
}
}
@Contract(mutates = "param3")
void impossibleToMutateThirdParamWhenMethodHasOnlyTwoParams(int a, int b) {
}
@Contract(mutates = "param")
void impossibleToMutableImmutableType(String s) {
}
@Contract(mutates = "this")
static void impossibleToMutateThisInStaticMethod() {
}
} | repos\tutorials-master\jetbrains-annotations\src\main\java\com\baeldung\annotations\Demo.java | 1 |
请完成以下Java代码 | private Mono<?> updateUsername(UpdateUserRequest request, User user) {
if (request.getUsername() == null) {
return Mono.empty();
}
if (request.getUsername().equals(user.getUsername())) {
return Mono.empty();
}
return userRepository.existsByUsername(request.getUsername())
.doOnNext(existsByUsername -> updateUsername(request, user, existsByUsername));
}
private void updateUsername(UpdateUserRequest request, User user, boolean existsByUsername) {
if (existsByUsername) {
throw usernameAlreadyInUseException();
}
user.setUsername(request.getUsername());
}
private Mono<?> updateEmail(UpdateUserRequest request, User user) {
if (request.getEmail() == null) {
return Mono.empty();
}
if (request.getEmail().equals(user.getEmail())) {
return Mono.empty();
} | return userRepository.existsByEmail(request.getEmail())
.doOnNext(existsByEmail -> updateEmail(request, user, existsByEmail));
}
private void updateEmail(UpdateUserRequest request, User user, boolean existsByEmail) {
if (existsByEmail) {
throw emailAlreadyInUseException();
}
user.setEmail(request.getEmail());
}
private InvalidRequestException usernameAlreadyInUseException() {
return new InvalidRequestException("Username", "already in use");
}
private InvalidRequestException emailAlreadyInUseException() {
return new InvalidRequestException("Email", "already in use");
}
} | repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\user\UserUpdater.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HistoricDetailQueryRequest extends PaginateRequest {
private String id;
private String processInstanceId;
private String executionId;
private String activityInstanceId;
private String taskId;
private Boolean selectOnlyFormProperties;
private Boolean selectOnlyVariableUpdates;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
} | public String getActivityInstanceId() {
return activityInstanceId;
}
public void setActivityInstanceId(String activityInstanceId) {
this.activityInstanceId = activityInstanceId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public Boolean getSelectOnlyFormProperties() {
return selectOnlyFormProperties;
}
public void setSelectOnlyFormProperties(Boolean selectOnlyFormProperties) {
this.selectOnlyFormProperties = selectOnlyFormProperties;
}
public Boolean getSelectOnlyVariableUpdates() {
return selectOnlyVariableUpdates;
}
public void setSelectOnlyVariableUpdates(Boolean selectOnlyVariableUpdates) {
this.selectOnlyVariableUpdates = selectOnlyVariableUpdates;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailQueryRequest.java | 2 |
请完成以下Java代码 | private void doRollback(boolean isNew, Throwable originalException) {
Throwable rollbackEx = null;
try {
if (isNew) {
transactionManager.rollback();
} else {
transactionManager.setRollbackOnly();
}
} catch (SystemException e) {
LOGGER.debug("Error when rolling back transaction", e);
} catch (RuntimeException e) {
rollbackEx = e;
throw e;
} catch (Error e) {
rollbackEx = e;
throw e;
} finally {
if (rollbackEx != null && originalException != null) {
LOGGER.error("Error when rolling back transaction, original exception was:", originalException);
}
}
}
private static class TransactionException extends RuntimeException { | private static final long serialVersionUID = 1L;
private TransactionException() {}
private TransactionException(String s) {
super(s);
}
private TransactionException(String s, Throwable throwable) {
super(s, throwable);
}
private TransactionException(Throwable throwable) {
super(throwable);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\JtaTransactionInterceptor.java | 1 |
请完成以下Java代码 | public class LazyDelegateFilter<T extends Filter> implements Filter {
protected final Class<? extends T> delegateClass;
protected InitHook<T> initHook;
protected T delegate;
protected FilterConfig filterConfig;
public LazyDelegateFilter(Class<? extends T> delegateClass) {
this.delegateClass = delegateClass;
LazyInitRegistration.register(this);
}
public void lazyInit() {
try {
delegate = createNewFilterInstance();
if (initHook != null) {
initHook.init(delegate);
}
delegate.init(filterConfig);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
LazyInitRegistration.lazyInit(this);
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
delegate.doFilter(request, response, chain);
} | @Override
public void destroy() {
if (delegate != null) {
delegate.destroy();
}
}
public InitHook<T> getInitHook() {
return initHook;
}
public void setInitHook(InitHook<T> initHook) {
this.initHook = initHook;
}
public Class<? extends T> getDelegateClass() {
return delegateClass;
}
protected T createNewFilterInstance() throws InstantiationException, IllegalAccessException {
return delegateClass.newInstance();
}
public static interface InitHook<T extends Filter> {
void init(T filter);
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter-webapp-core\src\main\java\org\camunda\bpm\spring\boot\starter\webapp\filter\LazyDelegateFilter.java | 1 |
请完成以下Java代码 | private void configureSslClientAuth(SslContextFactory.Server factory, @Nullable ClientAuth clientAuth) {
factory.setWantClientAuth(clientAuth == ClientAuth.WANT || clientAuth == ClientAuth.NEED);
factory.setNeedClientAuth(clientAuth == ClientAuth.NEED);
}
/**
* A {@link ServerConnector} that validates the ssl key alias on server startup.
*/
static class SslValidatingServerConnector extends ServerConnector {
private final SslBundleKey key;
private final SslContextFactory sslContextFactory;
SslValidatingServerConnector(SslBundleKey key, SslContextFactory sslContextFactory, Server server,
SslConnectionFactory sslConnectionFactory, HttpConnectionFactory connectionFactory) {
super(server, sslConnectionFactory, connectionFactory);
this.key = key;
this.sslContextFactory = sslContextFactory; | }
SslValidatingServerConnector(SslBundleKey keyAlias, SslContextFactory sslContextFactory, Server server,
ConnectionFactory... factories) {
super(server, factories);
this.key = keyAlias;
this.sslContextFactory = sslContextFactory;
}
@Override
protected void doStart() throws Exception {
super.doStart();
this.key.assertContainsAlias(this.sslContextFactory.getKeyStore());
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-jetty\src\main\java\org\springframework\boot\jetty\SslServerCustomizer.java | 1 |
请完成以下Java代码 | public int size() {
return this.filesByName.size();
}
@Override
public @Nullable ClassLoaderFile getFile(@Nullable String name) {
return this.filesByName.get(name);
}
/**
* Returns a set of all file entries across all source directories for efficient
* iteration.
* @return a set of all file entries
* @since 4.0.0
*/
public Set<Entry<String, ClassLoaderFile>> getFileEntries() {
return Collections.unmodifiableSet(this.filesByName.entrySet());
}
/**
* An individual source directory that is being managed by the collection.
*/
public static class SourceDirectory implements Serializable {
@Serial
private static final long serialVersionUID = 1;
private final String name;
private final Map<String, ClassLoaderFile> files = new LinkedHashMap<>();
SourceDirectory(String name) {
this.name = name;
}
public Set<Entry<String, ClassLoaderFile>> getFilesEntrySet() {
return this.files.entrySet();
}
protected final void add(String name, ClassLoaderFile file) {
this.files.put(name, file);
} | protected final void remove(String name) {
this.files.remove(name);
}
protected final @Nullable ClassLoaderFile get(String name) {
return this.files.get(name);
}
/**
* Return the name of the source directory.
* @return the name of the source directory
*/
public String getName() {
return this.name;
}
/**
* Return all {@link ClassLoaderFile ClassLoaderFiles} in the collection that are
* contained in this source directory.
* @return the files contained in the source directory
*/
public Collection<ClassLoaderFile> getFiles() {
return Collections.unmodifiableCollection(this.files.values());
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\restart\classloader\ClassLoaderFiles.java | 1 |
请完成以下Java代码 | public ISnapshotRestorer<I_M_HU> setSnapshotId(final String snapshotId)
{
huSnapshotHandler.setSnapshotId(snapshotId);
return this;
}
@Override
public String getSnapshotId()
{
return huSnapshotHandler.getSnapshotId();
}
@Override
public M_HU_Snapshot_ProducerAndRestorer setContext(final IContextAware context)
{
huSnapshotHandler.setContext(context);
return this;
}
@Override
public M_HU_Snapshot_ProducerAndRestorer setDateTrx(final Date dateTrx)
{
huSnapshotHandler.setDateTrx(dateTrx);
return this;
}
@Override
public M_HU_Snapshot_ProducerAndRestorer setReferencedModel(final Object referencedModel)
{
huSnapshotHandler.setReferencedModel(referencedModel);
return this;
}
@Override
public M_HU_Snapshot_ProducerAndRestorer addModel(@NonNull final I_M_HU model)
{
_huIds.add(HuId.ofRepoId(model.getM_HU_ID()));
return this;
}
@Override
public final M_HU_Snapshot_ProducerAndRestorer addModels(final Collection<? extends I_M_HU> models)
{
models.forEach(this::addModel);
return this;
}
/**
* Gets currently enqueued models and it also clears the internal queue.
*
* @return enqueued models to be restored or snapshot-ed
*/
private final Set<HuId> getHUIdsAndClear()
{
final Set<HuId> modelIds = new HashSet<>(_huIds);
_huIds.clear();
return modelIds; | }
private final boolean hasModelsToSnapshot()
{
return !_huIds.isEmpty();
}
@Override
public ISnapshotRestorer<I_M_HU> addModelId(final int huId)
{
_huIds.add(HuId.ofRepoId(huId));
return this;
}
@Override
public ISnapshotRestorer<I_M_HU> addModelIds(@NonNull final Collection<Integer> huRepoIds)
{
final ImmutableSet<HuId> huIds = huRepoIds
.stream()
.map(HuId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
_huIds.addAll(huIds);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\snapshot\impl\M_HU_Snapshot_ProducerAndRestorer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SupplierType
extends BusinessEntityType
{
@XmlElement(name = "EBPP_ConsolidatorsBillerID")
protected String ebppConsolidatorsBillerID;
@XmlElement(name = "SupplierIDissuedByCustomer")
protected String supplierIDissuedByCustomer;
@XmlElement(name = "SupplierExtension", namespace = "http://erpel.at/schemas/1p0/documents/ext")
protected SupplierExtensionType supplierExtension;
/**
* ID of the supplier at the consolidator's side.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEBPPConsolidatorsBillerID() {
return ebppConsolidatorsBillerID;
}
/**
* Sets the value of the ebppConsolidatorsBillerID property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEBPPConsolidatorsBillerID(String value) {
this.ebppConsolidatorsBillerID = value;
}
/**
* The ID of the supplier issued by the customer.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSupplierIDissuedByCustomer() {
return supplierIDissuedByCustomer; | }
/**
* Sets the value of the supplierIDissuedByCustomer property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSupplierIDissuedByCustomer(String value) {
this.supplierIDissuedByCustomer = value;
}
/**
* Gets the value of the supplierExtension property.
*
* @return
* possible object is
* {@link SupplierExtensionType }
*
*/
public SupplierExtensionType getSupplierExtension() {
return supplierExtension;
}
/**
* Sets the value of the supplierExtension property.
*
* @param value
* allowed object is
* {@link SupplierExtensionType }
*
*/
public void setSupplierExtension(SupplierExtensionType value) {
this.supplierExtension = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\SupplierType.java | 2 |
请完成以下Java代码 | public Connection getConnection() throws SQLException {
final String URL = "jdbc:h2:~/test";
return DriverManager.getConnection(URL, "sa", "");
}
public void setAge(int age) {
if (age < 0 || age > 150) {
throw new IllegalArgumentException();
}
this.age = age;
}
public int getAge() {
return age;
}
@Override
public String toString() {
return this.name;
}
private class StudentGrade {
private BigDecimal grade = BigDecimal.ZERO;
private Date updatedAt;
public StudentGrade(int grade) { | this.grade = new BigDecimal(grade);
this.updatedAt = new Date();
}
public BigDecimal getGrade() {
return grade;
}
public Date getDate() {
return updatedAt;
}
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-modifiers-2\src\main\java\com\baeldung\publicmodifier\Student.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setExternalId (final java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setSUMUP_CardReader_ID (final int SUMUP_CardReader_ID)
{
if (SUMUP_CardReader_ID < 1)
set_ValueNoCheck (COLUMNNAME_SUMUP_CardReader_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SUMUP_CardReader_ID, SUMUP_CardReader_ID);
}
@Override
public int getSUMUP_CardReader_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_CardReader_ID); | }
@Override
public de.metas.payment.sumup.repository.model.I_SUMUP_Config getSUMUP_Config()
{
return get_ValueAsPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class);
}
@Override
public void setSUMUP_Config(final de.metas.payment.sumup.repository.model.I_SUMUP_Config SUMUP_Config)
{
set_ValueFromPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class, SUMUP_Config);
}
@Override
public void setSUMUP_Config_ID (final int SUMUP_Config_ID)
{
if (SUMUP_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID);
}
@Override
public int getSUMUP_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_CardReader.java | 2 |
请完成以下Java代码 | public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName () | {
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_C_BPartner_Allotment.java | 1 |
请完成以下Java代码 | public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((description == null) ? 0 : description.hashCode());
result = prime * result + ((id == null) ? 0 : id.hashCode());
result = prime * result + ((username == null) ? 0 : username.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false; | Course other = (Course) obj;
if (description == null) {
if (other.description != null)
return false;
} else if (!description.equals(other.description))
return false;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
if (username == null) {
return other.username == null;
} else return username.equals(other.username);
}
} | repos\spring-boot-examples-master\spring-boot-react-examples\spring-boot-react-crud-full-stack-with-maven\backend-spring-boot-react-crud-full-stack-with-maven\src\main\java\com\in28minutes\fullstack\springboot\maven\crud\springbootcrudfullstackwithmaven\course\Course.java | 1 |
请完成以下Java代码 | public final class PlainDeliveryDayQueryParams implements IDeliveryDayQueryParams
{
private ZonedDateTime deliveryDate = null;
private BPartnerLocationId bpartnerLocationId = null;
private Boolean toBeFetched = null;
private Boolean processed = null;
/**
* The time when the calculation is performed. For instance, the date+time when the order was created or the system time.
*/
private ZonedDateTime calculationTime = null;
/**
* The day when the products should be delivered
*/
@Nullable
private LocalDate preparationDay = null;
@Override
public String toString()
{
return "PlainDeliveryDayQueryParams ["
+ "deliveryDate=" + deliveryDate
+ ", bpartnerLocationId=" + bpartnerLocationId
+ ", toBeFetched=" + toBeFetched
+ ", processed=" + processed
+ "]";
}
@Override
public ZonedDateTime getDeliveryDate()
{
return deliveryDate;
}
public void setDeliveryDate(final ZonedDateTime deliveryDate)
{
this.deliveryDate = deliveryDate;
}
@Override
public BPartnerLocationId getBPartnerLocationId()
{
return bpartnerLocationId;
}
public void setBPartnerLocationId(final BPartnerLocationId bpartnerLocationId)
{
this.bpartnerLocationId = bpartnerLocationId;
}
@Override
public boolean isToBeFetched()
{
Check.assumeNotNull(toBeFetched, "toBeFetched set");
return toBeFetched;
} | /**
* @param toBeFetched
* @see #isToBeFetched()
*/
public void setToBeFetched(final boolean toBeFetched)
{
this.toBeFetched = toBeFetched;
}
@Override
public Boolean getProcessed()
{
return processed;
}
public void setProcessed(final Boolean processed)
{
this.processed = processed;
}
@Override
public ZonedDateTime getCalculationTime()
{
return calculationTime;
}
/**
* See {@link IDeliveryDayQueryParams#getCalculationTime()}.
*
* @param calculationTime
*/
public void setCalculationTime(final ZonedDateTime calculationTime)
{
this.calculationTime = calculationTime;
}
@Nullable
@Override
public LocalDate getPreparationDay()
{
return preparationDay;
}
public void setPreparationDay(@Nullable LocalDate preparationDay)
{
this.preparationDay = preparationDay;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\PlainDeliveryDayQueryParams.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private String extractPrefixFromRecordColumn(final String columnName)
{
final int recordStringIndex = columnName.indexOf(ITableRecordReference.COLUMNNAME_Record_ID);
final String prefix = columnName.substring(0, recordStringIndex);
return prefix;
}
@Override
public String getSingleKeyColumn(final String tableName)
{
if (Adempiere.isUnitTestMode())
{
return InterfaceWrapperHelper.getKeyColumnName(tableName);
}
final POInfo poInfo = POInfo.getPOInfo(tableName);
final List<String> keyColumnNames = poInfo.getKeyColumnNames();
if (keyColumnNames.size() != 1)
{
throw new NoSingleKeyColumnException(poInfo);
}
return keyColumnNames.get(0);
}
@Override
public boolean getDefaultAllowLoggingByColumnName(@NonNull final String columnName)
{
if (columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_Created)
|| columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_CreatedBy)
|| columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_Updated)
|| columnName.equalsIgnoreCase(I_AD_Column.COLUMNNAME_UpdatedBy))
{
return false;
} | return true;
}
@Override
public boolean getDefaultIsCalculatedByColumnName(@NonNull final String columnName)
{
return columnName.equalsIgnoreCase("Value")
|| columnName.equalsIgnoreCase("DocumentNo")
|| columnName.equalsIgnoreCase("DocStatus")
|| columnName.equalsIgnoreCase("Docaction")
|| columnName.equalsIgnoreCase("Processed")
|| columnName.equalsIgnoreCase("Processing")
|| StringUtils.containsIgnoreCase(columnName, "ExternalID")
|| columnName.equalsIgnoreCase("ExternalHeaderId")
|| columnName.equalsIgnoreCase("ExternalLineId")
|| columnName.equalsIgnoreCase("IsReconciled")
;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\service\impl\ColumnBL.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getHtmlMailView(Model model,
HttpServletRequest request) {
Map<String, String> templateEngines = new HashMap<>();
templateEngines.put("Thymeleaf", "Thymeleaf");
templateEngines.put("Freemarker", "Freemarker");
model.addAttribute("mailObject", new MailObject());
model.addAttribute("templateEngines", templateEngines);
return "mail/sendHtml";
}
@RequestMapping(value = "/sendHtml", method = RequestMethod.POST)
public String createHtmlMail(Model model,
@ModelAttribute("mailObject") @Valid MailObject mailObject,
Errors errors) throws IOException, MessagingException, TemplateException {
if (errors.hasErrors()) {
return "mail/send";
}
Map<String, Object> templateModel = new HashMap<>();
templateModel.put("recipientName", mailObject.getRecipientName());
templateModel.put("text", mailObject.getText());
templateModel.put("senderName", mailObject.getSenderName()); | if (mailObject.getTemplateEngine().equalsIgnoreCase("thymeleaf")) {
emailService.sendMessageUsingThymeleafTemplate(
mailObject.getTo(),
mailObject.getSubject(),
templateModel);
} else {
emailService.sendMessageUsingFreemarkerTemplate(
mailObject.getTo(),
mailObject.getSubject(),
templateModel);
}
return "redirect:/mail";
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics-2\src\main\java\com\baeldung\spring\controller\MailController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static String printDate(final java.util.Date val) {
final Calendar calendar = Calendar.getInstance();
calendar.setTime(val);
return jakarta.xml.bind.DatatypeConverter.printDate(calendar);
}
/**
* <p>
* Converts the string argument into a time ({@link Date}) value.
*
* @param lexicalXSDTime
* A string containing lexical representation of xsd:time.
* @return A time ({@link Date}) value represented by the string argument.
* @throws IllegalArgumentException
* if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:time.
*/
public static java.util.Date parseTime(final String lexicalXSDTime) {
final Calendar calendar = jakarta.xml.bind.DatatypeConverter.parseTime(lexicalXSDTime);
return calendar.getTime();
}
/**
* <p>
* Converts a time ({@link Date}) value into a string.
*
* @param val
* A time ({@link Date}) value
* @return A string containing a lexical representation of xsd:time
* @throws IllegalArgumentException
* if <tt>val</tt> is null.
*/
public static String printTime(final java.util.Date val) {
final Calendar calendar = Calendar.getInstance();
calendar.setTime(val);
return jakarta.xml.bind.DatatypeConverter.printTime(calendar);
}
/**
* <p>
* Converts the string argument into a date/time ({@link Date}) value.
*
* @param lexicalXSDDateTime
* A string containing lexical representation of xsd:dateTime.
* @return A date/time ({@link Date}) value represented by the string argument.
* @throws IllegalArgumentException | * if string parameter does not conform to lexical value space defined in XML Schema Part 2: Datatypes for xsd:date/Time.
*/
public static java.util.Date parseDateTime(final String lexicalXSDDateTime) {
final Calendar calendar = jakarta.xml.bind.DatatypeConverter.parseDateTime(lexicalXSDDateTime);
return calendar.getTime();
}
/**
* <p>
* Converts a date/time ({@link Date}) value into a string.
*
* @param val
* A date/time ({@link Date}) value
* @return A string containing a lexical representation of xsd:dateTime
* @throws IllegalArgumentException
* if <tt>val</tt> is null.
*/
public static String printDateTime(final java.util.Date val) {
final Calendar calendar = Calendar.getInstance();
calendar.setTime(val);
return jakarta.xml.bind.DatatypeConverter.printDateTime(calendar);
}
} | repos\flowable-engine-main\modules\flowable-cxf\src\main\java\org\flowable\engine\impl\webservice\DatatypeConverter.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public PackagingUnit defaultPackagingUnit(Boolean defaultPackagingUnit) {
this.defaultPackagingUnit = defaultPackagingUnit;
return this;
}
/**
* Voreingestelle Verpackungseinheit Ja/Nein (für Warenkorb)
* @return defaultPackagingUnit
**/
@Schema(example = "true", required = true, description = "Voreingestelle Verpackungseinheit Ja/Nein (für Warenkorb)")
public Boolean isDefaultPackagingUnit() {
return defaultPackagingUnit;
}
public void setDefaultPackagingUnit(Boolean defaultPackagingUnit) {
this.defaultPackagingUnit = defaultPackagingUnit;
}
public PackagingUnit archived(Boolean archived) {
this.archived = archived;
return this;
}
/**
* Kennzeichen ob Verpackungseinheit archiviert ist, d. h. nicht mehr im Warenkorb ausgewählt werden kann
* @return archived
**/
@Schema(example = "false", description = "Kennzeichen ob Verpackungseinheit archiviert ist, d. h. nicht mehr im Warenkorb ausgewählt werden kann")
public Boolean isArchived() {
return archived;
}
public void setArchived(Boolean archived) {
this.archived = archived;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PackagingUnit packagingUnit = (PackagingUnit) o;
return Objects.equals(this.unit, packagingUnit.unit) &&
Objects.equals(this.quantity, packagingUnit.quantity) &&
Objects.equals(this.pcn, packagingUnit.pcn) &&
Objects.equals(this.defaultPackagingUnit, packagingUnit.defaultPackagingUnit) &&
Objects.equals(this.archived, packagingUnit.archived);
}
@Override
public int hashCode() { | return Objects.hash(unit, quantity, pcn, defaultPackagingUnit, archived);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PackagingUnit {\n");
sb.append(" unit: ").append(toIndentedString(unit)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" pcn: ").append(toIndentedString(pcn)).append("\n");
sb.append(" defaultPackagingUnit: ").append(toIndentedString(defaultPackagingUnit)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).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(java.lang.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-article-api\src\main\java\io\swagger\client\model\PackagingUnit.java | 2 |
请完成以下Java代码 | public class ExtensionAttribute {
protected String name;
protected String value;
protected String namespacePrefix;
protected String namespace;
public ExtensionAttribute() {}
public ExtensionAttribute(String name) {
this.name = name;
}
public ExtensionAttribute(String namespace, String name) {
this.namespace = namespace;
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getNamespacePrefix() {
return namespacePrefix;
} | public void setNamespacePrefix(String namespacePrefix) {
this.namespacePrefix = namespacePrefix;
}
public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (namespacePrefix != null) {
sb.append(namespacePrefix);
if (name != null) sb.append(":").append(name);
} else sb.append(name);
if (value != null) sb.append("=").append(value);
return sb.toString();
}
public ExtensionAttribute clone() {
ExtensionAttribute clone = new ExtensionAttribute();
clone.setValues(this);
return clone;
}
public void setValues(ExtensionAttribute otherAttribute) {
setName(otherAttribute.getName());
setValue(otherAttribute.getValue());
setNamespacePrefix(otherAttribute.getNamespacePrefix());
setNamespace(otherAttribute.getNamespace());
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ExtensionAttribute.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public float getEvictionHeapPercentage() {
return this.evictionHeapPercentage;
}
public void setEvictionHeapPercentage(float evictionHeapPercentage) {
this.evictionHeapPercentage = evictionHeapPercentage;
}
public float getEvictionOffHeapPercentage() {
return this.evictionOffHeapPercentage;
}
public void setEvictionOffHeapPercentage(float evictionOffHeapPercentage) {
this.evictionOffHeapPercentage = evictionOffHeapPercentage;
}
public String getLogLevel() {
return this.logLevel;
}
public void setLogLevel(String logLevel) {
this.logLevel = logLevel;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public OffHeapProperties getOffHeap() {
return this.offHeap;
}
public PeerCacheProperties getPeer() {
return this.peer;
}
public CacheServerProperties getServer() {
return this.server;
}
public static class CompressionProperties {
private String compressorBeanName;
private String[] regionNames = {}; | public String getCompressorBeanName() {
return this.compressorBeanName;
}
public void setCompressorBeanName(String compressorBeanName) {
this.compressorBeanName = compressorBeanName;
}
public String[] getRegionNames() {
return this.regionNames;
}
public void setRegionNames(String[] regionNames) {
this.regionNames = regionNames;
}
}
public static class OffHeapProperties {
private String memorySize;
private String[] regionNames = {};
public String getMemorySize() {
return this.memorySize;
}
public void setMemorySize(String memorySize) {
this.memorySize = memorySize;
}
public String[] getRegionNames() {
return this.regionNames;
}
public void setRegionNames(String[] regionNames) {
this.regionNames = regionNames;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\CacheProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void deletePermRuleByPermId(String id) {
LambdaQueryWrapper<SysPermissionDataRule> query = new LambdaQueryWrapper<>();
query.eq(SysPermissionDataRule::getPermissionId, id);
Long countValue = this.permissionDataRuleService.count(query);
if(countValue > 0) {
this.permissionDataRuleService.remove(query);
}
}
/**
* 获取模糊匹配规则的数据权限URL
*/
@Override
@Cacheable(value = CacheConstant.SYS_DATA_PERMISSIONS_CACHE)
public List<String> queryPermissionUrlWithStar() {
return this.baseMapper.queryPermissionUrlWithStar();
}
@Override
public boolean hasPermission(String username, SysPermission sysPermission) {
int count = baseMapper.queryCountByUsername(username,sysPermission);
if(count>0){
return true;
}else{
return false;
}
}
@Override
public boolean hasPermission(String username, String url) {
SysPermission sysPermission = new SysPermission();
sysPermission.setUrl(url);
int count = baseMapper.queryCountByUsername(username,sysPermission);
if(count>0){
return true;
}else{
return false; | }
}
@Override
public List<SysPermission> queryDepartPermissionList(String departId) {
return sysPermissionMapper.queryDepartPermissionList(departId);
}
@Override
public boolean checkPermDuplication(String id, String url,Boolean alwaysShow) {
QueryWrapper<SysPermission> qw=new QueryWrapper();
qw.lambda().eq(true,SysPermission::getUrl,url).ne(oConvertUtils.isNotEmpty(id),SysPermission::getId,id).eq(true,SysPermission::isAlwaysShow,alwaysShow);
return count(qw)==0;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysPermissionServiceImpl.java | 2 |
请完成以下Java代码 | protected String getServiceUrl() {
if (instance.getServiceUrl() != null) {
return instance.getServiceUrl();
}
return UriComponentsBuilder.fromUriString(getServiceBaseUrl())
.path(getServicePath())
.path(getWebfluxBasePath())
.toUriString();
}
@Override
protected String getManagementBaseUrl() {
String baseUrl = this.instance.getManagementBaseUrl();
if (StringUtils.hasText(baseUrl)) {
return baseUrl;
}
if (isManagementPortEqual()) {
return this.getServiceUrl();
}
Ssl ssl = (this.management.getSsl() != null) ? this.management.getSsl() : this.server.getSsl();
return UriComponentsBuilder.newInstance()
.scheme(getScheme(ssl)) | .host(getManagementHost())
.port(getLocalManagementPort())
.path(getManagementContextPath())
.toUriString();
}
protected String getManagementContextPath() {
return management.getBasePath();
}
protected String getWebfluxBasePath() {
return webflux.getBasePath();
}
} | repos\spring-boot-admin-master\spring-boot-admin-client\src\main\java\de\codecentric\boot\admin\client\registration\ReactiveApplicationFactory.java | 1 |
请完成以下Java代码 | private ImmutableSet<ProductId> retrieveRelevantProductIds(@NonNull final DocumentFilterList filters)
{
final OrgId orgId = OrgId.ofRepoIdOrAny(Env.getAD_Org_ID(Env.getCtx()));
final int limit = Services
.get(ISysConfigBL.class)
.getIntValue(SYSCONFIG_EMPTY_PRODUCTS_LIMIT, DEFAULT_EMPTY_PRODUCTS_LIMIT);
final CacheKey cacheKey = new CacheKey(
orgId,
ProductFilterUtil.extractProductFilterVO(filters),
limit);
return productFilterVOToProducts
.getOrLoad(cacheKey, () -> retrieveProductsFor(cacheKey));
}
@NonNull
private List<ProductWithDemandSupply> getQtyRecords(
@NonNull final List<I_MD_Cockpit> cockpitRecords,
@NonNull final List<I_MD_Stock> stockRecords)
{
final Set<ProductId> productIds = Stream.concat(
cockpitRecords.stream().map(I_MD_Cockpit::getM_Product_ID),
stockRecords.stream().map(I_MD_Stock::getM_Product_ID))
.map(ProductId::ofRepoIdOrNull)
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
return qtyDemandSupplyRepository.getByProductIds(productIds).getAll();
}
private static ImmutableSet<ProductId> retrieveProductsFor(@NonNull final CacheKey cacheKey)
{
final OrgId orgId = cacheKey.getOrgId();
final ProductFilterVO productFilterVO = cacheKey.getProductFilterVO();
final int limit = cacheKey.getLimit();
final IQueryFilter<I_M_Product> productQueryFilter = ProductFilterUtil.createProductQueryFilterOrNull(
productFilterVO,
false/* nullForEmptyFilterVO */);
final IQueryBuilder<I_M_Product> queryBuilder = Services.get(IQueryBL.class)
.createQueryBuilder(I_M_Product.class)
.addInArrayFilter(I_M_Product.COLUMNNAME_AD_Org_ID, orgId.getRepoId(), 0)
.addEqualsFilter(I_M_Product.COLUMN_IsStocked, true)
.filter(productQueryFilter)
.orderBy(I_M_Product.COLUMN_Value); | if (limit > 0)
{
queryBuilder.setLimit(QueryLimit.ofInt(limit));
}
return queryBuilder
.create()
.idsAsSet(ProductId::ofRepoId);
}
@Value
private static class CacheKey
{
@NonNull
OrgId orgId;
@NonNull
ProductFilterVO productFilterVO;
int limit;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\MaterialCockpitRowsLoader.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getIpAddr(HttpServletRequest request) {
String ipAddress = null;
ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
log.error("未知主机",e);
}
ipAddress = inet.getHostAddress();
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
if (ipAddress != null && ipAddress.length() > 15) {
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
return ipAddress;
}
/**
* 获取refererUrl
*/ | public String getRefererUrl(HttpServletRequest request) {
return request.getHeader("referer");
}
public String readRequest(HttpServletRequest request) throws IOException {
StringBuilder sb = new StringBuilder();
try {
String line;
while ((line = request.getReader().readLine()) != null) {
sb.append(line);
}
} finally {
request.getReader().close();
}
return sb.toString();
}
public void write(HttpServletResponse response, String s) {
PrintWriter out = null;
try {
out = response.getWriter();
out.print(s);
} catch (IOException e) {
log.error("返回支付结果接收状态到微信支付错误", e);
} finally {
out.close();
}
}
} | repos\roncoo-pay-master\roncoo-pay-web-gateway\src\main\java\com\roncoo\pay\controller\common\BaseController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public JwtPair authenticateByTwoFaConfigurationToken(HttpServletRequest servletRequest) throws ThingsboardException {
SecurityUser user = getCurrentUser();
if (twoFactorAuthService.isTwoFaEnabled(user.getTenantId(), user)) {
logLogInAction(servletRequest, user, null);
return createTokenPair(user);
} else {
IllegalArgumentException error = new IllegalArgumentException("2FA is not configured");
logLogInAction(servletRequest, user, error);
throw error;
}
}
private JwtPair createTokenPair(SecurityUser user) {
log.debug("[{}][{}] Creating token pair for user", user.getTenantId(), user.getId());
user = new SecurityUser(userService.findUserById(user.getTenantId(), user.getId()), true, user.getUserPrincipal());
return tokenFactory.createTokenPair(user);
} | private void logLogInAction(HttpServletRequest servletRequest, SecurityUser user, Exception error) {
systemSecurityService.logLoginAction(user, new RestAuthenticationDetails(servletRequest), ActionType.LOGIN, error);
}
@Data
@AllArgsConstructor
@Builder
public static class TwoFaProviderInfo {
private TwoFaProviderType type;
private boolean isDefault;
private String contact;
private Integer minVerificationCodeSendPeriod;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\TwoFactorAuthController.java | 2 |
请完成以下Java代码 | public Object getConfig() {
return config;
}
@Override
public String toString() {
return String.format("RemoteAddrs: %s", config.getSources());
}
};
}
private void addSource(List<IpSubnetFilterRule> sources, String source) {
if (!source.contains("/")) { // no netmask, add default
source = source + "/32";
}
String[] ipAddressCidrPrefix = source.split("/", 2);
String ipAddress = ipAddressCidrPrefix[0];
int cidrPrefix = Integer.parseInt(ipAddressCidrPrefix[1]);
sources.add(new IpSubnetFilterRule(ipAddress, cidrPrefix, IpFilterRuleType.ACCEPT));
}
public static class Config {
@NotEmpty
private List<String> sources = new ArrayList<>();
@NotNull
private RemoteAddressResolver remoteAddressResolver = new RemoteAddressResolver() {
};
public List<String> getSources() { | return sources;
}
public Config setSources(List<String> sources) {
this.sources = sources;
return this;
}
public Config setSources(String... sources) {
this.sources = Arrays.asList(sources);
return this;
}
public Config setRemoteAddressResolver(RemoteAddressResolver remoteAddressResolver) {
this.remoteAddressResolver = remoteAddressResolver;
return this;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\handler\predicate\RemoteAddrRoutePredicateFactory.java | 1 |
请完成以下Java代码 | public String getNbOfNtries() {
return nbOfNtries;
}
/**
* Sets the value of the nbOfNtries property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNbOfNtries(String value) {
this.nbOfNtries = value;
}
/**
* Gets the value of the sum property.
*
* @return
* possible object is
* {@link BigDecimal } | *
*/
public BigDecimal getSum() {
return sum;
}
/**
* Sets the value of the sum property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setSum(BigDecimal value) {
this.sum = 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\NumberAndSumOfTransactions1.java | 1 |
请完成以下Java代码 | public I_C_CycleStep getC_CycleStep() throws RuntimeException
{
return (I_C_CycleStep)MTable.get(getCtx(), I_C_CycleStep.Table_Name)
.getPO(getC_CycleStep_ID(), get_TrxName()); }
/** Set Cycle Step.
@param C_CycleStep_ID
The step for this Cycle
*/
public void setC_CycleStep_ID (int C_CycleStep_ID)
{
if (C_CycleStep_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CycleStep_ID, Integer.valueOf(C_CycleStep_ID));
}
/** Get Cycle Step.
@return The step for this Cycle
*/
public int getC_CycleStep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CycleStep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_Phase getC_Phase() throws RuntimeException
{
return (I_C_Phase)MTable.get(getCtx(), I_C_Phase.Table_Name)
.getPO(getC_Phase_ID(), get_TrxName()); } | /** Set Standard Phase.
@param C_Phase_ID
Standard Phase of the Project Type
*/
public void setC_Phase_ID (int C_Phase_ID)
{
if (C_Phase_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Phase_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Phase_ID, Integer.valueOf(C_Phase_ID));
}
/** Get Standard Phase.
@return Standard Phase of the Project Type
*/
public int getC_Phase_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Phase_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CyclePhase.java | 1 |
请完成以下Java代码 | public boolean isSkipIoMappings() {
return skipIoMappings;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
public List<ProcessInstanceModificationInstructionDto> getInstructions() {
return instructions;
}
public void setInstructions(List<ProcessInstanceModificationInstructionDto> instructions) {
this.instructions = instructions;
} | public void applyTo(ProcessInstanceModificationBuilder builder, ProcessEngine engine, ObjectMapper objectMapper) {
for (ProcessInstanceModificationInstructionDto instruction : instructions) {
instruction.applyTo(builder, engine, objectMapper);
}
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\modification\ProcessInstanceModificationDto.java | 1 |
请完成以下Spring Boot application配置 | server.port=8443
# enable/disable https
server.ssl.enabled=true
# keystore format
server.ssl.key-store-type=PKCS12
# keystore location
server.ssl.key-store=classpath:keystore/keystore.p12
# keystore password
server.ssl.key-store-password=changeit
server.ssl.key-alias=baeldung
# SSL protocol to use
server.ssl.protocol=TLS
# Enabled SSL protocols
server.ssl.enabled-protocols=TLSv1.2
#serv | er.ssl.client-auth=need
#trust store location
#server.ssl.trust-store=classpath:keystore/truststore.p12
#trust store password
#server.ssl.trust-store-password=changeit | repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\resources\application-tls.properties | 2 |
请完成以下Java代码 | public java.math.BigDecimal getDK_ParcelWeight ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelWeight);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Paketbreite.
@param DK_ParcelWidth Paketbreite */
@Override
public void setDK_ParcelWidth (java.math.BigDecimal DK_ParcelWidth)
{
set_Value (COLUMNNAME_DK_ParcelWidth, DK_ParcelWidth);
}
/** Get Paketbreite.
@return Paketbreite */
@Override
public java.math.BigDecimal getDK_ParcelWidth ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DK_ParcelWidth);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Referenz.
@param DK_Reference Referenz */
@Override
public void setDK_Reference (java.lang.String DK_Reference)
{
set_Value (COLUMNNAME_DK_Reference, DK_Reference); | }
/** Get Referenz.
@return Referenz */
@Override
public java.lang.String getDK_Reference ()
{
return (java.lang.String)get_Value(COLUMNNAME_DK_Reference);
}
/** Set Zeile Nr..
@param Line
Einzelne Zeile in dem Dokument
*/
@Override
public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Einzelne Zeile in dem Dokument
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_DeliveryOrderLine.java | 1 |
请完成以下Java代码 | public void setWorkingTime (final @Nullable BigDecimal WorkingTime)
{
set_Value (COLUMNNAME_WorkingTime, WorkingTime);
}
@Override
public BigDecimal getWorkingTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WorkingTime);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setYield (final int Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public int getYield()
{
return get_ValueAsInt(COLUMNNAME_Yield);
} | @Override
public void setC_Manufacturing_Aggregation_ID (final int C_Manufacturing_Aggregation_ID)
{
if (C_Manufacturing_Aggregation_ID < 1)
set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, null);
else
set_Value (COLUMNNAME_C_Manufacturing_Aggregation_ID, C_Manufacturing_Aggregation_ID);
}
@Override
public int getC_Manufacturing_Aggregation_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Manufacturing_Aggregation_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Product_Planning.java | 1 |
请完成以下Java代码 | private static void onProductChangedCallout(final ICalloutField calloutField)
{
final QuickInput quickInput = QuickInput.getQuickInputOrNull(calloutField);
if (quickInput == null)
{
return;
}
final IForecastLineQuickInput quickInputModel = quickInput.getQuickInputDocumentAs(IForecastLineQuickInput.class);
final LookupValue productLookupValue = quickInputModel.getM_Product_ID();
if (productLookupValue == null)
{
return;
}
final ProductAndAttributes productAndAttributes = ProductLookupDescriptor.toProductAndAttributes(productLookupValue);
final ProductId quickInputProduct = productAndAttributes.getProductId();
final I_M_Forecast forecast = quickInput.getRootDocumentAs(I_M_Forecast.class);
Services.get(IHUOrderBL.class).findM_HU_PI_Item_ProductForForecast(forecast, quickInputProduct, quickInputModel::setM_HU_PI_Item_Product);
}
private DocumentEntityDescriptor createEntityDescriptor(
final DocumentId documentTypeId,
final DetailId detailId,
@NonNull final Optional<SOTrx> soTrx)
{
return createDescriptorBuilder(documentTypeId, detailId)
.addField(createProductFieldBuilder())
.addFieldIf(QuickInputConstants.isEnablePackingInstructionsField(), this::createPackingInstructionFieldBuilder)
.addField(createQuantityFieldBuilder())
.setIsSOTrx(soTrx)
.build();
}
private Builder createProductFieldBuilder()
{
return DocumentFieldDescriptor.builder(IForecastLineQuickInput.COLUMNNAME_M_Product_ID)
.setCaption(Services.get(IMsgBL.class).translatable(IForecastLineQuickInput.COLUMNNAME_M_Product_ID)) | //
.setWidgetType(DocumentFieldWidgetType.Lookup)
.setLookupDescriptorProvider(ProductLookupDescriptor.builderWithStockInfo()
.bpartnerParamName(I_M_Forecast.COLUMNNAME_C_BPartner_ID)
.pricingDateParamName(I_M_Forecast.COLUMNNAME_DatePromised)
.availableStockDateParamName(I_M_Forecast.COLUMNNAME_DatePromised)
.availableToPromiseAdapter(availableToPromiseAdapter)
.availableForSaleAdapter(availableForSaleAdapter)
.availableForSalesConfigRepo(availableForSalesConfigRepo)
.build())
.setReadonlyLogic(ConstantLogicExpression.FALSE)
.setAlwaysUpdateable(true)
.setMandatoryLogic(ConstantLogicExpression.TRUE)
.setDisplayLogic(ConstantLogicExpression.TRUE)
.addCallout(ForecastLineQuickInputDescriptorFactory::onProductChangedCallout)
.addCharacteristic(Characteristic.PublicField);
}
private static QuickInputLayoutDescriptor createLayout(final DocumentEntityDescriptor entityDescriptor)
{
return QuickInputLayoutDescriptor.onlyFields(entityDescriptor, new String[][] {
{ "M_Product_ID", "M_HU_PI_Item_Product_ID" } //
, { "Qty" }
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\forecastline\ForecastLineQuickInputDescriptorFactory.java | 1 |
请完成以下Java代码 | public IMutableHUContext createMutableHUContext(final IContextAware contextProvider)
{
return new MutableHUContext(contextProvider);
}
@Override
public final IHUContext deriveWithTrxName(final IHUContext huContext, final String trxNameNew)
{
// FIXME: handle the case of SaveOnCommit Storage and Attributes when changing transaction name
//
// Check: if transaction name was not changed, do nothing, return the old context
final String contextTrxName = huContext.getTrxName();// // TODO tbp: here the context has wrong org. WHYYYYY
final ITrxManager trxManager = Services.get(ITrxManager.class);
if (trxManager.isSameTrxName(contextTrxName, trxNameNew))
{ | return huContext;
}
final IMutableHUContext huContextNew = huContext.copyAsMutable();
huContextNew.setTrxName(trxNameNew);
configureProcessingContext(huContextNew);
return huContextNew;
}
@Override
public String toString()
{
return "HUContextFactory []";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUContextFactory.java | 1 |
请完成以下Spring Boot application配置 | context-path: /
micronaut:
router:
versioning:
enabled: true
default-version: 2
parameter:
enabled: true
names: 'v,api-version'
header:
enabled: true
names:
- 'X-API-VERSION'
application:
| name: hello-world-server
server:
port: ${random.port}
langchain4j:
open-ai:
api-key: ${OPENAI_API_KEY} | repos\tutorials-master\microservices-modules\micronaut\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public String getMemberPhone() {
return memberPhone;
}
public void setMemberPhone(String memberPhone) {
this.memberPhone = memberPhone;
}
public String getProductName() {
return productName;
}
public void setProductName(String productName) {
this.productName = productName;
}
public Date getSubscribeTime() {
return subscribeTime;
}
public void setSubscribeTime(Date subscribeTime) {
this.subscribeTime = subscribeTime;
}
public Date getSendTime() { | return sendTime;
}
public void setSendTime(Date sendTime) {
this.sendTime = sendTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", memberId=").append(memberId);
sb.append(", productId=").append(productId);
sb.append(", memberPhone=").append(memberPhone);
sb.append(", productName=").append(productName);
sb.append(", subscribeTime=").append(subscribeTime);
sb.append(", sendTime=").append(sendTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsFlashPromotionLog.java | 1 |
请完成以下Java代码 | private <T> T deserializePart(HttpServletRequest httpServletRequest, String name, Type type) {
try {
Part part = httpServletRequest.getPart(name);
if (part == null) {
return null;
}
return (T) this.genericHttpMessageConverter.read(type, null, new JsonMultipartInputMessage(part));
} catch (IOException | ServletException e) {
throw new RuntimeException(e);
}
}
@SuppressWarnings("unchecked")
private Map<String, Object> getFromMapOrEmpty(Map<String, Object> input, String key) {
if (input.containsKey(key)) {
return (Map<String, Object>) input.get(key);
} else {
return new HashMap<>(); | }
}
private static Map<String, MultipartFile> readMultipartFiles(HttpServletRequest httpServletRequest) {
Assert.isInstanceOf(MultipartHttpServletRequest.class, httpServletRequest, "Request should be of type MultipartHttpServletRequest");
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) httpServletRequest;
return multipartHttpServletRequest.getFileMap();
}
private static MediaType selectResponseMediaType(ServerRequest serverRequest) {
for (MediaType accepted : serverRequest.headers().accept()) {
if (SUPPORTED_MEDIA_TYPES.contains(accepted)) {
return accepted;
}
}
return MediaType.APPLICATION_JSON;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-graphql-2\src\main\java\com\baeldung\graphql\fileupload\MultipartGraphQlHttpHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public abstract class AbstractManager {
protected EntityLinkServiceConfiguration entityLinkServiceConfiguration;
public AbstractManager(EntityLinkServiceConfiguration entityLinkServiceConfiguration) {
this.entityLinkServiceConfiguration = entityLinkServiceConfiguration;
}
// Command scoped
protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
// Engine scoped | protected EntityLinkServiceConfiguration getEntityLinkServiceConfiguration() {
return entityLinkServiceConfiguration;
}
protected Clock getClock() {
return getEntityLinkServiceConfiguration().getClock();
}
protected FlowableEventDispatcher getEventDispatcher() {
return getEntityLinkServiceConfiguration().getEventDispatcher();
}
protected EntityLinkEntityManager getEntityLinkEntityManager() {
return getEntityLinkServiceConfiguration().getEntityLinkEntityManager();
}
protected HistoricEntityLinkEntityManager getHistoricEntityLinkEntityManager() {
return getEntityLinkServiceConfiguration().getHistoricEntityLinkEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\AbstractManager.java | 2 |
请完成以下Java代码 | public EventLogEntryEntity generateEventLogEntry(CommandContext commandContext) {
Map<String, Object> data = new HashMap<String, Object>();
try {
data.put("ip", InetAddress.getLocalHost().getHostAddress()); // Note
// that
// this
// might
// give
// the
// wrong
// ip
// address
// in
// case
// of | // multiple
// network
// interfaces
// -
// but
// it's
// better
// than
// nothing.
} catch (UnknownHostException e) {
// Best effort
}
return createEventLogEntry(data);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\event\logger\handler\EngineClosedEventHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PPOrderCostId implements RepoIdAware
{
@JsonCreator
public static PPOrderCostId ofRepoId(final int repoId)
{
return new PPOrderCostId(repoId);
}
public static PPOrderCostId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new PPOrderCostId(repoId) : null;
}
public static Optional<PPOrderCostId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(final PPOrderCostId id)
{
return toRepoIdOr(id, -1);
} | public static int toRepoIdOr(final PPOrderCostId id, final int defaultValue)
{
return id != null ? id.getRepoId() : defaultValue;
}
int repoId;
private PPOrderCostId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_Cost_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderCostId.java | 2 |
请完成以下Java代码 | public class VariableListConverter extends
JacksonAwareStringToTypeConverter<List<VariableQueryParameterDto>> {
private static final String EXPRESSION_DELIMITER = ",";
private static final String ATTRIBUTE_DELIMITER = "_";
/**
* Expects a query parameter of multiple variable expressions formatted as KEY_OPERATOR_VALUE, e.g. aVariable_eq_aValue.
* Multiple values are expected to be comma-separated.
*/
@Override
public List<VariableQueryParameterDto> convertQueryParameterToType(String value) {
String[] expressions = value.split(EXPRESSION_DELIMITER);
List<VariableQueryParameterDto> queryVariables = new ArrayList<VariableQueryParameterDto>();
for (String expression : expressions) { | String[] valueTriple = expression.split(ATTRIBUTE_DELIMITER);
if (valueTriple.length != 3) {
throw new InvalidRequestException(Status.BAD_REQUEST, "variable query parameter has to have format KEY_OPERATOR_VALUE.");
}
VariableQueryParameterDto queryVariable = new VariableQueryParameterDto();
queryVariable.setName(valueTriple[0]);
queryVariable.setOperator(valueTriple[1]);
queryVariable.setValue(valueTriple[2]);
queryVariables.add(queryVariable);
}
return queryVariables;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\converter\VariableListConverter.java | 1 |
请完成以下Java代码 | public int nextId(String tableName)
{
nextId++;
return nextId;
}
public void reset()
{
nextId = DEFAULT_FirstId;
}
}
@ToString
private static class PerTableSequence implements POJONextIdSupplier
{
private final int firstId = SingleSharedSequence.DEFAULT_FirstId * 10; // multiply by 10 to prevent overlapping in case we switch from Single Sequence | private final HashMap<String, AtomicInteger> nextIds = new HashMap<>();
@Override
public int nextId(@NonNull final String tableName)
{
final String tableNameNorm = tableName.trim().toLowerCase();
return nextIds.computeIfAbsent(tableNameNorm, k -> new AtomicInteger(firstId))
.getAndIncrement();
}
public void reset()
{
nextIds.clear();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJONextIdSuppliers.java | 1 |
请完成以下Java代码 | public void beforeCommit(Supplier<? extends Mono<Void>> action) {
}
@Override
public boolean isCommitted() {
return false;
}
boolean isCached() {
return this.cached;
}
@Override
public HttpHeaders getHeaders() {
return this.httpHeaders;
}
@Override
public DataBufferFactory bufferFactory() {
return this.bufferFactory;
}
/**
* Return the request body, or an error stream if the body was never set or when.
* @return body as {@link Flux}
*/
public Flux<DataBuffer> getBody() {
if (body == null) {
return Flux
.error(new IllegalStateException("The body is not set. " + "Did handling complete with success?"));
}
return this.body;
} | public Mono<Void> writeWith(Publisher<? extends DataBuffer> body) {
this.body = Flux.from(body);
this.cached = true;
return Mono.empty();
}
@Override
public Mono<Void> writeAndFlushWith(Publisher<? extends Publisher<? extends DataBuffer>> body) {
return writeWith(Flux.from(body).flatMap(p -> p));
}
@Override
public Mono<Void> setComplete() {
return writeWith(Flux.empty());
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\rewrite\CachedBodyOutputMessage.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HUsToReturnViewFactory extends HUEditorViewFactoryTemplate
{
static final String Window_ID_String = "541011"; // FIXME: hardcoded
private static final WindowId Window_ID = WindowId.fromJson(Window_ID_String);
public static final String PARAM_HUsToReturnViewContext = "HUsToReturnViewContext";
protected HUsToReturnViewFactory()
{
super(ImmutableList.of());
}
public static CreateViewRequest createViewRequest(@NonNull final InOutId customerReturnsId)
{
return CreateViewRequest.builder(Window_ID)
.setParameter(PARAM_HUsToReturnViewContext, HUsToReturnViewContext.builder()
.customerReturnsId(customerReturnsId)
.build())
.build();
}
@Override
protected void customizeViewLayout(
@NonNull final ViewLayout.Builder viewLayoutBuilder,
final JSONViewDataType viewDataType)
{
viewLayoutBuilder
.clearElements()
.addElementsFromViewRowClassAndFieldNames(HUEditorRow.class,
viewDataType,
ClassViewColumnOverrides.builder(HUEditorRow.FIELDNAME_HUCode).restrictToMediaType(MediaType.SCREEN).build(),
ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_Locator),
ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_Product),
ClassViewColumnOverrides.builder(HUEditorRow.FIELDNAME_PackingInfo).restrictToMediaType(MediaType.SCREEN).build(),
ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_QtyCU),
ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_UOM),
ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_SerialNo),
ClassViewColumnOverrides.ofFieldName(HUEditorRow.FIELDNAME_ServiceContract), | ClassViewColumnOverrides.builder(HUEditorRow.FIELDNAME_HUStatus).restrictToMediaType(MediaType.SCREEN).build());
}
@Override
protected void customizeHUEditorView(final HUEditorViewBuilder huViewBuilder)
{
huViewBuilder.assertParameterSet(PARAM_HUsToReturnViewContext);
huViewBuilder.considerTableRelatedProcessDescriptors(false)
.addAdditionalRelatedProcessDescriptor(createProcessDescriptor(HUsToReturn_SelectHU.class))
.addAdditionalRelatedProcessDescriptor(createProcessDescriptor(HUsToReturn_CreateShippedHU.class));
}
@Nullable
@Override
protected String getAdditionalSqlWhereClause()
{
return I_M_HU.COLUMNNAME_HUStatus + "=" + DB.TO_STRING(X_M_HU.HUSTATUS_Shipped);
}
/**
* This view is not configuration dependent always should be false to execute the customizeViewLayout method
*/
@Override
protected boolean isAlwaysUseSameLayout()
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.webui\src\main\java\de\metas\servicerepair\customerreturns\HUsToReturnViewFactory.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Optional<PlatformTwoFaSettings> getPlatformTwoFaSettings(TenantId tenantId, boolean sysadminSettingsAsDefault) {
return Optional.ofNullable(adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, TWO_FACTOR_AUTH_SETTINGS_KEY))
.map(adminSettings -> JacksonUtil.treeToValue(adminSettings.getJsonValue(), PlatformTwoFaSettings.class));
}
@Override
public PlatformTwoFaSettings savePlatformTwoFaSettings(TenantId tenantId, PlatformTwoFaSettings twoFactorAuthSettings) throws ThingsboardException {
ConstraintValidator.validateFields(twoFactorAuthSettings);
for (TwoFaProviderConfig providerConfig : twoFactorAuthSettings.getProviders()) {
twoFactorAuthService.checkProvider(tenantId, providerConfig.getProviderType());
}
if (tenantId.isSysTenantId()) {
if (twoFactorAuthSettings.isEnforceTwoFa()) {
if (twoFactorAuthSettings.getProviders().isEmpty()) {
throw new DataValidationException("At least one 2FA provider is required if enforcing is enabled");
}
if (twoFactorAuthSettings.getEnforcedUsersFilter() == null) {
throw new DataValidationException("Users filter to enforce 2FA for is required");
}
}
} else {
twoFactorAuthSettings.setEnforceTwoFa(false);
twoFactorAuthSettings.setEnforcedUsersFilter(null);
}
AdminSettings settings = Optional.ofNullable(adminSettingsService.findAdminSettingsByKey(tenantId, TWO_FACTOR_AUTH_SETTINGS_KEY))
.orElseGet(() -> { | AdminSettings newSettings = new AdminSettings();
newSettings.setKey(TWO_FACTOR_AUTH_SETTINGS_KEY);
return newSettings;
});
settings.setJsonValue(JacksonUtil.valueToTree(twoFactorAuthSettings));
adminSettingsService.saveAdminSettings(tenantId, settings);
return twoFactorAuthSettings;
}
@Override
public void deletePlatformTwoFaSettings(TenantId tenantId) {
Optional.ofNullable(adminSettingsService.findAdminSettingsByKey(tenantId, TWO_FACTOR_AUTH_SETTINGS_KEY))
.ifPresent(adminSettings -> adminSettingsDao.removeById(tenantId, adminSettings.getId().getId()));
}
private void checkAccountTwoFaSettings(TenantId tenantId, User user, AccountTwoFaSettings settings) {
if (settings.getConfigs().isEmpty()) {
if (twoFactorAuthService.isEnforceTwoFaEnabled(tenantId, user)) {
throw new DataValidationException("At least one 2FA provider is required");
}
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\mfa\config\DefaultTwoFaConfigManager.java | 2 |
请完成以下Java代码 | public class Hal {
public static final String APPLICATION_HAL_JSON = "application/hal+json";
public static final MediaType APPLICATION_HAL_JSON_TYPE = new MediaType("application", "hal+json");
public static Hal instance = new Hal();
protected Map<Class<?>, HalLinkResolver> halLinkResolvers = new HashMap<Class<?>, HalLinkResolver>();
protected Map<Class<?>, Cache> halRelationCaches = new HashMap<Class<?>, Cache>();
public Hal() {
// register the built-in resolvers
halLinkResolvers.put(UserRestService.class, new HalUserResolver());
halLinkResolvers.put(GroupRestService.class, new HalGroupResolver());
halLinkResolvers.put(ProcessDefinitionRestService.class, new HalProcessDefinitionResolver());
halLinkResolvers.put(CaseDefinitionRestService.class, new HalCaseDefinitionResolver());
halLinkResolvers.put(IdentityRestService.class, new HalIdentityLinkResolver());
}
public static Hal getInstance() {
return instance;
}
public HalLinker createLinker(HalResource<?> resource) {
return new HalLinker(this, resource); | }
public HalLinkResolver getLinkResolver(Class<?> resourceClass) {
return halLinkResolvers.get(resourceClass);
}
public void registerHalRelationCache(Class<?> entityClass, Cache cache) {
halRelationCaches.put(entityClass, cache);
}
public Cache getHalRelationCache(Class<?> resourceClass) {
return halRelationCaches.get(resourceClass);
}
public void destroyHalRelationCaches() {
for (Cache cache : halRelationCaches.values()) {
cache.destroy();
}
halRelationCaches.clear();
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\Hal.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class X_Carrier_Service extends org.compiere.model.PO implements I_Carrier_Service, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1787662385L;
/** Standard Constructor */
public X_Carrier_Service (final Properties ctx, final int Carrier_Service_ID, @Nullable final String trxName)
{
super (ctx, Carrier_Service_ID, trxName);
}
/** Load Constructor */
public X_Carrier_Service (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setCarrier_Service_ID (final int Carrier_Service_ID)
{
if (Carrier_Service_ID < 1)
set_ValueNoCheck (COLUMNNAME_Carrier_Service_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Carrier_Service_ID, Carrier_Service_ID);
}
@Override
public int getCarrier_Service_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_Service_ID);
}
@Override
public void setExternalId (final java.lang.String ExternalId)
{ | set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
}
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Service.java | 2 |
请完成以下Java代码 | public class Car {
@PrimaryKey
private UUID id;
private String make;
private String model;
private int year;
public Car(UUID id, String make, String model, int year) {
this.id = id;
this.make = make;
this.model = model;
this.year = year;
}
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
} | public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Car car = (Car) o;
return year == car.year && Objects.equals(id, car.id) && Objects.equals(make, car.make) && Objects.equals(model, car.model);
}
@Override
public int hashCode() {
return Objects.hash(id, make, model, year);
}
} | repos\tutorials-master\persistence-modules\spring-data-cassandra-2\src\main\java\org\baeldung\springcassandra\model\Car.java | 1 |
请完成以下Java代码 | public void init(final long delayMillis)
{
// If it's NULL then there is no point to schedule a timer
if (executor instanceof NullQueueProcessorsExecutor)
{
return;
}
// Do nothing if already initialized
if (delayedInit.isDone())
{
return;
}
delayedInit.run(delayMillis);
}
/**
* Initialize executors now.
*
* NOTE: never ever call this method directly. It's supposed to be called from {@link #delayedInit}.
*/
private void initNow()
{
// NOTE: don't check if it's already initialized because at the time when this method is called the "initialized" flag was already set,
// to prevent future executions.
// If it's NULL then there is no point to load all processors
if (executor instanceof NullQueueProcessorsExecutor)
{
return;
}
// Remove all queue processors. It shall be none, but just to make sure
executor.shutdown();
for (final I_C_Queue_Processor processorDef : queueDAO.retrieveAllProcessors())
{
executor.addQueueProcessor(processorDef);
}
} | @Override
public void removeAllQueueProcessors()
{
delayedInit.cancelAndReset();
executor.shutdown();
}
@Override
public IQueueProcessorsExecutor getExecutor()
{
// Make sure executor was initialized.
// Else it makes no sense to return it because could lead to data corruption.
if (!isInitialized())
{
throw new IllegalStateException("Service not initialized");
}
return executor;
}
@Override
public boolean isInitialized()
{
return delayedInit.isDone();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\QueueProcessorExecutorService.java | 1 |
请完成以下Java代码 | public class DerbyApplicationDemo {
public static void main(String[] args) {
runner("jdbc:derby:baeldung;create=true");
}
private static void runner(String urlConnection) {
try {
Connection con = DriverManager.getConnection(urlConnection);
Statement statement = con.createStatement();
if (!isTableExists("authors", con)) {
String createSQL = "CREATE TABLE authors (id INT PRIMARY KEY,first_name VARCHAR(255),last_name VARCHAR(255))";
statement.execute(createSQL);
String insertSQL = "INSERT INTO authors VALUES (1, 'arash','ariani')";
statement.execute(insertSQL);
}
String selectSQL = "SELECT * FROM authors"; | ResultSet result = statement.executeQuery(selectSQL);
while (result.next()) {
// use result here
}
} catch (SQLException e) {
e.printStackTrace();
}
}
private static boolean isTableExists(String tableName, Connection connection) throws SQLException {
DatabaseMetaData meta = connection.getMetaData();
ResultSet result = meta.getTables(null, null, tableName.toUpperCase(), null);
return result.next();
}
} | repos\tutorials-master\persistence-modules\apache-derby\src\main\java\com\baeldung\derby\DerbyApplicationDemo.java | 1 |
请完成以下Java代码 | public void pushCurrentValue(String value) {
deque.addFirst(value != null ? value : NULL_VALUE);
updateMdcWithCurrentValue();
}
/**
* @return true if a value was obtained from the mdc
* and added to the stack
*/
public boolean pushCurrentValueFromMdc() {
if (isNotBlank(mdcName)) {
String mdcValue = MdcAccess.get(mdcName);
deque.addFirst(mdcValue != null ? mdcValue : NULL_VALUE);
return true;
} else {
return false;
}
}
public void removeCurrentValue() {
deque.removeFirst();
updateMdcWithCurrentValue();
}
public void clearMdcProperty() {
if (isNotBlank(mdcName)) {
MdcAccess.remove(mdcName);
}
}
public void updateMdcWithCurrentValue() {
if (isNotBlank(mdcName)) {
String currentValue = getCurrentValue();
if (isNull(currentValue)) {
MdcAccess.remove(mdcName);
} else {
MdcAccess.put(mdcName, currentValue);
}
}
}
}
protected static class ProcessDataSections {
/**
* Keeps track of when we added values to which stack (as we do not add
* a new value to every stack with every update, but only changed values)
*/
protected Deque<List<ProcessDataStack>> sections = new ArrayDeque<>();
protected boolean currentSectionSealed = true;
/** | * Adds a stack to the current section. If the current section is already sealed,
* a new section is created.
*/
public void addToCurrentSection(ProcessDataStack stack) {
List<ProcessDataStack> currentSection;
if (currentSectionSealed) {
currentSection = new ArrayList<>();
sections.addFirst(currentSection);
currentSectionSealed = false;
} else {
currentSection = sections.peekFirst();
}
currentSection.add(stack);
}
/**
* Pops the current section and removes the
* current values from the referenced stacks (including updates
* to the MDC)
*/
public void popCurrentSection() {
List<ProcessDataStack> section = sections.pollFirst();
if (section != null) {
section.forEach(ProcessDataStack::removeCurrentValue);
}
currentSectionSealed = true;
}
/**
* After a section is sealed, a new section will be created
* with the next call to {@link #addToCurrentSection(ProcessDataStack)}
*/
public void sealCurrentSection() {
currentSectionSealed = true;
}
public int size() {
return sections.size();
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\ProcessDataContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getUserName() {
return userName;
}
/**
* Sets the user name.
*
* @param userName the new user name
*/
public void setUserName(String userName) {
this.userName = userName;
}
/**
* Gets the email address.
*
* @return the email address
*/
public String getEmailAddress() {
return emailAddress;
}
/**
* Sets the email address.
*
* @param emailAddress the new email address
*/
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ((emailAddress == null) ? 0 : emailAddress.hashCode());
result = prime * result
+ ((firstName == null) ? 0 : firstName.hashCode());
result = prime * result
+ ((lastName == null) ? 0 : lastName.hashCode());
result = prime * result
+ ((userName == null) ? 0 : userName.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj) | return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
UserDTO other = (UserDTO) obj;
if (emailAddress == null) {
if (other.emailAddress != null)
return false;
} else if (!emailAddress.equals(other.emailAddress))
return false;
if (firstName == null) {
if (other.firstName != null)
return false;
} else if (!firstName.equals(other.firstName))
return false;
if (lastName == null) {
if (other.lastName != null)
return false;
} else if (!lastName.equals(other.lastName))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "UserDTO [firstName=" + firstName + ", lastName=" + lastName
+ ", userName=" + userName + ", emailAddress=" + emailAddress
+ "]";
}
} | repos\spring-boot-microservices-master\user-webservice\src\main\java\com\rohitghatol\microservices\user\dto\UserDTO.java | 2 |
请完成以下Java代码 | public List<String> filterUsingPatternCompile() {
List<String> numbers = List.of("one", "two", "three", "four", "five");
List<String> startWithTList = new ArrayList<>();
Pattern pattern = Pattern.compile("^t.*");
for (String item : numbers) {
Matcher matcher = pattern.matcher(item);
if (matcher.matches())
startWithTList.add(item);
}
return startWithTList;
}
public Map<Boolean, List<String>> filterUsingCollectorsPartitioningBy() {
List<String> fruits = List.of("apple", "banana", "apricot", "berry"); | Pattern pattern = Pattern.compile("^a.*");
return fruits.stream()
.collect(Collectors.partitioningBy(pattern.asPredicate()));
}
public static void main(String[] args) {
RegexFilterExample regexFilterExample = new RegexFilterExample();
regexFilterExample.filterUsingPatternAndPredicate();
regexFilterExample.filterUsingStringMatches();
regexFilterExample.filterUsingPatternCompile();
regexFilterExample.filterUsingCollectorsPartitioningBy();
}
} | repos\tutorials-master\core-java-modules\core-java-regex-3\src\main\java\com\baeldung\listregexfilter\RegexFilterExample.java | 1 |
请完成以下Java代码 | public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumerische Bezeichnung fuer diesen Eintrag
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | /** Get Name.
@return Alphanumerische Bezeichnung fuer diesen Eintrag
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Suchschluessel.
@param Value
Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschluessel.
@return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCost.java | 1 |
请完成以下Java代码 | public void setC_Queue_Element_ID (final int C_Queue_Element_ID)
{
if (C_Queue_Element_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_Element_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_Element_ID, C_Queue_Element_ID);
}
@Override
public int getC_Queue_Element_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_Element_ID);
}
@Override
public I_C_Queue_WorkPackage getC_Queue_WorkPackage()
{
return get_ValueAsPO(COLUMNNAME_C_Queue_WorkPackage_ID, I_C_Queue_WorkPackage.class);
}
@Override
public void setC_Queue_WorkPackage(final I_C_Queue_WorkPackage C_Queue_WorkPackage)
{
set_ValueFromPO(COLUMNNAME_C_Queue_WorkPackage_ID, I_C_Queue_WorkPackage.class, C_Queue_WorkPackage);
}
@Override
public void setC_Queue_WorkPackage_ID (final int C_Queue_WorkPackage_ID)
{
if (C_Queue_WorkPackage_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, C_Queue_WorkPackage_ID);
}
@Override
public int getC_Queue_WorkPackage_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_WorkPackage_ID);
}
@Override
public I_C_Queue_WorkPackage getC_Queue_Workpackage_Preceeding()
{
return get_ValueAsPO(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID, I_C_Queue_WorkPackage.class);
}
@Override
public void setC_Queue_Workpackage_Preceeding(final I_C_Queue_WorkPackage C_Queue_Workpackage_Preceeding) | {
set_ValueFromPO(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID, I_C_Queue_WorkPackage.class, C_Queue_Workpackage_Preceeding);
}
@Override
public void setC_Queue_Workpackage_Preceeding_ID (final int C_Queue_Workpackage_Preceeding_ID)
{
throw new IllegalArgumentException ("C_Queue_Workpackage_Preceeding_ID is virtual column"); }
@Override
public int getC_Queue_Workpackage_Preceeding_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Queue_Workpackage_Preceeding_ID);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_Element.java | 1 |
请完成以下Java代码 | public void start(){
monitorThread = new Thread(new Runnable() {
@Override
public void run() {
// monitor
while (!toStop) {
try {
List<Long> failLogIds = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().findFailJobLogIds(1000);
if (failLogIds!=null && !failLogIds.isEmpty()) {
for (long failLogId: failLogIds) {
// lock log
int lockRet = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().updateAlarmStatus(failLogId, 0, -1);
if (lockRet < 1) {
continue;
}
XxlJobLog log = XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().load(failLogId);
XxlJobInfo info = XxlJobAdminConfig.getAdminConfig().getXxlJobInfoDao().loadById(log.getJobId());
// 1、fail retry monitor
if (log.getExecutorFailRetryCount() > 0) {
JobTriggerPoolHelper.trigger(log.getJobId(), TriggerTypeEnum.RETRY, (log.getExecutorFailRetryCount()-1), log.getExecutorShardingParam(), log.getExecutorParam(), null);
String retryMsg = "<br><br><span style=\"color:#F39C12;\" > >>>>>>>>>>>"+ I18nUtil.getString("jobconf_trigger_type_retry") +"<<<<<<<<<<< </span><br>";
log.setTriggerMsg(log.getTriggerMsg() + retryMsg);
XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().updateTriggerInfo(log);
}
// 2、fail alarm monitor
int newAlarmStatus = 0; // 告警状态:0-默认、-1=锁定状态、1-无需告警、2-告警成功、3-告警失败
if (info != null) {
boolean alarmResult = XxlJobAdminConfig.getAdminConfig().getJobAlarmer().alarm(info, log);
newAlarmStatus = alarmResult?2:3;
} else {
newAlarmStatus = 1;
}
XxlJobAdminConfig.getAdminConfig().getXxlJobLogDao().updateAlarmStatus(failLogId, -1, newAlarmStatus);
}
}
} catch (Exception e) {
if (!toStop) {
logger.error(">>>>>>>>>>> xxl-job, job fail monitor thread error:{}", e);
}
} | try {
TimeUnit.SECONDS.sleep(10);
} catch (Exception e) {
if (!toStop) {
logger.error(e.getMessage(), e);
}
}
}
logger.info(">>>>>>>>>>> xxl-job, job fail monitor thread stop");
}
});
monitorThread.setDaemon(true);
monitorThread.setName("xxl-job, admin JobFailMonitorHelper");
monitorThread.start();
}
public void toStop(){
toStop = true;
// interrupt and wait
monitorThread.interrupt();
try {
monitorThread.join();
} catch (InterruptedException e) {
logger.error(e.getMessage(), e);
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\thread\JobFailMonitorHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static JsonMetasfreshId extractDeliveryAddressMFId(@NonNull final JsonResponseUpsert deliveryAddressUpsertResponse)
{
final JsonResponseUpsertItem responseUpsertItem = Check.singleElement(deliveryAddressUpsertResponse.getResponseItems());
if (responseUpsertItem.getMetasfreshId() == null)
{
throw new RuntimeException("Delivery address wasn't successfully persisted! ExternalId: " + responseUpsertItem.getIdentifier());
}
return responseUpsertItem.getMetasfreshId();
}
private void computeNextImportDate(@NonNull final Exchange exchange, @NonNull final Order orderCandidate)
{
final Instant nextImportSinceDateCandidate = AlbertaUtil.asInstant(orderCandidate.getCreationDate());
if (nextImportSinceDateCandidate == null)
{
return;
}
final NextImportSinceTimestamp currentNextImportSinceDate =
ProcessorHelper.getPropertyOrThrowError(exchange, GetOrdersRouteConstants.ROUTE_PROPERTY_UPDATED_AFTER, NextImportSinceTimestamp.class);
if (nextImportSinceDateCandidate.isAfter(currentNextImportSinceDate.getDate()))
{
currentNextImportSinceDate.setDate(nextImportSinceDateCandidate); | }
}
@NonNull
private static Optional<JsonRequestBPartnerLocationAndContact> getBillToBPartner(@NonNull final JsonResponseComposite jsonResponseComposite)
{
final Optional<JsonResponseLocation> billingAddressLocation = jsonResponseComposite.getLocations()
.stream()
.filter(JsonResponseLocation::isBillTo)
.findFirst();
if (billingAddressLocation.isEmpty())
{
return Optional.empty();
}
return Optional.of(JsonRequestBPartnerLocationAndContact.builder()
.bPartnerIdentifier(JsonMetasfreshId.toValueStr(jsonResponseComposite.getBpartner().getMetasfreshId()))
.bPartnerLocationIdentifier(JsonMetasfreshId.toValueStr(billingAddressLocation.get().getMetasfreshId()))
.build());
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\ordercandidate\processor\JsonOLCandCreateRequestProcessor.java | 2 |
请完成以下Java代码 | public String getVersion() {
return this.version;
}
/**
* Sets the version.
* @param version the version
*/
public void setVersion(String version) {
this.version = version;
}
@Override
public String getName() {
return this.name;
}
/**
* Sets the name.
* @param name the name
*/
public void setName(String name) {
this.name = name;
}
@Override
public String getDescription() {
return this.description;
}
/**
* Sets the description.
* @param description the description
*/
public void setDescription(String description) {
this.description = description;
}
@Override
public String getApplicationName() {
return this.applicationName;
}
/** | * Sets the application name.
* @param applicationName the application name
*/
public void setApplicationName(String applicationName) {
this.applicationName = applicationName;
}
@Override
public String getPackageName() {
if (StringUtils.hasText(this.packageName)) {
return this.packageName;
}
if (StringUtils.hasText(this.groupId) && StringUtils.hasText(this.artifactId)) {
return this.groupId + "." + this.artifactId;
}
return null;
}
/**
* Sets the package name.
* @param packageName the package name
*/
public void setPackageName(String packageName) {
this.packageName = packageName;
}
@Override
public String getBaseDirectory() {
return this.baseDirectory;
}
/**
* Sets the base directory.
* @param baseDirectory the base directory
*/
public void setBaseDirectory(String baseDirectory) {
this.baseDirectory = baseDirectory;
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\project\MutableProjectDescription.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SimpleProperties {
/**
* Whether exporting of metrics to this backend is enabled.
*/
private boolean enabled = true;
/**
* Step size (i.e. reporting frequency) to use.
*/
private Duration step = Duration.ofMinutes(1);
/**
* Counting mode.
*/
private CountingMode mode = CountingMode.CUMULATIVE;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Duration getStep() { | return this.step;
}
public void setStep(Duration step) {
this.step = step;
}
public CountingMode getMode() {
return this.mode;
}
public void setMode(CountingMode mode) {
this.mode = mode;
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\simple\SimpleProperties.java | 2 |
请完成以下Java代码 | public BaseElement getElement() {
return element;
}
public void setElement(BaseElement element) {
this.element = element;
}
public int getXmlRowNumber() {
return xmlRowNumber;
}
public void setXmlRowNumber(int xmlRowNumber) {
this.xmlRowNumber = xmlRowNumber;
}
public int getXmlColumnNumber() {
return xmlColumnNumber;
}
public void setXmlColumnNumber(int xmlColumnNumber) {
this.xmlColumnNumber = xmlColumnNumber;
}
public double getRotation() {
return rotation;
}
public void setRotation(double rotation) {
this.rotation = rotation;
}
public boolean equals(GraphicInfo ginfo) {
if (this.getX() != ginfo.getX()) {
return false;
}
if (this.getY() != ginfo.getY()) {
return false;
}
if (this.getHeight() != ginfo.getHeight()) {
return false;
}
if (this.getWidth() != ginfo.getWidth()) { | return false;
}
if (this.getRotation() != ginfo.getRotation()) {
return false;
}
// check for zero value in case we are comparing model value to BPMN DI value
// model values do not have xml location information
if (0 != this.getXmlColumnNumber() && 0 != ginfo.getXmlColumnNumber() && this.getXmlColumnNumber() != ginfo.getXmlColumnNumber()) {
return false;
}
if (0 != this.getXmlRowNumber() && 0 != ginfo.getXmlRowNumber() && this.getXmlRowNumber() != ginfo.getXmlRowNumber()) {
return false;
}
// only check for elements that support this value
if (null != this.getExpanded() && null != ginfo.getExpanded() && !this.getExpanded().equals(ginfo.getExpanded())) {
return false;
}
return true;
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\GraphicInfo.java | 1 |
请完成以下Java代码 | public class DeserializedObject {
SerializableType type;
Object deserializedObject;
byte[] originalBytes;
VariableInstanceEntity variableInstanceEntity;
public DeserializedObject(SerializableType type, Object deserializedObject, byte[] serializedBytes, VariableInstanceEntity variableInstanceEntity) {
this.type = type;
this.deserializedObject = deserializedObject;
this.originalBytes = serializedBytes;
this.variableInstanceEntity = variableInstanceEntity;
}
public void flush() {
// this first check verifies if the variable value was not overwritten with another object | if (deserializedObject == variableInstanceEntity.getCachedValue() && !variableInstanceEntity.isDeleted()) {
byte[] bytes = type.serialize(deserializedObject, variableInstanceEntity);
if (!Arrays.equals(originalBytes, bytes)) {
// Add an additional check to prevent byte differences due to JDK changes etc
Object originalObject = type.deserialize(originalBytes, variableInstanceEntity);
byte[] refreshedOriginalBytes = type.serialize(originalObject, variableInstanceEntity);
if (!Arrays.equals(refreshedOriginalBytes, bytes)) {
variableInstanceEntity.setBytes(bytes);
}
}
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\variable\DeserializedObject.java | 1 |
请完成以下Java代码 | public ImmutableCredentialRecordBuilder credentialId(Bytes credentialId) {
this.credentialId = credentialId;
return this;
}
public ImmutableCredentialRecordBuilder userEntityUserId(Bytes userEntityUserId) {
this.userEntityUserId = userEntityUserId;
return this;
}
public ImmutableCredentialRecordBuilder publicKey(PublicKeyCose publicKey) {
this.publicKey = publicKey;
return this;
}
public ImmutableCredentialRecordBuilder signatureCount(long signatureCount) {
this.signatureCount = signatureCount;
return this;
}
public ImmutableCredentialRecordBuilder uvInitialized(boolean uvInitialized) {
this.uvInitialized = uvInitialized;
return this;
}
public ImmutableCredentialRecordBuilder transports(Set<AuthenticatorTransport> transports) {
this.transports = transports;
return this;
}
public ImmutableCredentialRecordBuilder backupEligible(boolean backupEligible) {
this.backupEligible = backupEligible;
return this;
}
public ImmutableCredentialRecordBuilder backupState(boolean backupState) {
this.backupState = backupState;
return this;
}
public ImmutableCredentialRecordBuilder attestationObject(@Nullable Bytes attestationObject) {
this.attestationObject = attestationObject; | return this;
}
public ImmutableCredentialRecordBuilder attestationClientDataJSON(@Nullable Bytes attestationClientDataJSON) {
this.attestationClientDataJSON = attestationClientDataJSON;
return this;
}
public ImmutableCredentialRecordBuilder created(Instant created) {
this.created = created;
return this;
}
public ImmutableCredentialRecordBuilder lastUsed(Instant lastUsed) {
this.lastUsed = lastUsed;
return this;
}
public ImmutableCredentialRecordBuilder label(String label) {
this.label = label;
return this;
}
public ImmutableCredentialRecord build() {
return new ImmutableCredentialRecord(this.credentialType, this.credentialId, this.userEntityUserId,
this.publicKey, this.signatureCount, this.uvInitialized, this.transports, this.backupEligible,
this.backupState, this.attestationObject, this.attestationClientDataJSON, this.created,
this.lastUsed, this.label);
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\ImmutableCredentialRecord.java | 1 |
请完成以下Java代码 | protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
Object principal = principalCollection.getPrimaryPrincipal();
Set<String> roles = new HashSet<>();
roles.add("user");
if ("admin".equals(principal)) {
roles.add("admin");
}
return new SimpleAuthorizationInfo(roles);
}
// 认证
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
log.info("MyRealm doGetAuthenticationInfo");
UsernamePasswordToken userToken = (UsernamePasswordToken) token;
String username = userToken.getUsername();
if ("unknown".equals(username)) {
throw new UnknownAccountException("用户不存在");
}
if ("monster".equals(username)) {
throw new LockedAccountException("用户被锁定");
} | Object principal = username;
Object credentials = "e10adc3949ba59abbe56e057f20f883e";
String realmName = getName();
log.info("doGetAuthenticationInfo username: {}", username);
/**
* 见 {@link ShiroConfig#myRealm} 的密码指定算法
*/
return new SimpleAuthenticationInfo(principal, credentials, realmName);
}
public static void main(String[] args) {
String hashAlgorithmName = "MD5";
String credentials = "123456";
Object salt = null;
int hashIterations = 100;
SimpleHash simpleHash = new SimpleHash(hashAlgorithmName, credentials, salt, hashIterations);
System.out.println(simpleHash);
}
} | repos\spring-boot-quick-master\quick-shiro\src\main\java\com\shiro\quick\shiro\realm\MyRealm.java | 1 |
请完成以下Java代码 | private static void assertNotChangingRegularAndCustomizationFields(final I_Mobile_Application_Trl mobileApplicationTrl)
{
final Set<String> changedRegularFields = new HashSet<>();
final Set<String> changedCustomizationFields = new HashSet<>();
if (isValueChanged(mobileApplicationTrl, I_Mobile_Application_Trl.COLUMNNAME_IsUseCustomization))
{
changedCustomizationFields.add(I_Mobile_Application_Trl.COLUMNNAME_IsUseCustomization);
}
//
for (final MobileApplicationTranslatedColumn field : MobileApplicationTranslatedColumn.values())
{
if (field.hasCustomizedField() && isValueChanged(mobileApplicationTrl, field.getCustomizationColumnName()))
{
changedCustomizationFields.add(field.getCustomizationColumnName());
}
if (isValueChanged(mobileApplicationTrl, field.getColumnName()))
{
changedRegularFields.add(field.getColumnName());
}
}
//
if (!changedRegularFields.isEmpty() && !changedCustomizationFields.isEmpty())
{
throw new AdempiereException("Changing regular fields and customization fields is not allowed."
+ "\n Regular fields changed: " + changedRegularFields
+ "\n Customization fields changed: " + changedCustomizationFields)
.markAsUserValidationError();
}
} | private static boolean isValueChanged(final I_Mobile_Application_Trl mobileApplicationTrl, final String columnName)
{
return InterfaceWrapperHelper.isValueChanged(mobileApplicationTrl, columnName);
}
private enum MobileApplicationTranslatedColumn
{
Name(I_Mobile_Application_Trl.COLUMNNAME_Name, I_Mobile_Application_Trl.COLUMNNAME_Name_Customized), //
Description(I_Mobile_Application_Trl.COLUMNNAME_Description, I_Mobile_Application_Trl.COLUMNNAME_Description_Customized), //
;
@Getter
private final String columnName;
@Getter
private final String customizationColumnName;
MobileApplicationTranslatedColumn(
@NonNull final String columnName,
@Nullable final String customizationColumnName)
{
this.columnName = columnName;
this.customizationColumnName = customizationColumnName;
}
public boolean hasCustomizedField()
{
return getCustomizationColumnName() != null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\translation\interceptor\Mobile_Application_Trl.java | 1 |
请完成以下Java代码 | public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
/** Set Summary.
@param Summary
Textual summary of this request
*/
public void setSummary (String Summary)
{
set_ValueNoCheck (COLUMNNAME_Summary, Summary);
}
/** Get Summary.
@return Textual summary of this request
*/
public String getSummary ()
{
return (String)get_Value(COLUMNNAME_Summary);
}
/** TaskStatus AD_Reference_ID=366 */
public static final int TASKSTATUS_AD_Reference_ID=366;
/** 0% Not Started = 0 */
public static final String TASKSTATUS_0NotStarted = "0";
/** 100% Complete = D */
public static final String TASKSTATUS_100Complete = "D";
/** 20% Started = 2 */
public static final String TASKSTATUS_20Started = "2";
/** 80% Nearly Done = 8 */
public static final String TASKSTATUS_80NearlyDone = "8"; | /** 40% Busy = 4 */
public static final String TASKSTATUS_40Busy = "4";
/** 60% Good Progress = 6 */
public static final String TASKSTATUS_60GoodProgress = "6";
/** 90% Finishing = 9 */
public static final String TASKSTATUS_90Finishing = "9";
/** 95% Almost Done = A */
public static final String TASKSTATUS_95AlmostDone = "A";
/** 99% Cleaning up = C */
public static final String TASKSTATUS_99CleaningUp = "C";
/** Set Task Status.
@param TaskStatus
Status of the Task
*/
public void setTaskStatus (String TaskStatus)
{
set_Value (COLUMNNAME_TaskStatus, TaskStatus);
}
/** Get Task Status.
@return Status of the Task
*/
public String getTaskStatus ()
{
return (String)get_Value(COLUMNNAME_TaskStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_RequestAction.java | 1 |
请完成以下Java代码 | public Method getMethodFor(Object payload) {
return getHandlerForPayload(payload.getClass()).getMethod();
}
public boolean hasDefaultHandler() {
return this.defaultHandler != null;
}
public @Nullable InvocationResult getInvocationResultFor(Object result, Object inboundPayload) {
InvocableHandlerMethod handler = findHandlerForPayload(inboundPayload.getClass());
if (handler != null) {
return new InvocationResult(result, this.handlerSendTo.get(handler),
handler.getMethod().getGenericReturnType(), handler.getBean(), handler.getMethod());
}
return null;
}
private static final class PayloadValidator extends PayloadMethodArgumentResolver {
PayloadValidator(Validator validator) {
super(new MessageConverter() { // Required but never used
@Override | public @Nullable Message<?> toMessage(Object payload, @Nullable MessageHeaders headers) {
return null;
}
@Override
public @Nullable Object fromMessage(Message<?> message, Class<?> targetClass) {
return null;
}
}, validator);
}
@Override
public void validate(Message<?> message, MethodParameter parameter, Object target) { // NOSONAR - public
super.validate(message, parameter, target);
}
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\adapter\DelegatingInvocableHandler.java | 1 |
请完成以下Java代码 | public void setC_PrintJob_Line_To_ID (int C_PrintJob_Line_To_ID)
{
if (C_PrintJob_Line_To_ID < 1)
set_Value (COLUMNNAME_C_PrintJob_Line_To_ID, null);
else
set_Value (COLUMNNAME_C_PrintJob_Line_To_ID, Integer.valueOf(C_PrintJob_Line_To_ID));
}
@Override
public int getC_PrintJob_Line_To_ID()
{
return get_ValueAsInt(COLUMNNAME_C_PrintJob_Line_To_ID);
}
@Override
public void setErrorMsg (java.lang.String ErrorMsg)
{
set_Value (COLUMNNAME_ErrorMsg, ErrorMsg);
}
@Override
public java.lang.String getErrorMsg()
{
return (java.lang.String)get_Value(COLUMNNAME_ErrorMsg);
}
@Override
public void setHostKey (java.lang.String HostKey)
{
set_Value (COLUMNNAME_HostKey, HostKey);
}
@Override
public java.lang.String getHostKey()
{
return (java.lang.String)get_Value(COLUMNNAME_HostKey);
}
/**
* Status AD_Reference_ID=540384
* Reference name: C_Print_Job_Instructions_Status
*/ | public static final int STATUS_AD_Reference_ID=540384;
/** Pending = P */
public static final String STATUS_Pending = "P";
/** Send = S */
public static final String STATUS_Send = "S";
/** Done = D */
public static final String STATUS_Done = "D";
/** Error = E */
public static final String STATUS_Error = "E";
@Override
public void setStatus (java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return (java.lang.String)get_Value(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Print_Job_Instructions.java | 1 |
请完成以下Java代码 | private void skipWhitespace() throws IOException {
while (isWhiteSpace()) {
this.character = this.reader.read();
this.columnNumber++;
}
}
private void setLastLineCommentPrefixCharacter(int lastLineCommentPrefixCharacter) {
this.lastLineCommentPrefixCharacter = lastLineCommentPrefixCharacter;
}
private void skipComment() throws IOException {
while (this.character != '\n' && this.character != -1) {
this.character = this.reader.read();
}
this.columnNumber = -1;
}
private void readEscaped() throws IOException {
this.character = this.reader.read();
int escapeIndex = ESCAPES[0].indexOf(this.character);
if (escapeIndex != -1) {
this.character = ESCAPES[1].charAt(escapeIndex);
}
else if (this.character == '\n') {
this.columnNumber = -1;
read();
}
else if (this.character == 'u') {
readUnicode();
}
}
private void readUnicode() throws IOException {
this.character = 0;
for (int i = 0; i < 4; i++) {
int digit = this.reader.read();
if (digit >= '0' && digit <= '9') {
this.character = (this.character << 4) + digit - '0';
}
else if (digit >= 'a' && digit <= 'f') {
this.character = (this.character << 4) + digit - 'a' + 10;
}
else if (digit >= 'A' && digit <= 'F') {
this.character = (this.character << 4) + digit - 'A' + 10;
}
else {
throw new IllegalStateException("Malformed \\uxxxx encoding.");
}
}
}
boolean isWhiteSpace() {
return !this.escaped && (this.character == ' ' || this.character == '\t' || this.character == '\f');
}
boolean isEndOfFile() {
return this.character == -1;
}
boolean isEndOfLine() {
return this.character == -1 || (!this.escaped && this.character == '\n');
}
boolean isListDelimiter() {
return !this.escaped && this.character == ','; | }
boolean isPropertyDelimiter() {
return !this.escaped && (this.character == '=' || this.character == ':');
}
char getCharacter() {
return (char) this.character;
}
Location getLocation() {
return new Location(this.reader.getLineNumber(), this.columnNumber);
}
boolean isSameLastLineCommentPrefix() {
return this.lastLineCommentPrefixCharacter == this.character;
}
boolean isCommentPrefixCharacter() {
return this.character == '#' || this.character == '!';
}
boolean isHyphenCharacter() {
return this.character == '-';
}
}
/**
* A single document within the properties file.
*/
static class Document {
private final Map<String, OriginTrackedValue> values = new LinkedHashMap<>();
void put(String key, OriginTrackedValue value) {
if (!key.isEmpty()) {
this.values.put(key, value);
}
}
boolean isEmpty() {
return this.values.isEmpty();
}
Map<String, OriginTrackedValue> asMap() {
return this.values;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\OriginTrackedPropertiesLoader.java | 1 |
请完成以下Java代码 | public void afterDelete(final I_GL_JournalLine glJournalLine)
{
updateJournalTotal(glJournalLine);
} // afterDelete
/**
* Update amounts of {@link I_GL_Journal} and {@link I_GL_JournalBatch}.
*/
private void updateJournalTotal(final I_GL_JournalLine glJournalLine)
{
final int glJournalId = glJournalLine.getGL_Journal_ID();
//
// Update Journal Total
{
final String sql = DB.convertSqlToNative("UPDATE GL_Journal j"
+ " SET (TotalDr, TotalCr) = (SELECT COALESCE(SUM(AmtAcctDr),0), COALESCE(SUM(AmtAcctCr),0)" // croo Bug# 1789935
+ " FROM GL_JournalLine jl WHERE jl.IsActive='Y' AND j.GL_Journal_ID=jl.GL_Journal_ID) "
+ "WHERE GL_Journal_ID=" + glJournalId);
final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited);
if (no != 1)
{
throw new AdempiereException("afterSave - Update Journal #" + no);
}
}
//
// Update Batch Total, if there is any batch | {
final String sql = DB.convertSqlToNative("UPDATE GL_JournalBatch jb"
+ " SET (TotalDr, TotalCr) = (SELECT COALESCE(SUM(TotalDr),0), COALESCE(SUM(TotalCr),0)"
+ " FROM GL_Journal j WHERE jb.GL_JournalBatch_ID=j.GL_JournalBatch_ID) "
+ "WHERE GL_JournalBatch_ID="
+ "(SELECT DISTINCT GL_JournalBatch_ID FROM GL_Journal WHERE GL_Journal_ID=" + glJournalId + ")");
final int no = DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited);
if (no != 0 && no != 1)
{
throw new AdempiereException("Update Batch #" + no);
}
}
CacheMgt.get().resetLocalNowAndBroadcastOnTrxCommit(
ITrx.TRXNAME_ThreadInherited,
CacheInvalidateMultiRequest.rootRecord(I_GL_Journal.Table_Name, glJournalId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\GL_JournalLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getBankReturnMsg() {
return bankReturnMsg;
}
public void setBankReturnMsg(String bankReturnMsg) {
this.bankReturnMsg = bankReturnMsg;
}
public TradeStatusEnum getTradeStatus() {
return tradeStatus;
}
public void setTradeStatus(TradeStatusEnum tradeStatus) {
this.tradeStatus = tradeStatus;
} | public boolean isAuth() {
return isAuth;
}
public void setAuth(boolean auth) {
isAuth = auth;
}
public String getSign() {
return sign;
}
public void setSign(String sign) {
this.sign = sign;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthProgramInitResultVo.java | 2 |
请完成以下Spring Boot application配置 | logging.level.org.springframework=INFO
################### DataSource Configuration ##########################
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=root
spring.datasource.password=admin
spring.datasource.initialize=t | rue
################### Hibernate Configuration ##########################
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true | repos\Spring-Boot-Advanced-Projects-main\springboot2-webapp-thymeleaf\src\main\resources\application-prod.properties | 2 |
请完成以下Java代码 | public void setStartActivityId(String startUserId) {
this.startActivityId = startUserId;
}
@Override
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public void setSuperProcessInstanceId(String superProcessInstanceId) {
this.superProcessInstanceId = superProcessInstanceId;
}
@Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getName() {
if (localizedName != null && localizedName.length() > 0) {
return localizedName;
} else {
return name;
}
}
public void setName(String name) {
this.name = name;
}
public String getLocalizedName() {
return localizedName;
}
@Override
public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
@Override
public String getDescription() {
if (localizedDescription != null && localizedDescription.length() > 0) {
return localizedDescription;
} else {
return description;
} | }
public void setDescription(String description) {
this.description = description;
}
public String getLocalizedDescription() {
return localizedDescription;
}
@Override
public void setLocalizedDescription(String localizedDescription) {
this.localizedDescription = localizedDescription;
}
@Override
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "HistoricProcessInstanceEntity[superProcessInstanceId=" + superProcessInstanceId + "]";
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricProcessInstanceEntity.java | 1 |
请完成以下Java代码 | public BigDecimal getPercent()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percent);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPriorityNo (final int PriorityNo)
{
set_Value (COLUMNNAME_PriorityNo, PriorityNo);
}
@Override
public int getPriorityNo()
{
return get_ValueAsInt(COLUMNNAME_PriorityNo);
}
@Override
public void setTransfertTime (final @Nullable BigDecimal TransfertTime)
{
set_Value (COLUMNNAME_TransfertTime, TransfertTime);
}
@Override
public BigDecimal getTransfertTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TransfertTime);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
} | @Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_DD_NetworkDistributionLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id", unique = true, nullable = false)
private Long id;
@Column
private String address;
@Column
private String country;
@OneToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "user_id")
private User user;
public Address() {
}
public Address(String address, String country, User user) {
this.id = id;
this.address = address;
this.country = country;
this.user = user;
}
public Long getId() {
return id;
} | public void setId(Long id) {
this.id = id;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
} | repos\tutorials-master\persistence-modules\spring-data-rest-querydsl\src\main\java\com\baeldung\entity\Address.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void log(TransportProtos.DeviceDisconnectProto msg) {
totalCounter.increment();
deviceDisconnectsCounter.increment();
}
public void log(TransportProtos.DeviceInactivityProto msg) {
totalCounter.increment();
deviceInactivitiesCounter.increment();
}
public void log(TransportProtos.DeviceInactivityTimeoutUpdateProto msg) {
totalCounter.increment();
deviceInactivityTimeoutUpdatesCounter.increment();
}
public void log(TransportProtos.SubscriptionMgrMsgProto msg) {
totalCounter.increment();
subscriptionMsgCounter.increment();
}
public void log(TransportProtos.ToCoreNotificationMsg msg) {
totalCounter.increment();
if (msg.hasToLocalSubscriptionServiceMsg()) {
toCoreNfSubscriptionServiceCounter.increment();
} else if (msg.hasFromDeviceRpcResponse()) {
toCoreNfDeviceRpcResponseCounter.increment();
} else if (msg.hasComponentLifecycle()) {
toCoreNfComponentLifecycleCounter.increment();
} else if (msg.getQueueUpdateMsgsCount() > 0) {
toCoreNfQueueUpdateCounter.increment();
} else if (msg.getQueueDeleteMsgsCount() > 0) { | toCoreNfQueueDeleteCounter.increment();
} else if (msg.hasVcResponseMsg()) {
toCoreNfVersionControlResponseCounter.increment();
} else if (msg.hasToSubscriptionMgrMsg()) {
toCoreNfSubscriptionManagerCounter.increment();
} else if (msg.hasNotificationRuleProcessorMsg()) {
toCoreNfNotificationRuleProcessorCounter.increment();
} else {
toCoreNfOtherCounter.increment();
}
}
public void printStats() {
int total = totalCounter.get();
if (total > 0) {
StringBuilder stats = new StringBuilder();
counters.forEach(counter ->
stats.append(counter.getName()).append(" = [").append(counter.get()).append("] "));
log.info("Core Stats: {}", stats);
}
}
public void reset() {
counters.forEach(StatsCounter::clear);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\queue\TbCoreConsumerStats.java | 2 |
请完成以下Java代码 | public void add(final RModelCalculationContext calculationCtx, final List<Object> row, final Object columnValue)
{
final IRModelMetadata metadata = calculationCtx.getMetadata();
final BigDecimal qtyToAdd = toBigDecimalOrZero(columnValue);
final int rowProductId = getM_Product_ID(metadata, row);
if (rowProductId <= 0)
{
return;
}
final int rowUomId = getC_UOM_ID(metadata, row);
if (rowUomId <= 0)
{
return;
}
add(rowProductId, rowUomId, qtyToAdd);
}
private void add(final int rowProductId, final int rowUomId, final BigDecimal rowQty)
{
// If this aggregation is no longer valid => do nothing
if (!valid)
{
return;
}
final boolean isInitialized = product != null;
if (!isInitialized)
{
uomConversionCtx = UOMConversionContext.of(rowProductId);
uom = productBL.getStockUOM(rowProductId);
qty = BigDecimal.ZERO;
}
//
// Check if it's compatible
else if (product.getM_Product_ID() != rowProductId)
{
valid = false;
return;
}
final I_C_UOM rowUOM = InterfaceWrapperHelper.create(getCtx(), rowUomId, I_C_UOM.class, ITrx.TRXNAME_None);
final BigDecimal rowQtyInBaseUOM;
try
{
rowQtyInBaseUOM = uomConversionBL.convertQty(uomConversionCtx, rowQty, rowUOM, uom);
}
catch (final Exception e)
{
log.warn(e.getLocalizedMessage());
valid = false;
return;
}
qty = qty.add(rowQtyInBaseUOM);
}
@Override
public Object getAggregatedValue(final RModelCalculationContext calculationCtx, final List<Object> groupRow)
{
if (!valid)
{
return null;
}
if (!isGroupBy(calculationCtx, COLUMNNAME_M_Product_ID))
{
return null;
}
final IRModelMetadata metadata = calculationCtx.getMetadata();
final int groupProductId = getM_Product_ID(metadata, groupRow);
if (groupProductId <= 0) | {
return null;
}
else if (product == null)
{
return BigDecimal.ZERO;
}
else if (product.getM_Product_ID() != groupProductId)
{
// shall not happen
return null;
}
//
// Update UOM column
// FIXME: dirty hack
{
final KeyNamePair uomKNP = new KeyNamePair(uom.getC_UOM_ID(), uom.getName());
setRowValueOrNull(metadata, groupRow, COLUMNNAME_C_UOM_ID, uomKNP);
}
return qty;
}
private final int getM_Product_ID(final IRModelMetadata metadata, final List<Object> row)
{
final KeyNamePair productKNP = getRowValueOrNull(metadata, row, COLUMNNAME_M_Product_ID, KeyNamePair.class);
if (productKNP == null)
{
return -1;
}
return productKNP.getKey();
}
private final int getC_UOM_ID(final IRModelMetadata metadata, final List<Object> row)
{
final KeyNamePair uomKNP = getRowValueOrNull(metadata, row, COLUMNNAME_C_UOM_ID, KeyNamePair.class);
if (uomKNP == null)
{
return -1;
}
return uomKNP.getKey();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\compiere\report\core\ProductQtyRModelAggregatedValue.java | 1 |
请完成以下Java代码 | public java.lang.String getExternalSystemMessage()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemMessage);
}
/**
* ExternalSystemStatus AD_Reference_ID=541502
* Reference name: ExpectedStatus
*/
public static final int EXTERNALSYSTEMSTATUS_AD_Reference_ID=541502;
/** Active = Active */
public static final String EXTERNALSYSTEMSTATUS_Active = "Active";
/** Inactive = Inactive */
public static final String EXTERNALSYSTEMSTATUS_Inactive = "Inactive";
/** Error = Error */ | public static final String EXTERNALSYSTEMSTATUS_Error = "Error ";
/** Down = Down */
public static final String EXTERNALSYSTEMSTATUS_Down = "Down";
@Override
public void setExternalSystemStatus (final java.lang.String ExternalSystemStatus)
{
set_Value (COLUMNNAME_ExternalSystemStatus, ExternalSystemStatus);
}
@Override
public java.lang.String getExternalSystemStatus()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Status.java | 1 |
请完成以下Java代码 | public void updateTarget(String targetName, String targetVersion, Optional<String> newTargetUrl, Optional<String> newTargetTag) {
this.targetName = targetName;
this.targetVersion = targetVersion;
this.targetUrl = newTargetUrl.orElse(null);
this.targetTag = newTargetTag.orElse(null);
}
@JsonIgnore
public boolean isUpdateRequired() {
if (StringUtils.isEmpty(targetName) || StringUtils.isEmpty(targetVersion) || !isSupported()) {
return false;
} else {
String targetPackageId = getPackageId(targetName, targetVersion);
String currentPackageId = getPackageId(currentName, currentVersion);
if (StringUtils.isNotEmpty(failedPackageId) && failedPackageId.equals(targetPackageId)) {
return false;
} else {
if (targetPackageId.equals(currentPackageId)) {
return false;
} else if (StringUtils.isNotEmpty(targetTag) && targetTag.equals(currentPackageId)) {
return false;
} else if (StringUtils.isNotEmpty(currentVersion3)) {
if (StringUtils.isNotEmpty(targetTag) && (currentVersion3.contains(targetTag) || targetTag.contains(currentVersion3))) {
return false;
}
return !currentVersion3.contains(targetPackageId);
} else {
return true;
}
}
}
}
@JsonIgnore
public boolean isSupported() {
return StringUtils.isNotEmpty(currentName) || StringUtils.isNotEmpty(currentVersion) || StringUtils.isNotEmpty(currentVersion3);
}
@JsonIgnore | public boolean isAssigned() {
return StringUtils.isNotEmpty(targetName) && StringUtils.isNotEmpty(targetVersion);
}
public abstract void update(Result result);
protected static String getPackageId(String name, String version) {
return (StringUtils.isNotEmpty(name) ? name : "") + (StringUtils.isNotEmpty(version) ? version : "");
}
public abstract OtaPackageType getType();
@JsonIgnore
public String getTargetPackageId() {
return getPackageId(targetName, targetVersion);
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\ota\LwM2MClientOtaInfo.java | 1 |
请完成以下Java代码 | public void destroy(VariableScope innerScopeInstance, VariableScope outerScopeInstance) {
if (destinationVariableName!=null) {
if (innerScopeInstance.hasVariable(sourceVariableName)) {
Object value = innerScopeInstance.getVariable(sourceVariableName);
outerScopeInstance.setVariable(destinationVariableName, value);
} else {
throw new ProcessEngineException("Couldn't destroy variable " + sourceVariableName + ", since it does not exist");
}
}
if (destinationExpression!=null) {
Object value = destinationExpression.getValue(innerScopeInstance);
outerScopeInstance.setVariable(destinationVariableName, value);
}
if (link!=null) {
if (innerScopeInstance.hasVariable(sourceVariableName)) {
Object value = innerScopeInstance.getVariable(sourceVariableName);
outerScopeInstance.setVariable(destinationVariableName, value);
} else {
throw new ProcessEngineException("Couldn't destroy variable " + sourceVariableName + ", since it does not exist");
}
}
if (linkExpression!=null) {
Object value = sourceExpression.getValue(innerScopeInstance);
outerScopeInstance.setVariable(destinationVariableName, value);
}
}
public VariableDeclaration(String name, String type) {
this.name = name;
this.type = type;
}
@Override
public String toString() {
return "VariableDeclaration[" + name + ":" + type + "]";
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type; | }
public String getSourceVariableName() {
return sourceVariableName;
}
public void setSourceVariableName(String sourceVariableName) {
this.sourceVariableName = sourceVariableName;
}
public Expression getSourceExpression() {
return sourceExpression;
}
public void setSourceExpression(Expression sourceExpression) {
this.sourceExpression = sourceExpression;
}
public String getDestinationVariableName() {
return destinationVariableName;
}
public void setDestinationVariableName(String destinationVariableName) {
this.destinationVariableName = destinationVariableName;
}
public Expression getDestinationExpression() {
return destinationExpression;
}
public void setDestinationExpression(Expression destinationExpression) {
this.destinationExpression = destinationExpression;
}
public String getLink() {
return link;
}
public void setLink(String link) {
this.link = link;
}
public Expression getLinkExpression() {
return linkExpression;
}
public void setLinkExpression(Expression linkExpression) {
this.linkExpression = linkExpression;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\VariableDeclaration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GenerateInvoiceCandidateForModelFilter_CallOrder implements IGenerateInvoiceCandidateForModelFilter
{
@NonNull
private final CallOrderContractService callOrderContractService;
public GenerateInvoiceCandidateForModelFilter_CallOrder(@NonNull final CallOrderContractService callOrderContractService)
{
this.callOrderContractService = callOrderContractService;
}
@Override
public boolean isEligible(final Object model)
{
if (!applies(model))
{
throw new AdempiereException("GenerateInvoiceEligibilityFilter_CallOrder called for an unsupported model type!")
.appendParametersToMessage() | .setParameter("model", model);
}
//dev-note: see de.metas.contracts.callorder.invoice.GenerateInvoiceCandidateForModelFilter_CallOrder.applies()
final I_C_OrderLine orderLine = (I_C_OrderLine)model;
final boolean isCallOrderContractLine = callOrderContractService.isCallOrderContractLine(orderLine);
return !isCallOrderContractLine;
}
@Override
public boolean applies(@NonNull final Object model)
{
return model instanceof I_C_OrderLine;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\callorder\invoice\GenerateInvoiceCandidateForModelFilter_CallOrder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected WidgetsBundle prepare(EntitiesImportCtx ctx, WidgetsBundle widgetsBundle, WidgetsBundle old, WidgetsBundleExportData exportData, IdProvider idProvider) {
return widgetsBundle;
}
@Override
protected WidgetsBundle saveOrUpdate(EntitiesImportCtx ctx, WidgetsBundle widgetsBundle, WidgetsBundleExportData exportData, IdProvider idProvider, CompareResult compareResult) {
if (CollectionsUtil.isNotEmpty(exportData.getWidgets())) {
exportData.getWidgets().forEach(widgetTypeNode -> {
String bundleAlias = widgetTypeNode.remove("bundleAlias").asText();
String alias = widgetTypeNode.remove("alias").asText();
String fqn = String.format("%s.%s", bundleAlias, alias);
exportData.addFqn(fqn);
WidgetTypeDetails widgetType = JacksonUtil.treeToValue(widgetTypeNode, WidgetTypeDetails.class);
widgetType.setTenantId(ctx.getTenantId());
widgetType.setFqn(fqn);
var existingWidgetType = widgetTypeService.findWidgetTypeByTenantIdAndFqn(ctx.getTenantId(), fqn);
if (existingWidgetType == null) {
widgetType.setId(null);
} else {
widgetType.setId(existingWidgetType.getId());
widgetType.setCreatedTime(existingWidgetType.getCreatedTime());
}
widgetTypeService.saveWidgetType(widgetType);
});
}
WidgetsBundle savedWidgetsBundle = widgetsBundleService.saveWidgetsBundle(widgetsBundle);
widgetTypeService.updateWidgetsBundleWidgetFqns(ctx.getTenantId(), savedWidgetsBundle.getId(), exportData.getFqns()); | return savedWidgetsBundle;
}
@Override
protected CompareResult compare(EntitiesImportCtx ctx, WidgetsBundleExportData exportData, WidgetsBundle prepared, WidgetsBundle existing) {
return new CompareResult(true);
}
@Override
protected WidgetsBundle deepCopy(WidgetsBundle widgetsBundle) {
return new WidgetsBundle(widgetsBundle);
}
@Override
public EntityType getEntityType() {
return EntityType.WIDGETS_BUNDLE;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\WidgetsBundleImportService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private boolean determineSslEnabled(boolean sslEnabled) {
return (this.secureConnection != null) ? this.secureConnection : sslEnabled;
}
}
public static final class Stream {
/**
* Host of a RabbitMQ instance with the Stream plugin enabled.
*/
private String host = "localhost";
/**
* Stream port of a RabbitMQ instance with the Stream plugin enabled.
*/
private int port = DEFAULT_STREAM_PORT;
/**
* Virtual host of a RabbitMQ instance with the Stream plugin enabled. When not
* set, spring.rabbitmq.virtual-host is used.
*/
private @Nullable String virtualHost;
/**
* Login user to authenticate to the broker. When not set,
* spring.rabbitmq.username is used.
*/
private @Nullable String username;
/**
* Login password to authenticate to the broker. When not set
* spring.rabbitmq.password is used.
*/
private @Nullable String password;
/**
* Name of the stream.
*/
private @Nullable String name;
public String getHost() {
return this.host;
}
public void setHost(String host) {
this.host = host;
}
public int getPort() {
return this.port;
}
public void setPort(int port) { | this.port = port;
}
public @Nullable String getVirtualHost() {
return this.virtualHost;
}
public void setVirtualHost(@Nullable String virtualHost) {
this.virtualHost = virtualHost;
}
public @Nullable String getUsername() {
return this.username;
}
public void setUsername(@Nullable String username) {
this.username = username;
}
public @Nullable String getPassword() {
return this.password;
}
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getName() {
return this.name;
}
public void setName(@Nullable String name) {
this.name = name;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\RabbitProperties.java | 2 |
请完成以下Java代码 | public String getDeploymentId() {
return deploymentId;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public Object getPersistentState() {
return DmnResourceEntityImpl.class;
}
@Override
public boolean isGenerated() { | return false;
}
@Override
public void setGenerated(boolean generated) {
this.generated = generated;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "ResourceEntity[id=" + id + ", name=" + name + "]";
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\persistence\entity\DmnResourceEntityImpl.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* Attributes5 AD_Reference_ID=541336
* Reference name: Attributes5
*/
public static final int ATTRIBUTES5_AD_Reference_ID=541336;
/** Vereinszugehörigkeit = Vereinszugehörigkeit */
public static final String ATTRIBUTES5_Vereinszugehoerigkeit = "Vereinszugehörigkeit";
/** Politisches Engagement = Politisches Engagement */
public static final String ATTRIBUTES5_PolitischesEngagement = "Politisches Engagement";
/** Rechtsauskunft = Rechtsauskunft */
public static final String ATTRIBUTES5_Rechtsauskunft = "Rechtsauskunft";
/** Beratungen = Beratungen */
public static final String ATTRIBUTES5_Beratungen = "Beratungen";
/** Zeitung = Zeitung */
public static final String ATTRIBUTES5_Zeitung = "Zeitung";
/** Vergünstigungen = Vergünstigungen */
public static final String ATTRIBUTES5_Verguenstigungen = "Vergünstigungen";
/** Dienstleistungen = Dienstleistungen */
public static final String ATTRIBUTES5_Dienstleistungen = "Dienstleistungen";
/** Andere = Andere */
public static final String ATTRIBUTES5_Andere = "Andere";
/** Netzwerk = Netzwerk */
public static final String ATTRIBUTES5_Netzwerk = "Netzwerk";
/** Seminare & Veranstaltungen = Seminare & Veranstaltungen */
public static final String ATTRIBUTES5_SeminareVeranstaltungen = "Seminare & Veranstaltungen";
@Override
public void setAttributes5 (final java.lang.String Attributes5)
{
set_Value (COLUMNNAME_Attributes5, Attributes5);
}
@Override
public java.lang.String getAttributes5()
{
return get_ValueAsString(COLUMNNAME_Attributes5);
} | @Override
public void setC_BPartner_Attribute5_ID (final int C_BPartner_Attribute5_ID)
{
if (C_BPartner_Attribute5_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_Attribute5_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Attribute5_ID, C_BPartner_Attribute5_ID);
}
@Override
public int getC_BPartner_Attribute5_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Attribute5_ID);
}
@Override
public void setC_BPartner_ID (final int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID);
}
@Override
public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Attribute5.java | 1 |
请完成以下Java代码 | public void setGL_FundRestriction_ID (int GL_FundRestriction_ID)
{
if (GL_FundRestriction_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_FundRestriction_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_FundRestriction_ID, Integer.valueOf(GL_FundRestriction_ID));
}
/** Get Fund Restriction.
@return Restriction of Funds
*/
public int getGL_FundRestriction_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_FundRestriction_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name); | }
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_FundRestriction.java | 1 |
请完成以下Java代码 | public void setMenge(Integer value) {
this.menge = value;
}
/**
* Gets the value of the typ property.
*
* @return
* possible object is
* {@link VerfuegbarkeitRueckmeldungTyp }
*
*/
public VerfuegbarkeitRueckmeldungTyp getTyp() {
return typ;
}
/**
* Sets the value of the typ property.
*
* @param value
* allowed object is
* {@link VerfuegbarkeitRueckmeldungTyp }
*
*/
public void setTyp(VerfuegbarkeitRueckmeldungTyp value) {
this.typ = value;
}
/**
* Gets the value of the lieferzeitpunkt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getLieferzeitpunkt() {
return lieferzeitpunkt;
}
/**
* Sets the value of the lieferzeitpunkt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setLieferzeitpunkt(XMLGregorianCalendar value) {
this.lieferzeitpunkt = value;
}
/**
* Gets the value of the tour property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTour() {
return tour;
}
/**
* Sets the value of the tour property.
*
* @param value
* allowed object is | * {@link String }
*
*/
public void setTour(String value) {
this.tour = value;
}
/**
* Gets the value of the grund property.
*
* @return
* possible object is
* {@link VerfuegbarkeitDefektgrund }
*
*/
public VerfuegbarkeitDefektgrund getGrund() {
return grund;
}
/**
* Sets the value of the grund property.
*
* @param value
* allowed object is
* {@link VerfuegbarkeitDefektgrund }
*
*/
public void setGrund(VerfuegbarkeitDefektgrund value) {
this.grund = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VerfuegbarkeitAnteil.java | 1 |
请完成以下Java代码 | public IWorkPackageBuilder setAD_PInstance_ID(final PInstanceId adPInstanceId)
{
this.adPInstanceId = adPInstanceId;
return this;
}
@NonNull
private I_C_Queue_WorkPackage enqueue(@NonNull final I_C_Queue_WorkPackage workPackage, @Nullable final ILockCommand elementsLocker)
{
final IWorkPackageQueue workPackageQueue = getWorkpackageQueue();
final IWorkpackagePrioStrategy workPackagePriority = getPriority();
final String originalWorkPackageTrxName = getTrxName(workPackage);
try (final IAutoCloseable ignored = () -> setTrxName(workPackage, originalWorkPackageTrxName))
{
// Fact: the workpackage trxName is used when creating the workpackage and its elements.
// Therefore, we temporarily set it to be our _trxName.
// Otherwise, if the current trx fails, the workpackage will have been created, but not have been flagged as "ReadyForProcessing" (which sucks).
setTrxName(workPackage, _trxName);
// Set the Async batch if provided
if (asyncBatchSet)
{
workPackage.setC_Async_Batch_ID(AsyncBatchId.toRepoId(asyncBatchId));
}
if (userInChargeId != null)
{
workPackage.setAD_User_InCharge_ID(userInChargeId.getRepoId());
}
@SuppressWarnings("deprecation") // Suppressing the warning, because *this class* is the workpackage builder to be used
final I_C_Queue_WorkPackage enqueuedWorkpackage = workPackageQueue.enqueueWorkPackage(
workPackage, | workPackagePriority);
try (final MDCCloseable ignored1 = TableRecordMDC.putTableRecordReference(enqueuedWorkpackage))
{
// Create workpackage parameters
if (_parametersBuilder != null)
{
_parametersBuilder.setC_Queue_WorkPackage(enqueuedWorkpackage);
_parametersBuilder.build();
}
createWorkpackageElements(workPackageQueue, enqueuedWorkpackage);
//
// Lock enqueued workpackage elements
if (elementsLocker != null)
{
final ILock lock = elementsLocker.acquire();
lock.unlockAllAfterTrxRollback();
}
//
// Actually mark the workpackage as ready for processing
// NOTE: method also accepts null transaction and in that case it will immediately mark as ready for processing
workPackageQueue.markReadyForProcessingAfterTrxCommit(enqueuedWorkpackage, _trxName);
}
return enqueuedWorkpackage;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\WorkPackageBuilder.java | 1 |
请完成以下Java代码 | private Quantity computeQtyToIssue(final PPOrderLineRow row)
{
final List<I_M_Source_HU> activeSourceHus = WEBUI_PP_Order_ProcessHelper.retrieveActiveSourceHus(row);
if (activeSourceHus.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
final Quantity qtyLeftToIssue = row.getQtyPlan().subtract(row.getQty());
final BOMComponentIssueMethod issueMethod = row.getIssueMethod();
if (BOMComponentIssueMethod.IssueOnlyForReceived.equals(issueMethod))
{
if (qtyLeftToIssue.signum() <= 0)
{
return qtyLeftToIssue.toZero();
} | if (row.isProcessed())
{
final I_PP_Order_BOMLine bomLine = ppOrderBOMDAO.getOrderBOMLineById(row.getOrderBOMLineId());
final DraftPPOrderQuantities draftQtys = huPPOrderQtyBL.getDraftPPOrderQuantities(row.getOrderId());
final Quantity quantityToIssueForWhatWasReceived = ppOrderBomBL.computeQtyToIssueBasedOnFinishedGoodReceipt(bomLine, row.getUom(), draftQtys);
return qtyLeftToIssue.min(quantityToIssueForWhatWasReceived);
}
else
{
return qtyLeftToIssue;
}
}
else
{
return qtyLeftToIssue;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_M_Source_HU_IssueCUQty.java | 1 |
请完成以下Java代码 | protected void completing(CmmnActivityExecution execution) {
TaskEntity task = getTask(execution);
if (task != null) {
task.caseExecutionCompleted();
}
}
protected void manualCompleting(CmmnActivityExecution execution) {
completing(execution);
}
protected void suspending(CmmnActivityExecution execution) {
String id = execution.getId();
Context
.getCommandContext()
.getTaskManager()
.updateTaskSuspensionStateByCaseExecutionId(id, SuspensionState.SUSPENDED);
}
protected void resuming(CmmnActivityExecution execution) {
String id = execution.getId();
Context
.getCommandContext()
.getTaskManager()
.updateTaskSuspensionStateByCaseExecutionId(id, SuspensionState.ACTIVE);
}
protected TaskEntity getTask(CmmnActivityExecution execution) {
return Context
.getCommandContext() | .getTaskManager()
.findTaskByCaseExecutionId(execution.getId());
}
protected String getTypeName() {
return "human task";
}
// getters/setters /////////////////////////////////////////////////
public TaskDecorator getTaskDecorator() {
return taskDecorator;
}
public void setTaskDecorator(TaskDecorator taskDecorator) {
this.taskDecorator = taskDecorator;
}
public TaskDefinition getTaskDefinition() {
return taskDecorator.getTaskDefinition();
}
public ExpressionManager getExpressionManager() {
return taskDecorator.getExpressionManager();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\HumanTaskActivityBehavior.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.