instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public class CustomerController {
private static final String HTML = "<H1>%s</H1>";
@Autowired
private CustomerRepository customerRepository;
@GetMapping("/customers")
public Iterable<Customer> findAll() {
return this.customerRepository.findAll();
}
@PostMapping("/customers")
public Customer save(Customer customer) {
return this.customerRepository.save(customer);
}
@GetMapping("/customers/{name}") | public Customer findByName(@PathVariable("name") String name) {
return this.customerRepository.findByNameLike(name);
}
@GetMapping("/")
public String home() {
return format("Customer Relationship Management");
}
@GetMapping("/ping")
public String ping() {
return format("PONG");
}
private String format(String value) {
return String.format(HTML, value);
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\intro\getting-started\src\main\java\example\app\crm\controller\CustomerController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<ParcelInformationType> getParcelInformation() {
if (parcelInformation == null) {
parcelInformation = new ArrayList<ParcelInformationType>();
}
return this.parcelInformation;
}
/**
* Gets the value of the faults property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the faults property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getFaults().add(newItem);
* </pre> | *
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link FaultCodeType }
*
*
*/
public List<FaultCodeType> getFaults() {
if (faults == null) {
faults = new ArrayList<FaultCodeType>();
}
return this.faults;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ShipmentResponse.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AuthConfig {
@Value(value = "${com.auth0.domain}")
private String domain;
@Value(value = "${com.auth0.clientId}")
private String clientId;
@Value(value = "${com.auth0.clientSecret}")
private String clientSecret;
@Value(value = "${com.auth0.managementApi.clientId}")
private String managementApiClientId;
@Value(value = "${com.auth0.managementApi.clientSecret}")
private String managementApiClientSecret;
@Value(value = "${com.auth0.managementApi.grantType}")
private String grantType;
@Bean
public LogoutSuccessHandler logoutSuccessHandler() {
return new LogoutController();
}
@Bean
public AuthenticationController authenticationController() throws UnsupportedEncodingException {
JwkProvider jwkProvider = new JwkProviderBuilder(domain).build();
return AuthenticationController.newBuilder(domain, clientId, clientSecret)
.withJwkProvider(jwkProvider)
.build();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf()
.disable()
.authorizeRequests()
.antMatchers("/callback", "/login", "/")
.permitAll()
.anyRequest()
.authenticated()
.and()
.formLogin()
.loginPage("/login")
.and()
.logout()
.logoutSuccessHandler(logoutSuccessHandler())
.permitAll();
return http.build();
}
public String getDomain() {
return domain;
}
public String getClientId() {
return clientId;
}
public String getClientSecret() {
return clientSecret;
} | public String getManagementApiClientId() {
return managementApiClientId;
}
public String getManagementApiClientSecret() {
return managementApiClientSecret;
}
public String getGrantType() {
return grantType;
}
public String getUserInfoUrl() {
return "https://" + getDomain() + "/userinfo";
}
public String getUsersUrl() {
return "https://" + getDomain() + "/api/v2/users";
}
public String getUsersByEmailUrl() {
return "https://" + getDomain() + "/api/v2/users-by-email?email=";
}
public String getLogoutUrl() {
return "https://" + getDomain() +"/v2/logout";
}
public String getContextPath(HttpServletRequest request) {
String path = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort();
return path;
}
} | repos\tutorials-master\spring-security-modules\spring-security-auth0\src\main\java\com\baeldung\auth0\AuthConfig.java | 2 |
请完成以下Java代码 | public static BPartnerContactId of(@NonNull final BPartnerId bpartnerId, @NonNull final UserId userId)
{
return new BPartnerContactId(bpartnerId, userId);
}
public static BPartnerContactId ofRepoId(final int bpartnerRepoId, final int contactRepoId)
{
final BPartnerId bpartnerId = BPartnerId.ofRepoId(bpartnerRepoId);
final UserId userId = toValidContactUserIdOrNull(contactRepoId);
if (userId == null)
{
throw new AdempiereException("@Invalid@ @Contact_ID@")
.appendParametersToMessage()
.setParameter("bpartnerId", bpartnerId)
.setParameter("contactRepoId", contactRepoId);
}
return of(bpartnerId, userId);
}
@Nullable
public static BPartnerContactId ofRepoIdOrNull(
@Nullable final BPartnerId bpartnerId,
@Nullable final Integer contactRepoId)
{
if(bpartnerId == null)
{
return null;
}
final UserId userId = toValidContactUserIdOrNull(contactRepoId);
return userId != null ? of(bpartnerId, userId) : null;
}
@Nullable
public static BPartnerContactId ofRepoIdOrNull(
@Nullable final Integer bpartnerRepoId,
@Nullable final Integer contactRepoId)
{
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(bpartnerRepoId);
if (bpartnerId == null)
{
return null;
}
final UserId userId = toValidContactUserIdOrNull(contactRepoId);
if (userId == null)
{
return null;
}
return of(bpartnerId, userId);
}
@Nullable
private static UserId toValidContactUserIdOrNull(@Nullable final Integer userRepoId)
{
final UserId userId = userRepoId != null ? UserId.ofRepoIdOrNull(userRepoId) : null;
// NOTE: system user is not a valid BP contact
return userId != null && userId.isRegularUser() ? userId : null;
}
private BPartnerContactId(@NonNull final BPartnerId bpartnerId, @NonNull final UserId userId)
{
this.bpartnerId = bpartnerId;
this.userId = userId;
}
@Override
public int getRepoId()
{
return userId.getRepoId();
}
public static int toRepoId(@Nullable final BPartnerContactId id)
{
return id != null ? id.getRepoId() : -1; | }
@Nullable
public static UserId toUserIdOrNull(@Nullable final BPartnerContactId id)
{
return id != null ? id.getUserId() : null;
}
public static boolean equals(@Nullable final BPartnerContactId id1, @Nullable final BPartnerContactId id2)
{
return Objects.equals(id1, id2);
}
@JsonCreator
public static BPartnerContactId ofJsonString(@NonNull final String idStr)
{
try
{
final List<String> parts = Splitter.on("-").splitToList(idStr);
return of(
BPartnerId.ofRepoId(Integer.parseInt(parts.get(0))),
UserId.ofRepoId(Integer.parseInt(parts.get(1))));
}
catch (Exception ex)
{
throw new AdempiereException("Invalid BPartnerContactId string: " + idStr, ex);
}
}
@JsonValue
public String toJson()
{
return bpartnerId.getRepoId() + "-" + userId.getRepoId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerContactId.java | 1 |
请完成以下Java代码 | public <T extends Spin<?>> T createSpinFromSpin(T parameter, DataFormat<T> format) {
ensureNotNull("parameter", parameter);
return parameter;
}
public <T extends Spin<?>> T createSpinFromString(String parameter, DataFormat<T> format) {
ensureNotNull("parameter", parameter);
Reader input = SpinIoUtil.stringAsReader(parameter);
return createSpin(input, format);
}
public <T extends Spin<?>> T createSpinFromReader(Reader parameter, DataFormat<T> format) {
ensureNotNull("parameter", parameter); | DataFormatReader reader = format.getReader();
Object dataFormatInput = reader.readInput(parameter);
return format.createWrapperInstance(dataFormatInput);
}
public <T extends Spin<?>> T createSpinFromObject(Object parameter, DataFormat<T> format) {
ensureNotNull("parameter", parameter);
DataFormatMapper mapper = format.getMapper();
Object dataFormatInput = mapper.mapJavaToInternal(parameter);
return format.createWrapperInstance(dataFormatInput);
}
} | repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\SpinFactoryImpl.java | 1 |
请完成以下Java代码 | public abstract class ForwardingEvaluatee implements Evaluatee
{
protected final Evaluatee delegate;
public ForwardingEvaluatee(@NonNull final Evaluatee delegate) {this.delegate = delegate;}
@Nullable
@Override
public <T> T get_ValueAsObject(final String variableName)
{
return delegate.get_ValueAsObject(variableName);
}
@Nullable
@Override
public String get_ValueAsString(final String variableName)
{
return delegate.get_ValueAsString(variableName);
}
@Nullable
@Override
public Integer get_ValueAsInt(final String variableName, @Nullable final Integer defaultValue)
{
return delegate.get_ValueAsInt(variableName, defaultValue);
}
@Nullable | @Override
public Boolean get_ValueAsBoolean(final String variableName, @Nullable final Boolean defaultValue)
{
return delegate.get_ValueAsBoolean(variableName, defaultValue);
}
@Nullable
@Override
public BigDecimal get_ValueAsBigDecimal(final String variableName, @Nullable final BigDecimal defaultValue)
{
return delegate.get_ValueAsBigDecimal(variableName, defaultValue);
}
@Nullable
@Override
public Date get_ValueAsDate(final String variableName, @Nullable final Date defaultValue)
{
return delegate.get_ValueAsDate(variableName, defaultValue);
}
@Override
public Optional<Object> get_ValueIfExists(final @NonNull String variableName, final @NonNull Class<?> targetType)
{
return delegate.get_ValueIfExists(variableName, targetType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\ForwardingEvaluatee.java | 1 |
请完成以下Java代码 | public Integer getDeductionPerAmount() {
return deductionPerAmount;
}
public void setDeductionPerAmount(Integer deductionPerAmount) {
this.deductionPerAmount = deductionPerAmount;
}
public Integer getMaxPercentPerOrder() {
return maxPercentPerOrder;
}
public void setMaxPercentPerOrder(Integer maxPercentPerOrder) {
this.maxPercentPerOrder = maxPercentPerOrder;
}
public Integer getUseUnit() {
return useUnit;
}
public void setUseUnit(Integer useUnit) {
this.useUnit = useUnit;
}
public Integer getCouponStatus() {
return couponStatus;
}
public void setCouponStatus(Integer couponStatus) {
this.couponStatus = couponStatus;
} | @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(", deductionPerAmount=").append(deductionPerAmount);
sb.append(", maxPercentPerOrder=").append(maxPercentPerOrder);
sb.append(", useUnit=").append(useUnit);
sb.append(", couponStatus=").append(couponStatus);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsIntegrationConsumeSetting.java | 1 |
请完成以下Java代码 | public String getExpressionString()
{
return expressionStr;
}
@Override
public String getFormatedExpressionString()
{
return expressionStr; // expressionStr is good enough in this case
}
@Override
public Set<CtxName> getParameters()
{
return _parametersList;
}
protected Object extractParameterValue(final Evaluatee ctx)
{
final String valueStr = parameter.getValueAsString(ctx);
if (valueStr == null || valueStr == CtxNames.VALUE_NULL)
{
return null;
}
return valueStr;
}
@Override
public final V evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
final Object valueObj = extractParameterValue(ctx);
if (valueObj == null)
{
if (onVariableNotFound == OnVariableNotFound.ReturnNoResult) // i.e. !ignoreUnparsable
{
return noResultValue;
}
else if (onVariableNotFound == OnVariableNotFound.Fail)
{
throw ExpressionEvaluationException.newWithTranslatableMessage("@NotFound@: " + parameter);
}
else
{
throw new IllegalArgumentException("Unknown " + OnVariableNotFound.class + " value: " + onVariableNotFound);
}
}
return valueConverter.convertFrom(valueObj, options);
}
}
protected abstract static class GeneralExpressionTemplate<V, ET extends IExpression<V>> extends ExpressionTemplateBase<V, ET>
{
private final StringExpression stringExpression;
/* package */ GeneralExpressionTemplate(final ExpressionContext context, final Compiler<V, ET> compiler, final String expressionStr, final List<Object> expressionChunks)
{
super(context, compiler); | stringExpression = new StringExpression(expressionStr, expressionChunks);
}
@Override
public String getExpressionString()
{
return stringExpression.getExpressionString();
}
@Override
public String getFormatedExpressionString()
{
return stringExpression.getFormatedExpressionString();
}
@Override
public Set<String> getParameterNames()
{
return stringExpression.getParameterNames();
}
@Override
public Set<CtxName> getParameters()
{
return stringExpression.getParameters();
}
@Override
public V evaluate(final Evaluatee ctx, final OnVariableNotFound onVariableNotFound) throws ExpressionEvaluationException
{
final String resultStr = stringExpression.evaluate(ctx, onVariableNotFound);
if (stringExpression.isNoResult(resultStr))
{
if (onVariableNotFound == OnVariableNotFound.ReturnNoResult) // i.e. !ignoreUnparsable
{
return noResultValue;
}
// else if (onVariableNotFound == OnVariableNotFound.Fail) // no need to handle this case because we expect an exception to be already thrown
else
{
throw new IllegalArgumentException("Unknown " + OnVariableNotFound.class + " value: " + onVariableNotFound);
}
}
return valueConverter.convertFrom(resultStr, options);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\StringExpressionSupportTemplate.java | 1 |
请完成以下Java代码 | public class SignalImpl extends BaseElementImpl implements Signal {
protected static Attribute<String> nameAttribute;
protected static AttributeReference<ItemDefinition> structureRefAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Signal.class, BPMN_ELEMENT_SIGNAL)
.namespaceUri(BPMN20_NS)
.extendsType(RootElement.class)
.instanceProvider(new ModelTypeInstanceProvider<Signal>() {
public Signal newInstance(ModelTypeInstanceContext instanceContext) {
return new SignalImpl(instanceContext);
}
});
nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME)
.build();
structureRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_STRUCTURE_REF)
.qNameAttributeReference(ItemDefinition.class)
.build();
typeBuilder.build(); | }
public SignalImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getName() {
return nameAttribute.getValue(this);
}
public void setName(String name) {
nameAttribute.setValue(this, name);
}
public ItemDefinition getStructure() {
return structureRefAttribute.getReferenceTargetElement(this);
}
public void setStructure(ItemDefinition structure) {
structureRefAttribute.setReferenceTargetElement(this, structure);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\SignalImpl.java | 1 |
请完成以下Java代码 | private int getDisplayType(final PropertyDescriptor pd)
{
int displayType = getDisplayType(pd.getReadMethod());
if (displayType <= 0)
{
displayType = getDisplayType(pd.getWriteMethod());
}
if (displayType <= 0)
{
displayType = suggestDisplayType(pd.getReadMethod().getReturnType());
}
return displayType;
}
private static final int suggestDisplayType(final Class<?> returnType)
{
if (returnType == String.class)
{
return DisplayType.String;
}
else if (returnType == Boolean.class || returnType == boolean.class)
{
return DisplayType.YesNo;
}
else if (returnType == BigDecimal.class)
{
return DisplayType.Amount;
}
else if (returnType == Integer.class)
{
return DisplayType.Integer;
}
else if (Date.class.isAssignableFrom(returnType))
{
return DisplayType.Date;
}
else
{
return -1;
}
}
private int getDisplayType(final Method method)
{
if (method == null)
{
return -1;
} | final ColumnInfo info = method.getAnnotation(ColumnInfo.class);
if (info == null)
{
return -1;
}
final int displayType = info.displayType();
return displayType > 0 ? displayType : -1;
}
private boolean isSelectionColumn(final PropertyDescriptor pd)
{
Boolean selectionColumn = getSelectionColumn(pd.getReadMethod());
if (selectionColumn == null)
{
selectionColumn = getSelectionColumn(pd.getWriteMethod());
}
return selectionColumn != null ? selectionColumn : false;
}
private Boolean getSelectionColumn(final Method method)
{
if (method == null)
{
return null;
}
final ColumnInfo info = method.getAnnotation(ColumnInfo.class);
if (info == null)
{
return null;
}
return info.selectionColumn();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\swing\table\TableModelMetaInfo.java | 1 |
请完成以下Java代码 | public ObjectInputFilter apply(ObjectInputFilter current, ObjectInputFilter next) {
if (current == null) {
Class<?> caller = findInStack(DeserializationService.class);
if (caller == null) {
current = FilterUtils.fallbackFilter();
} else if (caller.equals(SmallObjectService.class)) {
current = FilterUtils.safeSizeFilter(190);
} else if (caller.equals(LowDepthService.class)) {
current = FilterUtils.safeDepthFilter(2);
} else if (caller.equals(LimitedArrayService.class)) {
current = FilterUtils.safeArrayFilter(3);
}
}
return ObjectInputFilter.merge(current, next); | }
private static Class<?> findInStack(Class<?> superType) {
for (StackTraceElement element : Thread.currentThread()
.getStackTrace()) {
try {
Class<?> subType = Class.forName(element.getClassName());
if (superType.isAssignableFrom(subType)) {
return subType;
}
} catch (ClassNotFoundException e) {
return null;
}
}
return null;
}
} | repos\tutorials-master\core-java-modules\core-java-17\src\main\java\com\baeldung\deserializationfilters\ContextSpecificDeserializationFilterFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void prepareRestAPIContext(@NonNull final Exchange exchange)
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
final WOORestAPIContext context = WOORestAPIContext.builder()
.request(request)
.build();
exchange.setProperty(ROUTE_PROPERTY_WOO_REST_API_CONTEXT, context);
}
private void prepareExternalStatusCreateRequest(@NonNull final Exchange exchange, @NonNull final JsonExternalStatus status)
{
final WOORestAPIContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_WOO_REST_API_CONTEXT, WOORestAPIContext.class);
final JsonExternalSystemRequest request = context.getRequest();
final JsonStatusRequest jsonStatusRequest = JsonStatusRequest.builder()
.status(status)
.pInstanceId(request.getAdPInstanceId())
.build();
final ExternalStatusCreateCamelRequest camelRequest = ExternalStatusCreateCamelRequest.builder()
.jsonStatusRequest(jsonStatusRequest)
.externalSystemConfigType(getExternalSystemTypeCode())
.externalSystemChildConfigValue(request.getExternalSystemChildConfigValue())
.serviceValue(getServiceValue())
.build();
exchange.getIn().setBody(camelRequest, JsonExternalSystemRequest.class);
}
@Override
public String getServiceValue()
{
return "defaultRestAPIWOO";
}
@Override | public String getExternalSystemTypeCode()
{
return WOO_EXTERNAL_SYSTEM_NAME;
}
@Override
public String getEnableCommand()
{
return ENABLE_RESOURCE_ROUTE;
}
@Override
public String getDisableCommand()
{
return DISABLE_RESOURCE_ROUTE;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-woocommerce\src\main\java\de\metas\camel\externalsystems\woocommerce\restapi\RestAPIRouteBuilder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String createPLVName(final @NonNull String priceListName, final @NonNull LocalDate date)
{
final String formattedDate = date.format(DateTimeFormatter.ISO_LOCAL_DATE);
return priceListName + " " + formattedDate;
}
@Override
public int updateAllPLVName(final String namePrefix, final PriceListId priceListId)
{
final String dateFormat = "YYYY-MM-DD"; // equivalent of DateTimeFormatter.ISO_LOCAL_DATE
final UserId updatedBy = Env.getLoggedUserId();
final Timestamp now = SystemTime.asTimestamp(); | final String sqlStr =
" UPDATE " + I_M_PriceList_Version.Table_Name + " plv "
+ " SET " + I_M_PriceList_Version.COLUMNNAME_Name + " = ? || ' ' || to_char(plv." + I_M_PriceList_Version.COLUMNNAME_ValidFrom + ", '" + dateFormat + "'), "
+ " " + I_M_PriceList_Version.COLUMNNAME_UpdatedBy + " = ?, "
+ " " + I_M_PriceList_Version.COLUMNNAME_Updated + " = ? "
+ " WHERE plv." + I_M_PriceList_Version.COLUMNNAME_M_PriceList_ID + " = ? ";
final int recordsUpdated = DB.executeUpdateAndThrowExceptionOnFail(sqlStr, new Object[] { namePrefix, updatedBy, now, priceListId }, ITrx.TRXNAME_ThreadInherited);
final CacheInvalidateMultiRequest cacheInvalidateRequest = CacheInvalidateMultiRequest.allChildRecords(I_M_PriceList.Table_Name, priceListId.getRepoId(), I_M_PriceList_Version.Table_Name);
CacheMgt.get().reset(cacheInvalidateRequest);
return recordsUpdated;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\service\impl\PriceListBL.java | 2 |
请完成以下Java代码 | public static POSTerminalId ofRepoId(final int repoId)
{
return new POSTerminalId(repoId);
}
@JsonCreator
public static POSTerminalId ofString(@NonNull final String str)
{
return RepoIdAwares.ofObject(str, POSTerminalId.class, POSTerminalId::ofRepoId);
}
@Nullable
public static POSTerminalId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new POSTerminalId(repoId) : null;
} | public static int toRepoId(@Nullable final OrderId id)
{
return id != null ? id.getRepoId() : -1;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final POSTerminalId id1, @Nullable final POSTerminalId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSTerminalId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | BeanPostProcessor cacheServerLoadProbeWrappingBeanPostProcessor() {
return new BeanPostProcessor() {
@Nullable @Override @SuppressWarnings("all")
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof CacheServerFactoryBean) {
CacheServerFactoryBean cacheServerFactoryBean = (CacheServerFactoryBean) bean;
ServerLoadProbe serverLoadProbe =
ObjectUtils.<ServerLoadProbe>get(bean, "serverLoadProbe");
if (serverLoadProbe != null) {
cacheServerFactoryBean.setServerLoadProbe(wrap(serverLoadProbe));
}
}
return bean;
}
@Nullable @Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (bean instanceof CacheServer) {
CacheServer cacheServer = (CacheServer) bean;
Optional.ofNullable(cacheServer.getLoadProbe())
.filter(it -> !(it instanceof ActuatorServerLoadProbeWrapper))
.filter(it -> cacheServer.getLoadPollInterval() > 0)
.filter(it -> !cacheServer.isRunning())
.ifPresent(serverLoadProbe ->
cacheServer.setLoadProbe(new ActuatorServerLoadProbeWrapper(serverLoadProbe)));
}
return bean;
} | private ServerLoadProbe wrap(ServerLoadProbe serverLoadProbe) {
return new ActuatorServerLoadProbeWrapper(serverLoadProbe);
}
};
}
public static final class PeerCacheCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
Cache peerCache = CacheUtils.getCache();
ClientCache clientCache = CacheUtils.getClientCache();
return peerCache != null || clientCache == null;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-actuator-autoconfigure\src\main\java\org\springframework\geode\boot\actuate\autoconfigure\config\PeerCacheHealthIndicatorConfiguration.java | 2 |
请完成以下Java代码 | public int getC_BP_Contact_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_Contact_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);
}
@Override
public void setC_BPartner_Location_ID (final int C_BPartner_Location_ID)
{
if (C_BPartner_Location_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_Location_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Location_ID, C_BPartner_Location_ID);
}
@Override
public int getC_BPartner_Location_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID);
}
@Override
public void setCity (final @Nullable java.lang.String City)
{
set_Value (COLUMNNAME_City, City);
}
@Override
public java.lang.String getCity()
{
return get_ValueAsString(COLUMNNAME_City);
}
@Override
public void setES_DocumentId (final java.lang.String ES_DocumentId)
{
set_ValueNoCheck (COLUMNNAME_ES_DocumentId, ES_DocumentId);
}
@Override
public java.lang.String getES_DocumentId()
{
return get_ValueAsString(COLUMNNAME_ES_DocumentId);
}
@Override
public void setFirstname (final @Nullable java.lang.String Firstname)
{
set_Value (COLUMNNAME_Firstname, Firstname);
}
@Override
public java.lang.String getFirstname()
{
return get_ValueAsString(COLUMNNAME_Firstname);
} | @Override
public void setIsCompany (final boolean IsCompany)
{
set_ValueNoCheck (COLUMNNAME_IsCompany, IsCompany);
}
@Override
public boolean isCompany()
{
return get_ValueAsBoolean(COLUMNNAME_IsCompany);
}
@Override
public void setLastname (final @Nullable java.lang.String Lastname)
{
set_Value (COLUMNNAME_Lastname, Lastname);
}
@Override
public java.lang.String getLastname()
{
return get_ValueAsString(COLUMNNAME_Lastname);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Adv_Search.java | 1 |
请完成以下Java代码 | public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public String getHistoryConfiguration() {
return historyConfiguration;
}
public void setHistoryConfiguration(String historyConfiguration) {
this.historyConfiguration = historyConfiguration;
}
public String getIncidentMessage() {
return incidentMessage;
}
public void setIncidentMessage(String incidentMessage) {
this.incidentMessage = incidentMessage;
}
public void setIncidentState(int incidentState) {
this.incidentState = incidentState;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public void setJobDefinitionId(String jobDefinitionId) {
this.jobDefinitionId = jobDefinitionId;
} | public boolean isOpen() {
return IncidentState.DEFAULT.getStateCode() == incidentState;
}
public boolean isDeleted() {
return IncidentState.DELETED.getStateCode() == incidentState;
}
public boolean isResolved() {
return IncidentState.RESOLVED.getStateCode() == incidentState;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public String getFailedActivityId() {
return failedActivityId;
}
public void setFailedActivityId(String failedActivityId) {
this.failedActivityId = failedActivityId;
}
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricIncidentEventEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MemberReadHistoryController {
@Autowired
private MemberReadHistoryService memberReadHistoryService;
@ApiOperation("创建浏览记录")
@RequestMapping(value = "/create", method = RequestMethod.POST)
@ResponseBody
public CommonResult create(@RequestBody MemberReadHistory memberReadHistory) {
int count = memberReadHistoryService.create(memberReadHistory);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation("删除浏览记录")
@RequestMapping(value = "/delete", method = RequestMethod.POST)
@ResponseBody
public CommonResult delete(@RequestParam("ids") List<String> ids) {
int count = memberReadHistoryService.delete(ids);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
} | @ApiOperation("清空浏览记录")
@RequestMapping(value = "/clear", method = RequestMethod.POST)
@ResponseBody
public CommonResult clear() {
memberReadHistoryService.clear();
return CommonResult.success(null);
}
@ApiOperation("分页获取浏览记录")
@RequestMapping(value = "/list", method = RequestMethod.GET)
@ResponseBody
public CommonResult<CommonPage<MemberReadHistory>> list(@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
Page<MemberReadHistory> page = memberReadHistoryService.list(pageNum, pageSize);
return CommonResult.success(CommonPage.restPage(page));
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\controller\MemberReadHistoryController.java | 2 |
请完成以下Java代码 | public void setState(String state) {
this.state = state;
}
public String getCounty() {
return county;
}
public void setCounty(String county) {
this.county = county;
}
public String getTimezone() {
return timezone;
} | public void setTimezone(String timezone) {
this.timezone = timezone;
}
@JsonIgnore
@Override public String getId() {
return zip;
}
@JsonIgnore
@Override public boolean isNew() {
return !persisted;
}
} | repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\spring-project\src\main\java\com\baeldung\spring_project\domain\ZipCode.java | 1 |
请完成以下Java代码 | public VariableMap execute(CommandContext commandContext) {
ensureNotNull("taskId", taskId);
TaskManager taskManager = commandContext.getTaskManager();
TaskEntity task = taskManager.findTaskById(taskId);
ensureNotNull("Cannot find task with id " + taskId, "task", task);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkTaskWork(task);
}
TaskDefinition taskDefinition = task.getTaskDefinition();
if(taskDefinition != null) {
TaskFormHandler taskFormHandler = taskDefinition.getTaskFormHandler();
taskFormHandler.submitFormVariables(properties, task);
} else {
// set variables on standalone task
task.setVariables(properties);
}
ExecutionEntity execution = task.getProcessInstance();
ExecutionVariableSnapshotObserver variablesListener = null;
if (returnVariables && execution != null) {
variablesListener = new ExecutionVariableSnapshotObserver(execution, false, deserializeValues);
}
// complete or resolve the task
if (DelegationState.PENDING.equals(task.getDelegationState())) {
task.resolve();
task.logUserOperation(UserOperationLogEntry.OPERATION_TYPE_RESOLVE);
task.triggerUpdateEvent();
} else {
task.logUserOperation(UserOperationLogEntry.OPERATION_TYPE_COMPLETE); | task.complete();
}
if (returnVariables)
{
if (variablesListener != null) {
return variablesListener.getVariables();
} else {
return task.getCaseDefinitionId() == null ? null : task.getVariablesTyped(false);
}
}
else
{
return null;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SubmitTaskFormCmd.java | 1 |
请完成以下Java代码 | public void setCamundaCandidateStarterGroupsList(List<String> camundaCandidateStarterGroupsList) {
String candidateStarterGroups = StringUtil.joinCommaSeparatedList(camundaCandidateStarterGroupsList);
camundaCandidateStarterGroupsAttribute.setValue(this, candidateStarterGroups);
}
public String getCamundaCandidateStarterUsers() {
return camundaCandidateStarterUsersAttribute.getValue(this);
}
public void setCamundaCandidateStarterUsers(String camundaCandidateStarterUsers) {
camundaCandidateStarterUsersAttribute.setValue(this, camundaCandidateStarterUsers);
}
public List<String> getCamundaCandidateStarterUsersList() {
String candidateStarterUsers = camundaCandidateStarterUsersAttribute.getValue(this);
return StringUtil.splitCommaSeparatedList(candidateStarterUsers);
}
public void setCamundaCandidateStarterUsersList(List<String> camundaCandidateStarterUsersList) {
String candidateStarterUsers = StringUtil.joinCommaSeparatedList(camundaCandidateStarterUsersList);
camundaCandidateStarterUsersAttribute.setValue(this, candidateStarterUsers);
}
public String getCamundaJobPriority() {
return camundaJobPriorityAttribute.getValue(this);
}
public void setCamundaJobPriority(String jobPriority) {
camundaJobPriorityAttribute.setValue(this, jobPriority);
}
@Override
public String getCamundaTaskPriority() {
return camundaTaskPriorityAttribute.getValue(this);
}
@Override
public void setCamundaTaskPriority(String taskPriority) {
camundaTaskPriorityAttribute.setValue(this, taskPriority);
}
@Override
public Integer getCamundaHistoryTimeToLive() {
String ttl = getCamundaHistoryTimeToLiveString();
if (ttl != null) {
return Integer.parseInt(ttl); | }
return null;
}
@Override
public void setCamundaHistoryTimeToLive(Integer historyTimeToLive) {
var value = historyTimeToLive == null ? null : String.valueOf(historyTimeToLive);
setCamundaHistoryTimeToLiveString(value);
}
@Override
public String getCamundaHistoryTimeToLiveString() {
return camundaHistoryTimeToLiveAttribute.getValue(this);
}
@Override
public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) {
if (historyTimeToLive == null) {
camundaHistoryTimeToLiveAttribute.removeAttribute(this);
} else {
camundaHistoryTimeToLiveAttribute.setValue(this, historyTimeToLive);
}
}
@Override
public Boolean isCamundaStartableInTasklist() {
return camundaIsStartableInTasklistAttribute.getValue(this);
}
@Override
public void setCamundaIsStartableInTasklist(Boolean isStartableInTasklist) {
camundaIsStartableInTasklistAttribute.setValue(this, isStartableInTasklist);
}
@Override
public String getCamundaVersionTag() {
return camundaVersionTagAttribute.getValue(this);
}
@Override
public void setCamundaVersionTag(String versionTag) {
camundaVersionTagAttribute.setValue(this, versionTag);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ProcessImpl.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
String token = System.getenv(OPENAI_TOKEN);
OpenAiService service = new OpenAiService(token);
List<ChatMessage> messages = new ArrayList<>();
ChatMessage systemMessage = new ChatMessage(ChatMessageRole.SYSTEM.value(), PROMPT);
messages.add(systemMessage);
System.out.print(GREETING);
Scanner scanner = new Scanner(System.in);
ChatMessage firstMsg = new ChatMessage(ChatMessageRole.USER.value(), scanner.nextLine());
messages.add(firstMsg);
while (true) {
ChatCompletionRequest chatCompletionRequest = ChatCompletionRequest
.builder()
.model(MODEL)
.maxTokens(MAX_TOKENS)
.messages(messages) | .build();
ChatCompletionResult result = service.createChatCompletion(chatCompletionRequest);
long usedTokens = result.getUsage().getTotalTokens();
ChatMessage response = result.getChoices().get(0).getMessage();
messages.add(response);
System.out.println(response.getContent());
System.out.println("Total tokens used: " + usedTokens);
System.out.print("Anything else?\n");
String nextLine = scanner.nextLine();
if (nextLine.equalsIgnoreCase("exit")) {
scanner.close();
System.exit(0);
}
messages.add(new ChatMessage(ChatMessageRole.USER.value(), nextLine));
}
}
} | repos\tutorials-master\libraries-ai\src\main\java\baeldungassistant\BaeldungLearningAssistant.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public <T extends ReferenceListAwareEnum> T getReferenceListAware(final String name, final T defaultValue, final Class<T> type)
{
final String code = sysConfigDAO.getValue(name, ClientAndOrgId.SYSTEM).orElse(null);
return code != null && !Check.isBlank(code)
? ReferenceListAwareEnums.ofCode(code, type)
: defaultValue;
}
@Override
public <T extends Enum<T>> ImmutableSet<T> getCommaSeparatedEnums(@NonNull final String sysconfigName, @NonNull final Class<T> enumType)
{
final String string = StringUtils.trimBlankToNull(sysConfigDAO.getValue(sysconfigName, ClientAndOrgId.SYSTEM).orElse(null));
if (string == null || string.equals("-"))
{
return ImmutableSet.of();
}
return Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.splitToList(string)
.stream() | .map(name -> {
try
{
return Enum.valueOf(enumType, name);
}
catch (final Exception ex)
{
logger.warn("Failed converting `{}` to enum {}. Ignoring it.", name, enumType, ex);
return null;
}
})
.filter(Objects::nonNull)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\service\impl\SysConfigBL.java | 2 |
请完成以下Java代码 | private final void updateOrderLine_RegularProduct(final I_C_OrderLine newOrderLine, final ICablesOrderLineQuickInput fromQuickInputModel)
{
if (fromQuickInputModel.getPlug1_Product_ID() <= 0)
{
throw new FillMandatoryException(ICablesOrderLineQuickInput.COLUMNNAME_Plug1_Product_ID);
}
final ProductId productId = ProductId.ofRepoId(fromQuickInputModel.getPlug1_Product_ID());
final BigDecimal qty = fromQuickInputModel.getQty();
if (qty.signum() <= 0)
{
throw new FillMandatoryException(ICablesOrderLineQuickInput.COLUMNNAME_Qty);
}
newOrderLine.setM_Product_ID(productId.getRepoId());
newOrderLine.setQtyEntered(qty);
}
private ProductId getBOMProductId(ICablesOrderLineQuickInput quickInputModel)
{
final ProductId plugProduct1Id = ProductId.ofRepoId(quickInputModel.getPlug1_Product_ID());
final ProductId plugProduct2Id = ProductId.ofRepoId(quickInputModel.getPlug2_Product_ID());
final ProductId cableProductId = ProductId.ofRepoId(quickInputModel.getCable_Product_ID());
final IProductBOMDAO productBOMsRepo = Services.get(IProductBOMDAO.class);
final List<I_PP_Product_BOM> boms = productBOMsRepo.retrieveBOMsContainingExactProducts(plugProduct1Id.getRepoId(), cableProductId.getRepoId(), plugProduct2Id.getRepoId());
if (boms.isEmpty())
{ | throw new AdempiereException("@NotFound@ @PP_Product_BOM_ID@");
}
else if (boms.size() > 1)
{
final String bomValues = boms.stream().map(I_PP_Product_BOM::getValue).collect(Collectors.joining(", "));
throw new AdempiereException("More than one BOMs found: " + bomValues);
}
else
{
final I_PP_Product_BOM bom = boms.get(0);
return ProductId.ofRepoId(bom.getM_Product_ID());
}
}
private boolean isCableProduct(final ICablesOrderLineQuickInput quickInputModel)
{
return quickInputModel.getPlug1_Product_ID() > 0
&& quickInputModel.getCable_Product_ID() > 0
&& quickInputModel.getPlug2_Product_ID() > 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\vertical\cables\webui\quickinput\CableSalesOrderLineQuickInputProcessor.java | 1 |
请完成以下Java代码 | public StandardDocumentReportType getStandardDocumentReportType()
{
return StandardDocumentReportType.MANUFACTURING_ORDER;
}
@Override
public @NonNull DocumentReportInfo getDocumentReportInfo(
@NonNull final TableRecordReference recordRef,
@Nullable final PrintFormatId adPrintFormatToUseId, final AdProcessId reportProcessIdToUse)
{
final PPOrderId manufacturingOrderId = recordRef.getIdAssumingTableName(I_PP_Order.Table_Name, PPOrderId::ofRepoId);
final I_PP_Order manufacturingOrder = ppOrderBL.getById(manufacturingOrderId);
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(manufacturingOrder.getC_BPartner_ID());
final I_C_BPartner bpartner = bpartnerId == null? null: util.getBPartnerById(bpartnerId);
final DocTypeId docTypeId = extractDocTypeId(manufacturingOrder);
final I_C_DocType docType = util.getDocTypeById(docTypeId);
final ClientId clientId = ClientId.ofRepoId(manufacturingOrder.getAD_Client_ID());
final PrintFormatId printFormatId = CoalesceUtil.coalesceSuppliers(
() -> adPrintFormatToUseId,
() -> bpartnerId == null ? null :
util.getBPartnerPrintFormats(bpartnerId).getPrintFormatIdByDocTypeId(docTypeId).orElse(null),
() -> PrintFormatId.ofRepoIdOrNull(docType.getAD_PrintFormat_ID()),
() -> util.getDefaultPrintFormats(clientId).getManufacturingOrderPrintFormatId());
if (printFormatId == null)
{
throw new AdempiereException("@NotFound@ @AD_PrintFormat_ID@");
} | final Language language = bpartner == null ? null : util.getBPartnerLanguage(bpartner).orElse(null);
final BPPrintFormatQuery bpPrintFormatQuery = bpartnerId == null ? null : BPPrintFormatQuery.builder()
.adTableId(recordRef.getAdTableId())
.bpartnerId(bpartnerId)
.bPartnerLocationId(null)
.docTypeId(docTypeId)
.onlyCopiesGreaterZero(true)
.build();
return DocumentReportInfo.builder()
.recordRef(TableRecordReference.of(I_PP_Order.Table_Name, manufacturingOrderId))
.reportProcessId(util.getReportProcessIdByPrintFormatId(printFormatId))
.copies(util.getDocumentCopies(docType, bpPrintFormatQuery))
.documentNo(manufacturingOrder.getDocumentNo())
.bpartnerId(bpartnerId)
.docTypeId(docTypeId)
.language(language)
.build();
}
private DocTypeId extractDocTypeId(@NonNull final I_PP_Order manufacturingOrder)
{
return DocTypeId.optionalOfRepoId(manufacturingOrder.getC_DocType_ID())
.orElseThrow(() -> new AdempiereException("No document type set"));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\ManufacturingOrderDocumentReportAdvisor.java | 1 |
请完成以下Java代码 | private void save(final I_C_Async_Batch asyncBatch)
{
Services.get(IQueueDAO.class).save(asyncBatch);
}
private int setAsyncBatchCountEnqueued(@NonNull final I_C_Queue_WorkPackage workPackage, final int offset)
{
final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoIdOrNull(workPackage.getC_Async_Batch_ID());
if (asyncBatchId == null)
{
return 0;
}
lock.lock();
try
{
final I_C_Async_Batch asyncBatch = asyncBatchDAO.retrieveAsyncBatchRecordOutOfTrx(asyncBatchId);
final Timestamp enqueued = SystemTime.asTimestamp();
if (asyncBatch.getFirstEnqueued() == null)
{
asyncBatch.setFirstEnqueued(enqueued); | }
asyncBatch.setLastEnqueued(enqueued);
final int countEnqueued = asyncBatch.getCountEnqueued() + offset;
asyncBatch.setCountEnqueued(countEnqueued);
// we just enqueued something, so we are clearly not done yet
asyncBatch.setIsProcessing(true);
asyncBatch.setProcessed(false);
save(asyncBatch);
return countEnqueued;
}
finally
{
lock.unlock();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AsyncBatchBL.java | 1 |
请完成以下Java代码 | public class WordVectorModel extends AbstractVectorModel<String>
{
/**
* 加载模型<br>
*
* @param modelFileName 模型路径
* @throws IOException 加载错误
*/
public WordVectorModel(String modelFileName) throws IOException
{
this(modelFileName, new TreeMap<String, Vector>());
}
/**
* 加载模型
*
* @param modelFileName 模型路径
* @param storage 一个空白的Map(HashMap等)
* @throws IOException 加载错误
*/
public WordVectorModel(String modelFileName, Map<String, Vector> storage) throws IOException
{
super(loadVectorMap(modelFileName, storage));
}
private static Map<String, Vector> loadVectorMap(String modelFileName, Map<String, Vector> storage) throws IOException
{
VectorsReader reader = new VectorsReader(modelFileName);
reader.readVectorFile();
for (int i = 0; i < reader.vocab.length; i++)
{
storage.put(reader.vocab[i], new Vector(reader.matrix[i]));
}
return storage;
}
/**
* 返回跟 A - B + C 最相似的词语,比如 中国 - 北京 + 东京 = 日本。输入顺序按照 中国 北京 东京
*
* @param A 做加法的词语
* @param B 做减法的词语
* @param C 做加法的词语
* @return 与(A - B + C)语义距离最近的词语及其相似度列表
*/
public List<Map.Entry<String, Float>> analogy(String A, String B, String C)
{
return analogy(A, B, C, 10);
}
/**
* 返回跟 A - B + C 最相似的词语,比如 中国 - 北京 + 东京 = 日本。输入顺序按照 中国 北京 东京
*
* @param A 做加法的词语
* @param B 做减法的词语
* @param C 做加法的词语
* @param size topN个
* @return 与(A - B + C)语义距离最近的词语及其相似度列表
*/ | public List<Map.Entry<String, Float>> analogy(String A, String B, String C, int size)
{
Vector a = storage.get(A);
Vector b = storage.get(B);
Vector c = storage.get(C);
if (a == null || b == null || c == null)
{
return Collections.emptyList();
}
List<Map.Entry<String, Float>> resultList = nearest(a.minus(b).add(c), size + 3);
ListIterator<Map.Entry<String, Float>> listIterator = resultList.listIterator();
while (listIterator.hasNext())
{
String key = listIterator.next().getKey();
if (key.equals(A) || key.equals(B) || key.equals(C))
{
listIterator.remove();
}
}
if (resultList.size() > size)
{
resultList = resultList.subList(0, size);
}
return resultList;
}
@Override
public Vector query(String query)
{
return vector(query);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\WordVectorModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Charset getDefaultEncoding() {
return this.defaultEncoding;
}
public void setDefaultEncoding(Charset defaultEncoding) {
this.defaultEncoding = defaultEncoding;
}
public Map<String, String> getProperties() {
return this.properties;
}
public @Nullable String getJndiName() {
return this.jndiName;
}
public void setJndiName(@Nullable String jndiName) {
this.jndiName = jndiName;
}
public Ssl getSsl() {
return this.ssl;
}
public static class Ssl {
/**
* Whether to enable SSL support. If enabled, 'mail.(protocol).ssl.enable'
* property is set to 'true'.
*/
private boolean enabled;
/**
* SSL bundle name. If set, 'mail.(protocol).ssl.socketFactory' property is set to
* an SSLSocketFactory obtained from the corresponding SSL bundle.
* <p>
* Note that the STARTTLS command can use the corresponding SSLSocketFactory, even
* if the 'mail.(protocol).ssl.enable' property is not set.
*/
private @Nullable String bundle; | public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-mail\src\main\java\org\springframework\boot\mail\autoconfigure\MailProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setPassword(String password) {
this.password = password;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
}
public static class SslCertificateProperties {
@NestedConfigurationProperty
private SslCertificateAliasProperties alias = new SslCertificateAliasProperties();
public SslCertificateAliasProperties getAlias() {
return this.alias;
}
}
public static class SslCertificateAliasProperties {
private String all;
private String cluster;
private String defaultAlias;
private String gateway;
private String jmx;
private String locator;
private String server;
private String web;
public String getAll() {
return this.all;
}
public void setAll(String all) {
this.all = all;
}
public String getCluster() {
return this.cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getDefaultAlias() {
return this.defaultAlias;
} | public void setDefaultAlias(String defaultAlias) {
this.defaultAlias = defaultAlias;
}
public String getGateway() {
return this.gateway;
}
public void setGateway(String gateway) {
this.gateway = gateway;
}
public String getJmx() {
return this.jmx;
}
public void setJmx(String jmx) {
this.jmx = jmx;
}
public String getLocator() {
return this.locator;
}
public void setLocator(String locator) {
this.locator = locator;
}
public String getServer() {
return this.server;
}
public void setServer(String server) {
this.server = server;
}
public String getWeb() {
return this.web;
}
public void setWeb(String web) {
this.web = web;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SslProperties.java | 2 |
请完成以下Java代码 | public boolean isCanReport ()
{
Object oo = get_Value(COLUMNNAME_IsCanReport);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Ausschluß.
@param IsExclude
Exclude access to the data - if not selected Include access to the data
*/
@Override
public void setIsExclude (boolean IsExclude)
{
set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude));
}
/** Get Ausschluß.
@return Exclude access to the data - if not selected Include access to the data
*/
@Override
public boolean isExclude ()
{
Object oo = get_Value(COLUMNNAME_IsExclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set Schreibgeschützt.
@param IsReadOnly
Field is read only
*/
@Override
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Schreibgeschützt.
@return Field is read only
*/
@Override
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table_Access.java | 1 |
请完成以下Java代码 | public List<PurchaseCandidate> getAllByPurchaseOrderLineIds(@NonNull final Collection<OrderAndLineId> purchaseOrderLineIds)
{
final Set<PurchaseCandidateId> purchaseCandidateIds = queryBL.createQueryBuilder(I_C_PurchaseCandidate_Alloc.class)
.addInArrayFilter(I_C_PurchaseCandidate_Alloc.COLUMNNAME_C_OrderLinePO_ID, OrderAndLineId.getOrderLineRepoIds(purchaseOrderLineIds))
.create()
.stream()
.map(I_C_PurchaseCandidate_Alloc::getC_PurchaseCandidate_ID)
.map(PurchaseCandidateId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
return getAllByIds(purchaseCandidateIds);
}
public void deletePurchaseCandidates(@NonNull final DeletePurchaseCandidateQuery deletePurchaseCandidateQuery)
{
final IQueryBuilder<I_C_PurchaseCandidate> deleteQuery = queryBL.createQueryBuilder(I_C_PurchaseCandidate.class);
if (deletePurchaseCandidateQuery.isOnlySimulated())
{
deleteQuery.addEqualsFilter(I_C_PurchaseCandidate.COLUMNNAME_IsSimulated, deletePurchaseCandidateQuery.isOnlySimulated());
}
if (deletePurchaseCandidateQuery.getSalesOrderLineId() != null)
{
deleteQuery.addEqualsFilter(I_C_PurchaseCandidate.COLUMNNAME_C_OrderLineSO_ID, deletePurchaseCandidateQuery.getSalesOrderLineId());
}
if (deleteQuery.getCompositeFilter().isEmpty())
{
throw new AdempiereException("Deleting all I_C_PurchaseCandidate records is not allowed!");
}
deleteQuery
.create()
.deleteDirectly();
}
@NonNull
private IQuery<I_C_PurchaseCandidate> toSqlQuery(@NonNull final PurchaseCandidateQuery query)
{
final IQueryBuilder<I_C_PurchaseCandidate> queryBuilder = queryBL.createQueryBuilder(I_C_PurchaseCandidate.class)
.addOnlyActiveRecordsFilter(); | if (query.getExternalSystemType() != null)
{
final ExternalSystemId externalSystemId = externalSystemRepository.getIdByType(query.getExternalSystemType());
queryBuilder.addEqualsFilter(I_C_PurchaseCandidate.COLUMNNAME_ExternalSystem_ID, externalSystemId);
}
if (query.getExternalHeaderId() != null)
{
queryBuilder.addEqualsFilter(I_C_PurchaseCandidate.COLUMN_ExternalHeaderId, query.getExternalHeaderId());
}
if (query.getExternalLineId() != null)
{
queryBuilder.addEqualsFilter(I_C_PurchaseCandidate.COLUMNNAME_ExternalLineId, query.getExternalLineId());
}
return queryBuilder
.create();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\PurchaseCandidateRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void init() {
try {
authenticationManagerBuilder
.userDetailsService(userDetailsService)
.passwordEncoder(passwordEncoder());
} catch (Exception e) {
throw new BeanInitializationException("Security configuration failed", e);
}
}
@Override
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring()
.antMatchers(HttpMethod.OPTIONS, "/**")
.antMatchers("/app/**/*.{js,html}")
.antMatchers("/i18n/**")
.antMatchers("/content/**")
.antMatchers("/h2-console/**")
.antMatchers("/swagger-ui/index.html")
.antMatchers("/test/**");
}
@Override
public void configure(HttpSecurity http) throws Exception {
http
.csrf()
.disable()
.addFilterBefore(corsFilter, UsernamePasswordAuthenticationFilter.class)
.exceptionHandling()
.authenticationEntryPoint(problemSupport)
.accessDeniedHandler(problemSupport)
.and()
.headers()
.frameOptions()
.disable()
.and() | .sessionManagement()
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
.and()
.authorizeRequests()
.antMatchers("/api/books/purchase/**").authenticated()
.antMatchers("/api/register").permitAll()
.antMatchers("/api/activate").permitAll()
.antMatchers("/api/authenticate").permitAll()
.antMatchers("/api/account/reset-password/init").permitAll()
.antMatchers("/api/account/reset-password/finish").permitAll()
.antMatchers("/api/**").authenticated()
.antMatchers("/management/health").permitAll()
.antMatchers("/management/info").permitAll()
.antMatchers("/management/**").hasAuthority(AuthoritiesConstants.ADMIN)
.and()
.apply(securityConfigurerAdapter());
}
private JWTConfigurer securityConfigurerAdapter() {
return new JWTConfigurer(tokenProvider);
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\config\SecurityConfiguration.java | 2 |
请完成以下Java代码 | public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Product Key.
@param ProductValue
Key of the Product
*/
public void setProductValue (String ProductValue)
{
set_Value (COLUMNNAME_ProductValue, ProductValue);
}
/** Get Product Key.
@return Key of the Product
*/
public String getProductValue ()
{
return (String)get_Value(COLUMNNAME_ProductValue); | }
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set UOM Code.
@param X12DE355
UOM EDI X12 Code
*/
public void setX12DE355 (String X12DE355)
{
set_Value (COLUMNNAME_X12DE355, X12DE355);
}
/** Get UOM Code.
@return UOM EDI X12 Code
*/
public String getX12DE355 ()
{
return (String)get_Value(COLUMNNAME_X12DE355);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_PriceList.java | 1 |
请完成以下Java代码 | public String getClientId() {
return this.clientId;
}
/**
* Returns the redirect uri.
* @return the redirect uri
*/
@Nullable
public String getRedirectUri() {
return this.redirectUri;
}
/**
* Returns the state.
* @return the state
*/
@Nullable
public String getState() {
return this.state;
}
/**
* Returns the requested (or authorized) scope(s). | * @return the requested (or authorized) scope(s), or an empty {@code Set} if not
* available
*/
public Set<String> getScopes() {
return this.scopes;
}
/**
* Returns the additional parameters.
* @return the additional parameters, or an empty {@code Map} if not available
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\AbstractOAuth2AuthorizationCodeRequestAuthenticationToken.java | 1 |
请完成以下Java代码 | public class StockTrade {
private final String symbol;
private final int quantity;
private final double price;
private final Date tradeDate;
public StockTrade(String symbol, int quantity, double price, Date tradeDate) {
this.symbol = symbol;
this.quantity = quantity;
this.price = price;
this.tradeDate = tradeDate;
}
public String getSymbol() { | return this.symbol;
}
public int getQuantity() {
return this.quantity;
}
public double getPrice() {
return this.price;
}
public Date getTradeDate() {
return this.tradeDate;
}
} | repos\tutorials-master\spring-core-4\src\main\java\com\baeldung\beanpostprocessor\StockTrade.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setCONTACTTELEFAX(String value) {
this.contacttelefax = value;
}
/**
* Gets the value of the contactemail property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCONTACTEMAIL() {
return contactemail;
}
/**
* Sets the value of the contactemail property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCONTACTEMAIL(String value) {
this.contactemail = value;
} | /**
* Gets the value of the contactweb property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCONTACTWEB() {
return contactweb;
}
/**
* Sets the value of the contactweb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCONTACTWEB(String value) {
this.contactweb = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DCTAD1.java | 2 |
请完成以下Java代码 | public int getM_LotCtl_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_LotCtl_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Prefix.
@param Prefix
Prefix before the sequence number
*/
public void setPrefix (String Prefix)
{
set_Value (COLUMNNAME_Prefix, Prefix);
}
/** Get Prefix.
@return Prefix before the sequence number
*/
public String getPrefix ()
{
return (String)get_Value(COLUMNNAME_Prefix);
}
/** Set Start No.
@param StartNo
Starting number/position
*/
public void setStartNo (int StartNo)
{
set_Value (COLUMNNAME_StartNo, Integer.valueOf(StartNo)); | }
/** Get Start No.
@return Starting number/position
*/
public int getStartNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_StartNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Suffix.
@param Suffix
Suffix after the number
*/
public void setSuffix (String Suffix)
{
set_Value (COLUMNNAME_Suffix, Suffix);
}
/** Get Suffix.
@return Suffix after the number
*/
public String getSuffix ()
{
return (String)get_Value(COLUMNNAME_Suffix);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_LotCtl.java | 1 |
请完成以下Java代码 | public class Utf8CharacterMapping implements CharacterMapping, Serializable
{
private static final long serialVersionUID = -6529481088518753872L;
private static final int N = 256;
private static final int[] EMPTYLIST = new int[0];
public static final Charset UTF_8 = Charset.forName("UTF-8");
@Override
public int getInitSize()
{
return N;
}
@Override
public int getCharsetSize()
{
return N;
}
@Override
public int zeroId()
{
return 0;
}
@Override
public int[] toIdList(String key)
{
byte[] bytes = key.getBytes(UTF_8);
int[] res = new int[bytes.length];
for (int i = 0; i < res.length; i++)
{
res[i] = bytes[i] & 0xFF; // unsigned byte
}
if ((res.length == 1) && (res[0] == 0))
{
return EMPTYLIST;
}
return res;
}
/**
* codes ported from iconv lib in utf8.h utf8_codepointtomb
*/
@Override
public int[] toIdList(int codePoint)
{
int count;
if (codePoint < 0x80)
count = 1;
else if (codePoint < 0x800)
count = 2;
else if (codePoint < 0x10000)
count = 3;
else if (codePoint < 0x200000)
count = 4;
else if (codePoint < 0x4000000)
count = 5;
else if (codePoint <= 0x7fffffff)
count = 6;
else
return EMPTYLIST;
int[] r = new int[count];
switch (count)
{ /* note: code falls through cases! */
case 6:
r[5] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0x4000000;
case 5:
r[4] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0x200000;
case 4:
r[3] = (char) (0x80 | (codePoint & 0x3f)); | codePoint = codePoint >> 6;
codePoint |= 0x10000;
case 3:
r[2] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0x800;
case 2:
r[1] = (char) (0x80 | (codePoint & 0x3f));
codePoint = codePoint >> 6;
codePoint |= 0xc0;
case 1:
r[0] = (char) codePoint;
}
return r;
}
@Override
public String toString(int[] ids)
{
byte[] bytes = new byte[ids.length];
for (int i = 0; i < ids.length; i++)
{
bytes[i] = (byte) ids[i];
}
try
{
return new String(bytes, "UTF-8");
}
catch (UnsupportedEncodingException e)
{
return null;
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\Utf8CharacterMapping.java | 1 |
请完成以下Java代码 | public frameset addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public frameset addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public frameset removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
/**
The onload event occurs when the user agent finishes loading a window
or all frames within a frameset. This attribute may be used with body
and frameset elements.
@param The script
*/
public void setOnLoad(String script)
{ | addAttribute ( "onload", script );
}
/**
The onunload event occurs when the user agent removes a document from a
window or frame. This attribute may be used with body and frameset
elements.
@param The script
*/
public void setOnUnload(String script)
{
addAttribute ( "onunload", script );
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\frameset.java | 1 |
请完成以下Java代码 | public @Nullable List<AuthenticatorTransport> getTransports() {
return this.transports;
}
/**
* Creates a new instance.
* @return the {@link AuthenticatorAttestationResponseBuilder}
*/
public static AuthenticatorAttestationResponseBuilder builder() {
return new AuthenticatorAttestationResponseBuilder();
}
/**
* Builds {@link AuthenticatorAssertionResponse}.
*
* @author Rob Winch
* @since 6.4
*/
public static final class AuthenticatorAttestationResponseBuilder {
@SuppressWarnings("NullAway.Init")
private Bytes attestationObject;
private @Nullable List<AuthenticatorTransport> transports;
@SuppressWarnings("NullAway.Init")
private Bytes clientDataJSON;
private AuthenticatorAttestationResponseBuilder() {
}
/**
* Sets the {@link #getAttestationObject()} property.
* @param attestationObject the attestation object.
* @return the {@link AuthenticatorAttestationResponseBuilder}
*/
public AuthenticatorAttestationResponseBuilder attestationObject(Bytes attestationObject) {
this.attestationObject = attestationObject;
return this;
}
/**
* Sets the {@link #getTransports()} property.
* @param transports the transports
* @return the {@link AuthenticatorAttestationResponseBuilder}
*/
public AuthenticatorAttestationResponseBuilder transports(AuthenticatorTransport... transports) {
return transports(Arrays.asList(transports));
}
/**
* Sets the {@link #getTransports()} property.
* @param transports the transports
* @return the {@link AuthenticatorAttestationResponseBuilder}
*/
public AuthenticatorAttestationResponseBuilder transports(List<AuthenticatorTransport> transports) { | this.transports = transports;
return this;
}
/**
* Sets the {@link #getClientDataJSON()} property.
* @param clientDataJSON the client data JSON.
* @return the {@link AuthenticatorAttestationResponseBuilder}
*/
public AuthenticatorAttestationResponseBuilder clientDataJSON(Bytes clientDataJSON) {
this.clientDataJSON = clientDataJSON;
return this;
}
/**
* Builds a {@link AuthenticatorAssertionResponse}.
* @return the {@link AuthenticatorAttestationResponseBuilder}
*/
public AuthenticatorAttestationResponse build() {
return new AuthenticatorAttestationResponse(this.clientDataJSON, this.attestationObject, this.transports);
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\AuthenticatorAttestationResponse.java | 1 |
请完成以下Java代码 | public Set<String> getScope() {
return stringToSet(scopes);
}
/**
* 授权类型
*
* @return 结果
*/
@Override
public Set<String> getAuthorizedGrantTypes() {
return stringToSet(grantTypes);
}
@Override
public Set<String> getResourceIds() {
return stringToSet(resourceIds);
}
/**
* 获取回调地址
*
* @return redirectUrl
*/
@Override
public Set<String> getRegisteredRedirectUri() {
return stringToSet(redirectUrl);
}
/**
* 这里需要提一下
* 个人觉得这里应该是客户端所有的权限
* 但是已经有 scope 的存在可以很好的对客户端的权限进行认证了
* 那么在 oauth2 的四个角色中,这里就有可能是资源服务器的权限
* 但是一般资源服务器都有自己的权限管理机制,比如拿到用户信息后做 RBAC
* 所以在 spring security 的默认实现中直接给的是空的一个集合
* 这里我们也给他一个空的把
*
* @return GrantedAuthority
*/
@Override
public Collection<GrantedAuthority> getAuthorities() {
return Collections.emptyList();
}
/**
* 判断是否自动授权
*
* @param scope scope
* @return 结果
*/
@Override
public boolean isAutoApprove(String scope) {
if (autoApproveScopes == null || autoApproveScopes.isEmpty()) {
return false; | }
Set<String> authorizationSet = stringToSet(authorizations);
for (String auto : authorizationSet) {
if ("true".equalsIgnoreCase(auto) || scope.matches(auto)) {
return true;
}
}
return false;
}
/**
* additional information 是 spring security 的保留字段
* 暂时用不到,直接给个空的即可
*
* @return map
*/
@Override
public Map<String, Object> getAdditionalInformation() {
return Collections.emptyMap();
}
private Set<String> stringToSet(String s) {
return Arrays.stream(s.split(",")).collect(Collectors.toSet());
}
} | repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\entity\SysClientDetails.java | 1 |
请完成以下Java代码 | public void setPostal(PostalAddressType value) {
this.postal = value;
}
/**
* Gets the value of the telecom property.
*
* @return
* possible object is
* {@link TelecomAddressType }
*
*/
public TelecomAddressType getTelecom() {
return telecom;
}
/**
* Sets the value of the telecom property.
*
* @param value
* allowed object is
* {@link TelecomAddressType }
*
*/
public void setTelecom(TelecomAddressType value) {
this.telecom = value;
}
/**
* Gets the value of the online property.
*
* @return | * possible object is
* {@link OnlineAddressType }
*
*/
public OnlineAddressType getOnline() {
return online;
}
/**
* Sets the value of the online property.
*
* @param value
* allowed object is
* {@link OnlineAddressType }
*
*/
public void setOnline(OnlineAddressType value) {
this.online = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\CompanyType.java | 1 |
请完成以下Java代码 | public void save(final GridTab gridTab)
{
Services.get(ITrxManager.class).runInNewTrx(() -> save0(gridTab));
}
private void save0(final GridTab gridTab)
{
Check.assumeNotNull(gridTab, "gridTab not null");
for (final GridField gridField : gridTab.getFields())
{
save(gridField);
}
}
private void save(final GridField gridField)
{
final GridFieldVO gridFieldVO = gridField.getVO();
final AdFieldId adFieldId = gridFieldVO.getAD_Field_ID();
if (adFieldId == null) | {
return;
}
final I_AD_Field adField = InterfaceWrapperHelper.load(adFieldId, I_AD_Field.class);
if (adField == null)
{
return;
}
adField.setIsDisplayedGrid(gridFieldVO.isDisplayedGrid());
adField.setSeqNoGrid(gridFieldVO.getSeqNoGrid());
adField.setColumnDisplayLength(gridFieldVO.getLayoutConstraints().getColumnDisplayLength());
InterfaceWrapperHelper.save(adField);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\AWindowSaveStateModel.java | 1 |
请完成以下Java代码 | public byte[] serialize(String topic, Object data) {
if (data == null) {
return null;
}
Serializer<Object> delegate = findDelegate(data);
return delegate.serialize(topic, data);
}
@SuppressWarnings("NullAway") // Dataflow analysis limitation
@Override
public byte[] serialize(String topic, Headers headers, Object data) {
if (data == null) {
return null;
}
Serializer<Object> delegate = findDelegate(data);
return delegate.serialize(topic, headers, data);
}
protected <T> Serializer<T> findDelegate(T data) {
return findDelegate(data, this.delegates);
}
/**
* Determine the serializer for the data type.
* @param data the data.
* @param delegates the available delegates.
* @param <T> the data type
* @return the delegate.
* @throws SerializationException when there is no match. | * @since 2.8.3
*/
@SuppressWarnings("unchecked")
protected <T> Serializer<T> findDelegate(T data, Map<Class<?>, Serializer<?>> delegates) {
if (!this.assignable) {
Serializer<?> delegate = delegates.get(data.getClass());
if (delegate == null) {
throw new SerializationException("No matching delegate for type: " + data.getClass().getName()
+ "; supported types: " + delegates.keySet().stream()
.map(Class::getName)
.toList());
}
return (Serializer<T>) delegate;
}
else {
for (Entry<Class<?>, Serializer<?>> entry : delegates.entrySet()) {
if (entry.getKey().isAssignableFrom(data.getClass())) {
return (Serializer<T>) entry.getValue();
}
}
throw new SerializationException("No matching delegate for type: " + data.getClass().getName()
+ "; supported types: " + delegates.keySet().stream()
.map(Class::getName)
.toList());
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\DelegatingByTypeSerializer.java | 1 |
请完成以下Java代码 | private String getMessage(BindException cause) {
Throwable rootCause = getRootCause(cause.getCause());
ConversionFailedException conversionFailure = findCause(cause, ConversionFailedException.class);
if (conversionFailure != null) {
String message = "failed to convert " + conversionFailure.getSourceType() + " to "
+ conversionFailure.getTargetType();
if (rootCause != null) {
message += " (caused by " + getExceptionTypeAndMessage(rootCause) + ")";
}
return message;
}
if (rootCause != null && StringUtils.hasText(rootCause.getMessage())) {
return getExceptionTypeAndMessage(rootCause);
}
return getExceptionTypeAndMessage(cause);
}
private @Nullable Throwable getRootCause(@Nullable Throwable cause) {
Throwable rootCause = cause;
while (rootCause != null && rootCause.getCause() != null) {
rootCause = rootCause.getCause();
}
return rootCause;
}
private String getExceptionTypeAndMessage(Throwable ex) {
String message = ex.getMessage();
return ex.getClass().getName() + (StringUtils.hasText(message) ? ": " + message : "");
}
private FailureAnalysis getFailureAnalysis(String description, BindException cause,
@Nullable FailureAnalysis missingParametersAnalysis) {
StringBuilder action = new StringBuilder("Update your application's configuration");
Collection<String> validValues = findValidValues(cause);
if (!validValues.isEmpty()) {
action.append(String.format(". The following values are valid:%n"));
validValues.forEach((value) -> action.append(String.format("%n %s", value)));
} | if (missingParametersAnalysis != null) {
action.append(String.format("%n%n%s", missingParametersAnalysis.getAction()));
}
return new FailureAnalysis(description, action.toString(), cause);
}
private Collection<String> findValidValues(BindException ex) {
ConversionFailedException conversionFailure = findCause(ex, ConversionFailedException.class);
if (conversionFailure != null) {
Object[] enumConstants = conversionFailure.getTargetType().getType().getEnumConstants();
if (enumConstants != null) {
return Stream.of(enumConstants).map(Object::toString).collect(Collectors.toCollection(TreeSet::new));
}
}
return Collections.emptySet();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\diagnostics\analyzer\BindFailureAnalyzer.java | 1 |
请完成以下Java代码 | public final int getWindowNo()
{
return windowNo;
}
@Override
public final int getTabNo()
{
return tabNo;
}
@Override
public BPartnerId getBpartnerId()
{
return BPartnerId.ofRepoIdOrNull(getContextAsInt("C_BPartner_ID"));
}
@Override
public ProductId getProductId()
{
return ProductId.ofRepoIdOrNull(getContextAsInt("M_Product_ID"));
}
@Override
public boolean isSOTrx()
{
return SOTrx.toBoolean(getSoTrx());
}
@Override
public SOTrx getSoTrx()
{
final Boolean soTrx = Env.getSOTrxOrNull(ctx, windowNo);
return SOTrx.ofBoolean(soTrx);
} | @Override
public WarehouseId getWarehouseId()
{
return WarehouseId.ofRepoIdOrNull(getContextAsInt("M_Warehouse_ID"));
}
@Override
public int getM_Locator_ID()
{
return getContextAsInt("M_Locator_ID");
}
@Override
public DocTypeId getDocTypeId()
{
return DocTypeId.ofRepoIdOrNull(getContextAsInt("C_DocType_ID"));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\VPAttributeWindowContext.java | 1 |
请完成以下Java代码 | void patchRow(
@NonNull final PurchaseRowId idOfRowToPatch,
@NonNull final PurchaseRowChangeRequest request)
{
final PurchaseGroupRowEditor editorToUse = PurchaseRow::changeIncludedRow;
updateRow(idOfRowToPatch, request, editorToUse);
}
private void updateRow(
@NonNull final PurchaseRowId idOfRowToPatch,
@NonNull final PurchaseRowChangeRequest request,
@NonNull final PurchaseGroupRowEditor editor)
{
topLevelRowsById.compute(idOfRowToPatch.toGroupRowId(), (groupRowId, groupRow) -> {
if (groupRow == null)
{
throw new EntityNotFoundException("Row not found").appendParametersToMessage().setParameter("rowId", groupRowId);
}
final PurchaseRow newGroupRow = groupRow.copy();
if (idOfRowToPatch.isGroupRowId())
{
final PurchaseRowId includedRowId = null;
editor.edit(newGroupRow, includedRowId, request); | }
else
{
final PurchaseRowId includedRowId = idOfRowToPatch;
editor.edit(newGroupRow, includedRowId, request);
}
return newGroupRow;
});
}
@FunctionalInterface
private static interface PurchaseGroupRowEditor
{
void edit(final PurchaseRow editableGroupRow, final PurchaseRowId includedRowId, final PurchaseRowChangeRequest request);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowsCollection.java | 1 |
请完成以下Java代码 | public BigDecimal getConsumePerPoint() {
return consumePerPoint;
}
public void setConsumePerPoint(BigDecimal consumePerPoint) {
this.consumePerPoint = consumePerPoint;
}
public BigDecimal getLowOrderAmount() {
return lowOrderAmount;
}
public void setLowOrderAmount(BigDecimal lowOrderAmount) {
this.lowOrderAmount = lowOrderAmount;
}
public Integer getMaxPointPerOrder() {
return maxPointPerOrder;
}
public void setMaxPointPerOrder(Integer maxPointPerOrder) {
this.maxPointPerOrder = maxPointPerOrder;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
@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(", continueSignDay=").append(continueSignDay);
sb.append(", continueSignPoint=").append(continueSignPoint);
sb.append(", consumePerPoint=").append(consumePerPoint);
sb.append(", lowOrderAmount=").append(lowOrderAmount);
sb.append(", maxPointPerOrder=").append(maxPointPerOrder);
sb.append(", type=").append(type);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberRuleSetting.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<PPACK1> getPPACK1() {
if (ppack1 == null) {
ppack1 = new ArrayList<PPACK1>();
}
return this.ppack1;
}
/**
* Gets the value of the detail property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the detail property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDETAIL().add(newItem);
* </pre>
* | *
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DETAILXlief }
*
*
*/
public List<DETAILXlief> getDETAIL() {
if (detail == null) {
detail = new ArrayList<DETAILXlief>();
}
return this.detail;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\PACKINXlief.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private PartitionerConfigLine.LineBuilder newLine()
{
assertLineTableNamesUnique();
final PartitionerConfigLine.LineBuilder lineBuilder = new PartitionerConfigLine.LineBuilder(this);
lineBuilders.add(lineBuilder);
return lineBuilder;
}
/**
*
* @param tableName
* @return the already existing line builder for the given <code>tableName</code>, or a new one, if none existed yet.
*/
public LineBuilder line(final String tableName)
{
final Optional<LineBuilder> existingLineBuilder = lineBuilders
.stream()
.filter(b -> tableName.equals(b.getTableName()))
.findFirst();
if (existingLineBuilder.isPresent())
{
return existingLineBuilder.get();
}
setChanged(true);
return newLine().setTableName(tableName);
}
private void assertLineTableNamesUnique()
{
final List<LineBuilder> nonUniqueLines = lineBuilders.stream()
.collect(Collectors.groupingBy(r -> r.getTableName())) // group them by tableName; this returns a map
.entrySet().stream() // now stream the map's entries
.filter(e -> e.getValue().size() > 1) // now remove from the stream those that are OK
.flatMap(e -> e.getValue().stream()) // now get a stream with those that are not OK | .collect(Collectors.toList());
Check.errorUnless(nonUniqueLines.isEmpty(), "Found LineBuilders with duplicate tableNames: {}", nonUniqueLines);
}
public PartitionConfig build()
{
assertLineTableNamesUnique();
final PartitionConfig partitionerConfig = new PartitionConfig(name, changed);
partitionerConfig.setDLM_Partition_Config_ID(DLM_Partition_Config_ID);
// first build the lines
for (final PartitionerConfigLine.LineBuilder lineBuilder : lineBuilders)
{
final PartitionerConfigLine line = lineBuilder.buildLine(partitionerConfig);
partitionerConfig.lines.add(line);
}
for (final PartitionerConfigLine.LineBuilder lineBuilder : lineBuilders)
{
lineBuilder.buildRefs();
}
return partitionerConfig;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\config\PartitionConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class WebController {
@RequestMapping("/")
public String root() {
return "redirect:/index";
}
@RequestMapping("/index")
public String index(Model model) {
getDomain().ifPresent(d -> {
model.addAttribute("domain", d);
});
return "index";
}
@RequestMapping("/user/index")
public String userIndex(Model model) {
getDomain().ifPresent(d -> {
model.addAttribute("domain", d);
});
return "user/index";
} | @RequestMapping("/login")
public String login() {
return "login";
}
private Optional<String> getDomain() {
Authentication auth = SecurityContextHolder.getContext()
.getAuthentication();
String domain = null;
if (auth != null && !auth.getClass().equals(AnonymousAuthenticationToken.class)) {
User user = (User) auth.getPrincipal();
domain = user.getDomain();
}
return Optional.ofNullable(domain);
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-login-2\src\main\java\com\baeldung\loginextrafieldscustom\WebController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public abstract class Relationships {
private static Map<String, String> ROUTES;
public static void define(RestExpress server) {
ROUTES = server.getRouteUrlsByName();
HyperExpress.relationships()
.forCollectionOf(SampleUuidEntity.class)
.rel(RelTypes.SELF, href(Constants.Routes.SAMPLE_UUID_COLLECTION))
.withQuery("limit={limit}")
.withQuery("offset={offset}")
.rel(RelTypes.NEXT, href(Constants.Routes.SAMPLE_UUID_COLLECTION) + "?offset={nextOffset}")
.withQuery("limit={limit}")
.optional()
.rel(RelTypes.PREV, href(Constants.Routes.SAMPLE_UUID_COLLECTION) + "?offset={prevOffset}")
.withQuery("limit={limit}")
.optional()
.forClass(SampleUuidEntity.class)
.rel(RelTypes.SELF, href(Constants.Routes.SINGLE_UUID_SAMPLE))
.rel(RelTypes.UP, href(Constants.Routes.SAMPLE_UUID_COLLECTION))
.forCollectionOf(SampleOidEntity.class)
.rel(RelTypes.SELF, href(Constants.Routes.SAMPLE_OID_COLLECTION))
.withQuery("limit={limit}")
.withQuery("offset={offset}")
.rel(RelTypes.NEXT, href(Constants.Routes.SAMPLE_OID_COLLECTION) + "?offset={nextOffset}")
.withQuery("limit={limit}") | .optional()
.rel(RelTypes.PREV, href(Constants.Routes.SAMPLE_OID_COLLECTION) + "?offset={prevOffset}")
.withQuery("limit={limit}")
.optional()
.forClass(SampleOidEntity.class)
.rel(RelTypes.SELF, href(Constants.Routes.SINGLE_OID_SAMPLE))
.rel(RelTypes.UP, href(Constants.Routes.SAMPLE_OID_COLLECTION));
}
private static String href(String name) {
String href = ROUTES.get(name);
if (href == null) throw new ConfigurationException("Route name not found: " + name);
return href;
}
} | repos\tutorials-master\microservices-modules\rest-express\src\main\java\com\baeldung\restexpress\Relationships.java | 2 |
请完成以下Java代码 | public void down(Duration timeout) {
down(timeout, Collections.emptyList());
}
@Override
public void down(Duration timeout, List<String> arguments) {
this.cli.run(new DockerCliCommand.ComposeDown(timeout, arguments));
}
@Override
public void start(LogLevel logLevel) {
start(logLevel, Collections.emptyList());
}
@Override
public void start(LogLevel logLevel, List<String> arguments) {
this.cli.run(new DockerCliCommand.ComposeStart(logLevel, arguments));
}
@Override
public void stop(Duration timeout) {
stop(timeout, Collections.emptyList());
}
@Override
public void stop(Duration timeout, List<String> arguments) {
this.cli.run(new DockerCliCommand.ComposeStop(timeout, arguments));
}
@Override
public boolean hasDefinedServices() {
return !this.cli.run(new DockerCliCommand.ComposeConfig()).services().isEmpty();
}
@Override
public List<RunningService> getRunningServices() {
List<DockerCliComposePsResponse> runningPsResponses = runComposePs().stream().filter(this::isRunning).toList();
if (runningPsResponses.isEmpty()) {
return Collections.emptyList();
}
DockerComposeFile dockerComposeFile = this.cli.getDockerComposeFile();
List<RunningService> result = new ArrayList<>();
Map<String, DockerCliInspectResponse> inspected = inspect(runningPsResponses);
for (DockerCliComposePsResponse psResponse : runningPsResponses) {
DockerCliInspectResponse inspectResponse = inspectContainer(psResponse.id(), inspected);
Assert.state(inspectResponse != null, () -> "Failed to inspect container '%s'".formatted(psResponse.id())); | result.add(new DefaultRunningService(this.hostname, dockerComposeFile, psResponse, inspectResponse));
}
return Collections.unmodifiableList(result);
}
private Map<String, DockerCliInspectResponse> inspect(List<DockerCliComposePsResponse> runningPsResponses) {
List<String> ids = runningPsResponses.stream().map(DockerCliComposePsResponse::id).toList();
List<DockerCliInspectResponse> inspectResponses = this.cli.run(new DockerCliCommand.Inspect(ids));
return inspectResponses.stream().collect(Collectors.toMap(DockerCliInspectResponse::id, Function.identity()));
}
private @Nullable DockerCliInspectResponse inspectContainer(String id,
Map<String, DockerCliInspectResponse> inspected) {
DockerCliInspectResponse inspect = inspected.get(id);
if (inspect != null) {
return inspect;
}
// Docker Compose v2.23.0 returns truncated ids, so we have to do a prefix match
for (Entry<String, DockerCliInspectResponse> entry : inspected.entrySet()) {
if (entry.getKey().startsWith(id)) {
return entry.getValue();
}
}
return null;
}
private List<DockerCliComposePsResponse> runComposePs() {
return this.cli.run(new DockerCliCommand.ComposePs());
}
private boolean isRunning(DockerCliComposePsResponse psResponse) {
return !"exited".equals(psResponse.state());
}
} | repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\DefaultDockerCompose.java | 1 |
请完成以下Java代码 | public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
public void setProcessDefinitionVersionTag(String processDefinitionVersionTag) {
this.processDefinitionVersionTag = processDefinitionVersionTag;
}
public String getProcessDefinitionVersionTag() {
return processDefinitionVersionTag;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public void setTenantIdSet(boolean isTenantIdSet) {
this.isTenantIdSet = isTenantIdSet;
}
public String[] getTenantIds() {
return tenantIds;
}
public void setTenantIds(String[] tenantIds) {
isTenantIdSet = true;
this.tenantIds = tenantIds;
}
public List<QueryVariableValue> getFilterVariables() {
return filterVariables;
}
public void setFilterVariables(Map<String, Object> filterVariables) {
QueryVariableValue variableValue;
for (Map.Entry<String, Object> filter : filterVariables.entrySet()) {
variableValue = new QueryVariableValue(filter.getKey(), filter.getValue(), null, false);
this.filterVariables.add(variableValue);
}
}
public void addFilterVariable(String name, Object value) {
QueryVariableValue variableValue = new QueryVariableValue(name, value, QueryOperator.EQUALS, true);
this.filterVariables.add(variableValue);
}
public Long getLockDuration() {
return lockDuration;
}
public String getTopicName() {
return topicName;
}
public boolean isDeserializeVariables() {
return deserializeVariables; | }
public void setDeserializeVariables(boolean deserializeVariables) {
this.deserializeVariables = deserializeVariables;
}
public void ensureVariablesInitialized() {
if (!filterVariables.isEmpty()) {
ProcessEngineConfigurationImpl processEngineConfiguration = Context.getProcessEngineConfiguration();
VariableSerializers variableSerializers = processEngineConfiguration.getVariableSerializers();
String dbType = processEngineConfiguration.getDatabaseType();
for(QueryVariableValue queryVariableValue : filterVariables) {
queryVariableValue.initialize(variableSerializers, dbType);
}
}
}
public boolean isLocalVariables() {
return localVariables;
}
public void setLocalVariables(boolean localVariables) {
this.localVariables = localVariables;
}
public boolean isIncludeExtensionProperties() {
return includeExtensionProperties;
}
public void setIncludeExtensionProperties(boolean includeExtensionProperties) {
this.includeExtensionProperties = includeExtensionProperties;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\externaltask\TopicFetchInstruction.java | 1 |
请完成以下Java代码 | public class IllegalTrxRunStateException extends TrxException
{
/**
*
*/
private static final long serialVersionUID = 4659574948858028974L;
private ITrxRunConfig trxRunConfig;
private String trxName;
private boolean trxNameSet;
/**
* @param message reason why is not valid
*/
// NOTE: keep this method here no matter what because we want to use this exception in Check.assume methods.
public IllegalTrxRunStateException(final String message)
{
super(message);
}
@Override
protected ITranslatableString buildMessage()
{
final TranslatableStringBuilder message = TranslatableStrings.builder();
final ITranslatableString originalMessage = super.buildMessage();
if (TranslatableStrings.isBlank(originalMessage))
{
message.append("Illegal transaction run state");
}
else | {
message.append(originalMessage);
}
if (trxRunConfig != null)
{
message.append("\nTrxRunConfig: ").appendObj(trxRunConfig);
}
if (trxNameSet)
{
message.append("\nTrxName: ").append(trxName);
}
return message.build();
}
public IllegalTrxRunStateException setTrxRunConfig(final ITrxRunConfig trxRunConfig)
{
this.trxRunConfig = trxRunConfig;
resetMessageBuilt();
return this;
}
public IllegalTrxRunStateException setTrxName(final String trxName)
{
this.trxName = trxName;
this.trxNameSet = true;
resetMessageBuilt();
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\exceptions\IllegalTrxRunStateException.java | 1 |
请完成以下Java代码 | public Class<? extends EventDeploymentEntity> getManagedEntityClass() {
return EventDeploymentEntityImpl.class;
}
@Override
public EventDeploymentEntity create() {
return new EventDeploymentEntityImpl();
}
@Override
public long findDeploymentCountByQueryCriteria(EventDeploymentQueryImpl deploymentQuery) {
return (Long) getDbSqlSession().selectOne("selectEventDeploymentCountByQueryCriteria", deploymentQuery);
}
@Override
@SuppressWarnings("unchecked")
public List<EventDeployment> findDeploymentsByQueryCriteria(EventDeploymentQueryImpl deploymentQuery) {
return getDbSqlSession().selectList("selectEventDeploymentsByQueryCriteria", deploymentQuery);
}
@Override | public List<String> getDeploymentResourceNames(String deploymentId) {
return getDbSqlSession().getSqlSession().selectList("selectEventResourceNamesByDeploymentId", deploymentId);
}
@Override
@SuppressWarnings("unchecked")
public List<EventDeployment> findDeploymentsByNativeQuery(Map<String, Object> parameterMap) {
return getDbSqlSession().selectListWithRawParameter("selectEventDeploymentByNativeQuery", parameterMap);
}
@Override
public long findDeploymentCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectEventDeploymentCountByNativeQuery", parameterMap);
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\data\impl\MybatisEventDeploymentDataManager.java | 1 |
请完成以下Java代码 | public void setLogoWeb(org.compiere.model.I_AD_Image LogoWeb)
{
set_ValueFromPO(COLUMNNAME_LogoWeb_ID, org.compiere.model.I_AD_Image.class, LogoWeb);
}
/** Set Logo Web.
@param LogoWeb_ID Logo Web */
@Override
public void setLogoWeb_ID (int LogoWeb_ID)
{
if (LogoWeb_ID < 1)
set_Value (COLUMNNAME_LogoWeb_ID, null);
else
set_Value (COLUMNNAME_LogoWeb_ID, Integer.valueOf(LogoWeb_ID));
}
/** Get Logo Web.
@return Logo Web */
@Override
public int getLogoWeb_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LogoWeb_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_Product getM_ProductFreight() throws RuntimeException
{ | return get_ValueAsPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class);
}
@Override
public void setM_ProductFreight(org.compiere.model.I_M_Product M_ProductFreight)
{
set_ValueFromPO(COLUMNNAME_M_ProductFreight_ID, org.compiere.model.I_M_Product.class, M_ProductFreight);
}
/** Set Produkt für Fracht.
@param M_ProductFreight_ID Produkt für Fracht */
@Override
public void setM_ProductFreight_ID (int M_ProductFreight_ID)
{
if (M_ProductFreight_ID < 1)
set_Value (COLUMNNAME_M_ProductFreight_ID, null);
else
set_Value (COLUMNNAME_M_ProductFreight_ID, Integer.valueOf(M_ProductFreight_ID));
}
/** Get Produkt für Fracht.
@return Produkt für Fracht */
@Override
public int getM_ProductFreight_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductFreight_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_AD_ClientInfo.java | 1 |
请完成以下Java代码 | public void setM_Attribute_ID (int M_Attribute_ID)
{
if (M_Attribute_ID < 1)
set_Value (COLUMNNAME_M_Attribute_ID, null);
else
set_Value (COLUMNNAME_M_Attribute_ID, Integer.valueOf(M_Attribute_ID));
}
/** Get Merkmal.
@return Produkt-Merkmal
*/
@Override
public int getM_Attribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set MKTG_ContactPerson_Attribute.
@param MKTG_ContactPerson_Attribute_ID MKTG_ContactPerson_Attribute */
@Override
public void setMKTG_ContactPerson_Attribute_ID (int MKTG_ContactPerson_Attribute_ID)
{
if (MKTG_ContactPerson_Attribute_ID < 1)
set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_Attribute_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_Attribute_ID, Integer.valueOf(MKTG_ContactPerson_Attribute_ID));
}
/** Get MKTG_ContactPerson_Attribute.
@return MKTG_ContactPerson_Attribute */
@Override
public int getMKTG_ContactPerson_Attribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_Attribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.marketing.base.model.I_MKTG_ContactPerson getMKTG_ContactPerson() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class);
}
@Override
public void setMKTG_ContactPerson(de.metas.marketing.base.model.I_MKTG_ContactPerson MKTG_ContactPerson)
{ | set_ValueFromPO(COLUMNNAME_MKTG_ContactPerson_ID, de.metas.marketing.base.model.I_MKTG_ContactPerson.class, MKTG_ContactPerson);
}
/** Set MKTG_ContactPerson.
@param MKTG_ContactPerson_ID MKTG_ContactPerson */
@Override
public void setMKTG_ContactPerson_ID (int MKTG_ContactPerson_ID)
{
if (MKTG_ContactPerson_ID < 1)
set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MKTG_ContactPerson_ID, Integer.valueOf(MKTG_ContactPerson_ID));
}
/** Get MKTG_ContactPerson.
@return MKTG_ContactPerson */
@Override
public int getMKTG_ContactPerson_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_ContactPerson_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_ContactPerson_Attribute.java | 1 |
请完成以下Java代码 | public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsInstanceAttribute (final boolean IsInstanceAttribute)
{
set_Value (COLUMNNAME_IsInstanceAttribute, IsInstanceAttribute);
}
@Override
public boolean isInstanceAttribute()
{
return get_ValueAsBoolean(COLUMNNAME_IsInstanceAttribute);
}
/**
* MandatoryType AD_Reference_ID=324
* Reference name: M_AttributeSet MandatoryType
*/
public static final int MANDATORYTYPE_AD_Reference_ID=324;
/** Not Mandatary = N */
public static final String MANDATORYTYPE_NotMandatary = "N";
/** Always Mandatory = Y */
public static final String MANDATORYTYPE_AlwaysMandatory = "Y";
/** WhenShipping = S */
public static final String MANDATORYTYPE_WhenShipping = "S";
@Override
public void setMandatoryType (final java.lang.String MandatoryType)
{ | set_Value (COLUMNNAME_MandatoryType, MandatoryType);
}
@Override
public java.lang.String getMandatoryType()
{
return get_ValueAsString(COLUMNNAME_MandatoryType);
}
@Override
public void setM_AttributeSet_ID (final int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, M_AttributeSet_ID);
}
@Override
public int getM_AttributeSet_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSet_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_M_AttributeSet.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Person {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@Column(name = "inserted_at_timestamp")
private OffsetDateTime insertedAt;
@Column(name = "updated_at_timestamp")
@TimeZoneStorage(TimeZoneStorageType.COLUMN)
@TimeZoneColumn(name="last_updated_offset")
private OffsetDateTime lastUpdatedAt;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id; | }
public OffsetDateTime getInsertedAt() {
return insertedAt;
}
public void setInsertedAt(OffsetDateTime insertedAt) {
this.insertedAt = insertedAt;
}
public OffsetDateTime getLastUpdatedAt() {
return lastUpdatedAt;
}
public void setLastUpdatedAt(OffsetDateTime lastUpdatedAt) {
this.lastUpdatedAt = lastUpdatedAt;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa-3\src\main\java\com\baeldung\hibernate\timezonecolumn\model\Person.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void configure() throws Exception
{
//@formatter:off
errorHandler(defaultErrorHandler());
onException(Exception.class)
.to(direct(MF_ERROR_ROUTE_ID));
from(direct(SEND_TO_FILE_ROUTE_ID))
.routeId(SEND_TO_FILE_ROUTE_ID)
.log("Route invoked!")
.log(LoggingLevel.DEBUG, "exchange body: ${body}")
.doTry()
.process(this::prepareForFileEndpoint)
.to(file("").fileName("${in.header.LeichUndMehl_Path}/${in.header.LeichUndMehl_Filename}"))
.endDoTry()
.doCatch(RuntimeException.class)
.to(direct(MF_ERROR_ROUTE_ID));
//@formatter:on
}
private void prepareForFileEndpoint(@NonNull final Exchange exchange)
{
final ExportPPOrderRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_PP_ORDER_CONTEXT, ExportPPOrderRouteContext.class);
final DispatchMessageRequest dispatchMessageRequest = exchange.getIn().getBody(DispatchMessageRequest.class);
exchange.getIn().setHeader("LeichUndMehl_Path", dispatchMessageRequest.getDestinationDetails().getPluFileServerFolderNotBlank());
exchange.getIn().setHeader("LeichUndMehl_Filename", extractFilename(context.getPLUTemplateFilename())); | exchange.getIn().setBody(dispatchMessageRequest.getPayload());
}
@VisibleForTesting
static String extractFilename(@NonNull final String pluTemplateFilename)
{
final int lastIndexOfDot = pluTemplateFilename.lastIndexOf('.');
if (lastIndexOfDot == -1)
{
return pluTemplateFilename + "_" + SystemTime.millis();
}
return pluTemplateFilename.substring(0, lastIndexOfDot) + "_" + SystemTime.millis() + pluTemplateFilename.substring(lastIndexOfDot);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\file\SendToFileRouteBuilder.java | 2 |
请完成以下Java代码 | public MInvoiceBatchLine[] getLines (boolean reload)
{
if (m_lines != null && !reload) {
set_TrxName(m_lines, get_TrxName());
return m_lines;
}
String sql = "SELECT * FROM C_InvoiceBatchLine WHERE C_InvoiceBatch_ID=? ORDER BY Line";
ArrayList<MInvoiceBatchLine> list = new ArrayList<MInvoiceBatchLine>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getC_InvoiceBatch_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
{
list.add (new MInvoiceBatchLine (getCtx(), rs, get_TrxName()));
}
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
} | //
m_lines = new MInvoiceBatchLine[list.size ()];
list.toArray (m_lines);
return m_lines;
} // getLines
/**
* Set Processed
* @param processed processed
*/
public void setProcessed (boolean processed)
{
super.setProcessed (processed);
if (get_ID() == 0)
return;
String set = "SET Processed='"
+ (processed ? "Y" : "N")
+ "' WHERE C_InvoiceBatch_ID=" + getC_InvoiceBatch_ID();
int noLine = DB.executeUpdateAndSaveErrorOnFail("UPDATE C_InvoiceBatchLine " + set, get_TrxName());
m_lines = null;
log.debug(processed + " - Lines=" + noLine);
} // setProcessed
} // MInvoiceBatch | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MInvoiceBatch.java | 1 |
请完成以下Java代码 | public E buildEngine() {
init();
initPostEngineBuildConsumer();
E engine = createEngine();
if (runPostEngineBuildConsumer) {
postEngineBuildConsumer.accept(engine);
}
return engine;
}
protected abstract E createEngine();
protected abstract void init();
protected void initPostEngineBuildConsumer() {
if (this.postEngineBuildConsumer == null) {
this.postEngineBuildConsumer = createPostEngineBuildConsumer();
}
} | protected abstract Consumer<E> createPostEngineBuildConsumer();
public boolean isRunPostEngineBuildConsumer() {
return runPostEngineBuildConsumer;
}
public void setRunPostEngineBuildConsumer(boolean runPostEngineBuildConsumer) {
this.runPostEngineBuildConsumer = runPostEngineBuildConsumer;
}
public Consumer<E> getPostEngineBuildConsumer() {
return postEngineBuildConsumer;
}
public void setPostEngineBuildConsumer(Consumer<E> postEngineBuildConsumer) {
this.postEngineBuildConsumer = postEngineBuildConsumer;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\AbstractBuildableEngineConfiguration.java | 1 |
请完成以下Java代码 | public int getNotificationsUnreadCount()
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
return userNotificationsService.getNotificationsUnreadCount(adUserId);
}
@PutMapping("/{notificationId}/read")
public void markAsRead(@PathVariable("notificationId") final String notificationId)
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
userNotificationsService.markNotificationAsRead(adUserId, notificationId);
}
@PutMapping("/all/read")
public void markAllAsRead()
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
userNotificationsService.markAllNotificationsAsRead(adUserId);
}
@DeleteMapping("/{notificationId}")
public void deleteById(@PathVariable("notificationId") final String notificationId)
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
userNotificationsService.deleteNotification(adUserId, notificationId);
} | @DeleteMapping
public void deleteByIds(@RequestParam(name = "ids") final String notificationIdsListStr)
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
final List<String> notificationIds = Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.splitToList(notificationIdsListStr);
if (notificationIds.isEmpty())
{
throw new AdempiereException("No IDs provided");
}
notificationIds.forEach(notificationId -> userNotificationsService.deleteNotification(adUserId, notificationId));
}
@DeleteMapping("/all")
public void deleteAll()
{
userSession.assertLoggedIn();
final UserId adUserId = userSession.getLoggedUserId();
userNotificationsService.deleteAllNotification(adUserId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\NotificationRestController.java | 1 |
请完成以下Java代码 | public class X_T_Query_Selection extends org.compiere.model.PO implements I_T_Query_Selection, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = -518361247L;
/** Standard Constructor */
public X_T_Query_Selection (Properties ctx, int T_Query_Selection_ID, String trxName)
{
super (ctx, T_Query_Selection_ID, trxName);
/** if (T_Query_Selection_ID == 0)
{
setLine (0);
setRecord_ID (0);
setUUID (null);
} */
}
/** Load Constructor */
public X_T_Query_Selection (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Zeile Nr..
@param Line
Einzelne Zeile in dem Dokument
*/
@Override
public void setLine (int Line)
{
set_ValueNoCheck (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();
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); | }
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set UUID.
@param UUID UUID */
@Override
public void setUUID (java.lang.String UUID)
{
set_ValueNoCheck (COLUMNNAME_UUID, UUID);
}
/** Get UUID.
@return UUID */
@Override
public java.lang.String getUUID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UUID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dao\selection\model\X_T_Query_Selection.java | 1 |
请完成以下Java代码 | private IAllocationSource createAllocationSource(@NonNull final I_M_InOutLine returnLine)
{
final ProductId productId = ProductId.ofRepoId(returnLine.getM_Product_ID());
final I_C_UOM uom = uomDao.getById(returnLine.getC_UOM_ID());
final BigDecimal qty = returnLine.getQtyEntered();
final PlainProductStorage productStorage = new PlainProductStorage(productId, uom, qty);
return new GenericAllocationSourceDestination(productStorage, returnLine);
}
@Nullable
private AttributeSetInstanceId createAttributeSetInstance(@NonNull final CustomerReturnLineCandidate customerReturnLineCandidate)
{
final List<CreateAttributeInstanceReq> attributes = customerReturnLineCandidate.getCreateAttributeInstanceReqs();
if (attributes == null || attributes.isEmpty())
{
return null;
}
final AddAttributesRequest addAttributesRequest = AddAttributesRequest.builder()
.productId(customerReturnLineCandidate.getProductId())
.existingAttributeSetIdOrNone(AttributeSetInstanceId.NONE)
.attributeInstanceBasicInfos(attributes)
.build();
return attributeSetInstanceBL.addAttributes(addAttributesRequest);
}
private WarehouseId getWarehouseIdForReceivingReturnedGoods(@NonNull final ReturnedGoodsWarehouseType warehouseType)
{
final WarehouseId targetWarehouseId;
switch (warehouseType)
{
case QUARANTINE:
targetWarehouseId = warehousesRepo.retrieveQuarantineWarehouseId();
break;
case QUALITY_ISSUE:
targetWarehouseId = huWarehouseDAO.retrieveFirstQualityReturnWarehouseId();
break;
default:
throw new AdempiereException("The given ReturnedGoodsWarehouseType is not supported!")
.appendParametersToMessage()
.setParameter("ReturnedGoodsWarehouseType", warehouseType);
}
return targetWarehouseId;
}
@Value
@Builder
private static class CustomerReturnLineGroupingKey
{
@NonNull | OrgId orgId;
@NonNull
BPartnerLocationId bPartnerLocationId;
@NonNull
ReturnedGoodsWarehouseType warehouseType;
@Nullable
OrderId orderId;
@Nullable
LocalDate movementDate;
@Nullable
ZonedDateTime dateReceived;
@Nullable
String externalId;
@Nullable
String externalResourceURL;
public static CustomerReturnLineGroupingKey of(@NonNull final CustomerReturnLineCandidate returnLineCandidate)
{
return CustomerReturnLineGroupingKey.builder()
.orgId(returnLineCandidate.getOrgId())
.bPartnerLocationId(returnLineCandidate.getBPartnerLocationId())
.orderId(returnLineCandidate.getOrderId())
.movementDate(returnLineCandidate.getMovementDate())
.dateReceived(returnLineCandidate.getDateReceived())
.externalId(returnLineCandidate.getExternalId())
.externalResourceURL(returnLineCandidate.getExternalResourceURL())
.warehouseType(returnLineCandidate.getReturnedGoodsWarehouseType())
.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\CustomerReturnsWithoutHUsProducer.java | 1 |
请完成以下Java代码 | public class DatabaseSetupServlet extends HttpServlet {
@Resource(lookup = "java:comp/env/jdbc/securityDS")
private DataSource dataSource;
@Inject
private Pbkdf2PasswordHash passwordHash;
@Override
public void init() throws ServletException {
super.init();
initdb();
}
private void initdb() {
executeUpdate(dataSource, "DROP TABLE IF EXISTS USERS");
executeUpdate(dataSource, "DROP TABLE IF EXISTS GROUPS");
executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS USERS(username VARCHAR(64) PRIMARY KEY, password VARCHAR(255))");
executeUpdate(dataSource, "CREATE TABLE IF NOT EXISTS GROUPS(username VARCHAR(64), GROUPNAME VARCHAR(64))"); | executeUpdate(dataSource, "INSERT INTO USERS VALUES('admin', '" + passwordHash.generate("passadmin".toCharArray()) + "')");
executeUpdate(dataSource, "INSERT INTO USERS VALUES('user', '" + passwordHash.generate("passuser".toCharArray()) + "')");
executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'admin_role')");
executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('admin', 'user_role')");
executeUpdate(dataSource, "INSERT INTO GROUPS VALUES('user', 'user_role')");
}
private void executeUpdate(DataSource dataSource, String query) {
try (Connection connection = dataSource.getConnection()) {
try (PreparedStatement statement = connection.prepareStatement(query)) {
statement.executeUpdate();
}
} catch (SQLException e) {
throw new IllegalStateException(e);
}
}
} | repos\tutorials-master\security-modules\java-ee-8-security-api\app-auth-basic-store-db\src\main\java\com\baeldung\javaee\security\DatabaseSetupServlet.java | 1 |
请完成以下Java代码 | public void addEventLoggerListener(EventLoggerListener listener) {
if (listeners == null) {
listeners = new ArrayList<EventLoggerListener>(1);
}
listeners.add(listener);
}
/**
* Subclasses that want something else than the database flusher should override this method
*/
protected EventFlusher createEventFlusher() {
return null;
}
public Clock getClock() {
return clock;
}
public void setClock(Clock clock) {
this.clock = clock; | }
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public List<EventLoggerListener> getListeners() {
return listeners;
}
public void setListeners(List<EventLoggerListener> listeners) {
this.listeners = listeners;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\event\logger\EventLogger.java | 1 |
请完成以下Java代码 | final class ProductImportContext
{
@Getter
private final ProductsCache productsCache;
@Getter
private final boolean insertOnly;
@Getter
@Setter
private I_I_Product currentImportRecord;
@Builder
private ProductImportContext(
@NonNull final ProductsCache productsCache,
final boolean insertOnly)
{
this.productsCache = productsCache;
this.insertOnly = insertOnly;
}
public boolean isSameProduct(final I_I_Product importRecord)
{
final I_I_Product currentImportRecord = getCurrentImportRecord();
return currentImportRecord != null
&& Objects.equals(importRecord.getValue(), currentImportRecord.getValue());
}
public boolean isCurrentProductIdSet()
{
return getCurrentProductIdOrNull() != null;
}
public Product getCurrentProduct()
{ | final ProductId productId = getCurrentProductIdOrNull();
return getProductsCache().getProductById(productId);
}
public ProductId getCurrentProductIdOrNull()
{
final I_I_Product currentImportRecord = getCurrentImportRecord();
return currentImportRecord != null
? ProductId.ofRepoIdOrNull(currentImportRecord.getM_Product_ID())
: null;
}
public void setCurrentProductId(@NonNull final ProductId productId)
{
final I_I_Product currentImportRecord = getCurrentImportRecord();
Check.assumeNotNull(currentImportRecord, "Parameter currentImportRecord is not null");
currentImportRecord.setM_Product_ID(productId.getRepoId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impexp\ProductImportContext.java | 1 |
请完成以下Java代码 | public int getC_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_ID);
}
@Override
public void setC_BPartner_Location_ID (final int C_BPartner_Location_ID)
{
if (C_BPartner_Location_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_Location_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_Location_ID, C_BPartner_Location_ID);
}
@Override
public int getC_BPartner_Location_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID);
}
@Override
public void setCity (final @Nullable java.lang.String City)
{
set_Value (COLUMNNAME_City, City);
}
@Override
public java.lang.String getCity()
{
return get_ValueAsString(COLUMNNAME_City);
}
@Override
public void setES_DocumentId (final java.lang.String ES_DocumentId)
{
set_ValueNoCheck (COLUMNNAME_ES_DocumentId, ES_DocumentId);
}
@Override
public java.lang.String getES_DocumentId()
{
return get_ValueAsString(COLUMNNAME_ES_DocumentId);
}
@Override
public void setFirstname (final @Nullable java.lang.String Firstname)
{
set_Value (COLUMNNAME_Firstname, Firstname);
}
@Override
public java.lang.String getFirstname()
{
return get_ValueAsString(COLUMNNAME_Firstname);
}
@Override
public void setIsCompany (final boolean IsCompany)
{
set_ValueNoCheck (COLUMNNAME_IsCompany, IsCompany);
}
@Override
public boolean isCompany()
{
return get_ValueAsBoolean(COLUMNNAME_IsCompany);
}
@Override
public void setLastname (final @Nullable java.lang.String Lastname) | {
set_Value (COLUMNNAME_Lastname, Lastname);
}
@Override
public java.lang.String getLastname()
{
return get_ValueAsString(COLUMNNAME_Lastname);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Adv_Search.java | 1 |
请完成以下Java代码 | public class MigratingExternalTaskInstance implements MigratingInstance {
public static final MigrationLogger MIGRATION_LOGGER = ProcessEngineLogger.MIGRATION_LOGGER;
protected ExternalTaskEntity externalTask;
protected MigratingActivityInstance migratingActivityInstance;
protected List<MigratingInstance> dependentInstances = new ArrayList<MigratingInstance>();
public MigratingExternalTaskInstance(ExternalTaskEntity externalTask, MigratingActivityInstance migratingActivityInstance) {
this.externalTask = externalTask;
this.migratingActivityInstance = migratingActivityInstance;
}
@Override
public void migrateDependentEntities() {
for (MigratingInstance migratingDependentInstance : dependentInstances) {
migratingDependentInstance.migrateState();
}
}
@Override
public boolean isDetached() {
return externalTask.getExecutionId() == null;
}
@Override
public void detachState() {
externalTask.getExecution().removeExternalTask(externalTask);
externalTask.setExecution(null);
}
@Override
public void attachState(MigratingScopeInstance owningInstance) {
ExecutionEntity representativeExecution = owningInstance.resolveRepresentativeExecution();
representativeExecution.addExternalTask(externalTask);
externalTask.setExecution(representativeExecution); | }
@Override
public void attachState(MigratingTransitionInstance targetTransitionInstance) {
throw MIGRATION_LOGGER.cannotAttachToTransitionInstance(this);
}
@Override
public void migrateState() {
ScopeImpl targetActivity = migratingActivityInstance.getTargetScope();
ProcessDefinition targetProcessDefinition = (ProcessDefinition) targetActivity.getProcessDefinition();
externalTask.setActivityId(targetActivity.getId());
externalTask.setProcessDefinitionId(targetProcessDefinition.getId());
externalTask.setProcessDefinitionKey(targetProcessDefinition.getKey());
}
public String getId() {
return externalTask.getId();
}
public ScopeImpl getTargetScope() {
return migratingActivityInstance.getTargetScope();
}
public void addMigratingDependentInstance(MigratingInstance migratingInstance) {
dependentInstances.add(migratingInstance);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingExternalTaskInstance.java | 1 |
请完成以下Java代码 | public void setPackDescription (java.lang.String PackDescription)
{
set_Value (COLUMNNAME_PackDescription, PackDescription);
}
/** Get Packbeschreibung.
@return Packbeschreibung */
@Override
public java.lang.String getPackDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_PackDescription);
}
/** Set Lieferprodukt.
@param PMM_Product_ID Lieferprodukt */
@Override
public void setPMM_Product_ID (int PMM_Product_ID)
{
if (PMM_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_PMM_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PMM_Product_ID, Integer.valueOf(PMM_Product_ID));
}
/** Get Lieferprodukt.
@return Lieferprodukt */
@Override
public int getPMM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PMM_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Produktname.
@param ProductName
Name des Produktes
*/
@Override
public void setProductName (java.lang.String ProductName)
{
set_Value (COLUMNNAME_ProductName, ProductName);
}
/** Get Produktname.
@return Name des Produktes
*/
@Override
public java.lang.String getProductName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductName);
}
/** Set Produktschlüssel.
@param ProductValue
Schlüssel des Produktes
*/
@Override
public void setProductValue (java.lang.String ProductValue)
{
throw new IllegalArgumentException ("ProductValue is virtual column"); }
/** Get Produktschlüssel.
@return Schlüssel des Produktes
*/
@Override
public java.lang.String getProductValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductValue);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); | }
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set 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);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_Product.java | 1 |
请完成以下Java代码 | public Object getSummary() {
return summary;
}
public void setSummary(Object summary) {
this.summary = summary;
}
public void setTotal(int total) {
this.total = total;
}
public void setPage(int page) {
this.page = page;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public void setPageData(List pageData) {
this.pageData = pageData;
}
public long getTotal() { | return total;
}
public int getPage() {
return page;
}
public int getPageSize() {
return pageSize;
}
public List getPageData() {
return pageData;
}
} | repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\entity\PageListVO.java | 1 |
请完成以下Java代码 | public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Kommentar/Hilfe.
@param Help
Comment or Hint
*/
@Override
public void setHelp (java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Kommentar/Hilfe.
@return Comment or Hint
*/
@Override
public java.lang.String getHelp ()
{
return (java.lang.String)get_Value(COLUMNNAME_Help);
}
/** Set Order By Value.
@param IsOrderByValue
Order list using the value column instead of the name column
*/
@Override
public void setIsOrderByValue (boolean IsOrderByValue)
{
set_Value (COLUMNNAME_IsOrderByValue, Boolean.valueOf(IsOrderByValue));
}
/** Get Order By Value.
@return Order list using the value column instead of the name column
*/
@Override
public boolean isOrderByValue ()
{
Object oo = get_Value(COLUMNNAME_IsOrderByValue);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name); | }
/**
* ValidationType AD_Reference_ID=2
* Reference name: AD_Reference Validation Types
*/
public static final int VALIDATIONTYPE_AD_Reference_ID=2;
/** ListValidation = L */
public static final String VALIDATIONTYPE_ListValidation = "L";
/** DataType = D */
public static final String VALIDATIONTYPE_DataType = "D";
/** TableValidation = T */
public static final String VALIDATIONTYPE_TableValidation = "T";
/** Set Validation type.
@param ValidationType
Different method of validating data
*/
@Override
public void setValidationType (java.lang.String ValidationType)
{
set_Value (COLUMNNAME_ValidationType, ValidationType);
}
/** Get Validation type.
@return Different method of validating data
*/
@Override
public java.lang.String getValidationType ()
{
return (java.lang.String)get_Value(COLUMNNAME_ValidationType);
}
/** Set Value Format.
@param VFormat
Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
@Override
public void setVFormat (java.lang.String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
/** Get Value Format.
@return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
@Override
public java.lang.String getVFormat ()
{
return (java.lang.String)get_Value(COLUMNNAME_VFormat);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Reference.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return new ExecuteJobsRunnable(jobIds, processEngine);
}
@Override
public boolean schedule(Runnable runnable, boolean isLongRunning) {
if(isLongRunning) {
return scheduleLongRunningWork(runnable);
} else {
return scheduleShortRunningWork(runnable);
}
}
protected boolean scheduleShortRunningWork(Runnable runnable) {
EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get();
try {
EnhancedQueueExecutor.execute(runnable);
return true;
} catch (Exception e) {
// we must be able to schedule this
log.log(Level.WARNING, "Cannot schedule long running work.", e);
}
return false;
}
protected boolean scheduleLongRunningWork(Runnable runnable) { | final EnhancedQueueExecutor EnhancedQueueExecutor = managedQueueSupplier.get();
boolean rejected = false;
try {
EnhancedQueueExecutor.execute(runnable);
} catch (RejectedExecutionException e) {
rejected = true;
} catch (Exception e) {
// if it fails for some other reason, log a warning message
long now = System.currentTimeMillis();
// only log every 60 seconds to prevent log flooding
if((now-lastWarningLogged) >= (60*1000)) {
log.log(Level.WARNING, "Unexpected Exception while submitting job to executor pool.", e);
} else {
log.log(Level.FINE, "Unexpected Exception while submitting job to executor pool.", e);
}
}
return !rejected;
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscExecutorService.java | 2 |
请完成以下Java代码 | public Currency getById(@NonNull final CurrencyId currencyId)
{
return currencyDAO.getById(currencyId);
}
@NonNull
public Currency getById(final int currencyId)
{
return getById(CurrencyId.ofRepoId(currencyId));
}
public CurrencyId getCurrencyIdByCurrencyCode(@NonNull final CurrencyCode currencyCode)
{
final Currency currency = currencyDAO.getByCurrencyCode(currencyCode);
return currency.getId();
}
public CurrencyCode getCurrencyCodeById(@NonNull final CurrencyId currencyId)
{
return getById(currencyId).getCurrencyCode();
}
public CurrencyPrecision getStdPrecision(@NonNull final CurrencyId currencyId)
{ | return getById(currencyId).getPrecision();
}
public CurrencyPrecision getStdPrecision(@NonNull final CurrencyCode currencyCode)
{
final CurrencyId currencyId = getCurrencyIdByCurrencyCode(currencyCode);
return getStdPrecision(currencyId);
}
public CurrencyPrecision getCostingPrecision(@NonNull final CurrencyId currencyId)
{
return getById(currencyId).getCostingPrecision();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\CurrencyRepository.java | 1 |
请完成以下Java代码 | public long getTimestamp() {
return this.timestamp;
}
/**
* When the confirmation is nacked, set the cause when available.
* @param cause The cause.
* @since 1.4
*/
public void setCause(String cause) {
this.cause = cause;
}
/**
* @return the cause.
* @since 1.4
*/
public @Nullable String getCause() {
return this.cause;
}
/**
* True if a returned message has been received.
* @return true if there is a return.
* @since 2.2.10
*/
public boolean isReturned() {
return this.returned;
}
/**
* Indicate that a returned message has been received.
* @param isReturned true if there is a return.
* @since 2.2.10 | */
public void setReturned(boolean isReturned) {
this.returned = isReturned;
}
/**
* Return true if a return has been passed to the listener or if no return has been
* received.
* @return false if an expected returned message has not been passed to the listener.
* @throws InterruptedException if interrupted.
* @since 2.2.10
*/
public boolean waitForReturnIfNeeded() throws InterruptedException {
return !this.returned || this.latch.await(RETURN_CALLBACK_TIMEOUT, TimeUnit.SECONDS);
}
/**
* Count down the returned message latch; call after the listener has been called.
* @since 2.2.10
*/
public void countDown() {
this.latch.countDown();
}
@Override
public String toString() {
return "PendingConfirm [correlationData=" + this.correlationData +
(this.cause == null ? "" : " cause=" + this.cause) + "]";
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\connection\PendingConfirm.java | 1 |
请完成以下Java代码 | public boolean isAllowAnyDocType(@NonNull final WarehouseId warehouseId)
{
// allow any docType if there were no routings defined for given warehouse
return getDocBaseTypesForWarehouse(warehouseId).isEmpty();
}
private List<String> getDocBaseTypesForWarehouse(final WarehouseId warehouseId)
{
return docBaseTypesByWarehouseId.get(warehouseId);
}
public boolean isDocTypeAllowed(@NonNull final WarehouseId warehouseId, @NonNull final String docBaseType)
{
if (isAllowAnyDocType(warehouseId))
{ | return true;
}
return getDocBaseTypesForWarehouse(warehouseId).contains(docBaseType);
}
public Set<WarehouseId> getWarehouseIdsAllowedForDocType(final Set<WarehouseId> warehouseIds, final String docBaseType)
{
return warehouseIds
.stream()
.filter(warehouseId -> isDocTypeAllowed(warehouseId, docBaseType))
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\api\impl\WarehouseRoutingsIndex.java | 1 |
请完成以下Java代码 | public ProcessEngineConfiguration getProcessEngineConfig() {
return processEngineConfig;
}
public void setProcessEngineConfig(ProcessEngineConfiguration processEngineConfig) {
this.processEngineConfig = processEngineConfig;
}
private static final Logger LOGGER = LoggerFactory.getLogger(JMXConfigurator.class);
// disable jmx
private boolean disabled;
public String getDomain() {
return domain;
}
public void setDomain(String domain) {
this.domain = domain;
}
public String getMbeanDomain() {
return mbeanDomain;
}
public Boolean getCreateConnector() {
return createConnector;
}
public void setCreateConnector(Boolean createConnector) {
this.createConnector = createConnector;
}
public void setMbeanDomain(String mbeanDomain) {
this.mbeanDomain = mbeanDomain;
}
// jmx (rmi registry) port
private Integer registryPort = 1099;
public Integer getRegistryPort() {
return registryPort;
}
public void setRegistryPort(Integer registryPort) {
this.registryPort = registryPort;
}
public String getServiceUrlPath() {
return serviceUrlPath;
} | public void setServiceUrlPath(String serviceUrlPath) {
this.serviceUrlPath = serviceUrlPath;
}
public Integer getConnectorPort() {
return connectorPort;
}
public void setConnectorPort(Integer connectorPort) {
this.connectorPort = connectorPort;
}
@Override
public void beforeInit(AbstractEngineConfiguration engineConfiguration) {
// nothing to do
}
@Override
public void configure(AbstractEngineConfiguration engineConfiguration) {
try {
this.processEngineConfig = (ProcessEngineConfiguration) engineConfiguration;
if (!disabled) {
managementAgent = new DefaultManagementAgent(this);
managementAgent.doStart();
managementAgent.findAndRegisterMbeans();
}
} catch (Exception e) {
LOGGER.warn("error in initializing jmx. Continue with partial or no JMX configuration", e);
}
}
} | repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\JMXConfigurator.java | 1 |
请完成以下Java代码 | public boolean isInfiniteCapacity(@NonNull final HUPIItemProductId id)
{
if (id.isVirtualHU())
{
return true;
}
final I_M_HU_PI_Item_Product piip = getRecordById(id);
if (piip == null)
{
return true;
}
return piip.isInfiniteCapacity();
}
@Override
public void deleteForItem(final I_M_HU_PI_Item packingInstructionsItem)
{
final List<I_M_HU_PI_Item_Product> products = huPIItemProductDAO.retrievePIMaterialItemProducts(packingInstructionsItem);
for (final I_M_HU_PI_Item_Product product : products)
{
InterfaceWrapperHelper.delete(product);
}
}
@Override
public void setNameAndDescription(final I_M_HU_PI_Item_Product itemProduct)
{
//
// Build itemProduct's name from scratch
final String nameBuilt = buildDisplayName()
.setM_HU_PI_Item_Product(itemProduct)
.buildItemProductDisplayName(); // build it from scratch
// Set it as Name and Description
itemProduct.setName(nameBuilt);
itemProduct.setDescription(nameBuilt);
}
@Override
public IHUPIItemProductDisplayNameBuilder buildDisplayName()
{
return new HUPIItemProductDisplayNameBuilder();
}
@Override
public ITranslatableString getDisplayName(@NonNull final HUPIItemProductId piItemProductId)
{
return huPIItemProductDAO.getById(piItemProductId).getName();
}
@Nullable
public I_M_HU_PI_Item_Product getDefaultForProduct(@NonNull final ProductId productId, @NonNull final ZonedDateTime dateTime)
{
return huPIItemProductDAO.retrieveDefaultForProduct(productId, dateTime);
}
@NonNull
public I_M_HU_PI_Item_Product extractHUPIItemProduct(final I_C_Order order, final I_C_OrderLine orderLine)
{
final HUPIItemProductId hupiItemProductId = HUPIItemProductId.ofRepoIdOrNull(orderLine.getM_HU_PI_Item_Product_ID()); | if (hupiItemProductId != null)
{
return huPIItemProductDAO.getRecordById(hupiItemProductId);
}
else
{
final ProductId productId = ProductId.ofRepoId(orderLine.getM_Product_ID());
final BPartnerId buyerBPartnerId = BPartnerId.ofRepoId(order.getC_BPartner_ID());
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID()));
return huPIItemProductDAO.retrieveMaterialItemProduct(
productId,
buyerBPartnerId,
TimeUtil.asZonedDateTime(order.getDateOrdered(), timeZone),
X_M_HU_PI_Version.HU_UNITTYPE_TransportUnit, true/* allowInfiniteCapacity */);
}
}
@Override
public int getRequiredLUCount(final @NonNull Quantity qty, final I_M_HU_LUTU_Configuration lutuConfigurationInStockUOM)
{
if (lutuConfigurationInStockUOM.isInfiniteQtyTU() || lutuConfigurationInStockUOM.isInfiniteQtyCU())
{
return 1;
}
else
{
// Note need to use the StockQty because lutuConfigurationInStockUOM is also in stock-UOM.
// And in the case of catchweight, it's very important to *not* make metasfresh convert quantites using the UOM-conversion
return lutuConfigurationFactory.calculateQtyLUForTotalQtyCUs(
lutuConfigurationInStockUOM,
qty);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductBL.java | 1 |
请完成以下Java代码 | private boolean internalCheckPalindrome(String input) {
int left = 0;
int right = input.length() - 1;
while (left < right) {
if (input.charAt(left) != input.charAt(right)) {
return false;
}
left++;
right--;
}
return true;
}
@DELETE | @Path("empty-list")
public void emptyList() {
list.clear();
}
@GET
@Path("/clearmetrics")
public Response clearAllPollerMetrics() {
registry.clear();
list.clear();
registry.gaugeCollectionSize("palindrome.list.size", Tags.empty(), list);
return Response.ok().build();
}
} | repos\tutorials-master\quarkus-modules\quarkus\src\main\java\com\baeldung\quarkus\micrometer\PalindromeResource.java | 1 |
请完成以下Java代码 | protected void concatenateErrorMessages(Throwable throwable) {
while (throwable != null) {
if (message == null) {
message = throwable.getMessage();
} else {
message += ": " + throwable.getMessage();
}
throwable = throwable.getCause();
}
}
protected void extractElementDetails(Element element) {
if (element != null) {
this.line = element.getLine();
this.column = element.getColumn();
String id = element.attribute("id");
if (id != null && id.length() > 0) {
this.mainElementId = id;
this.elementIds.add(id);
}
}
}
// getters
@Override
public String getMessage() {
return message;
}
@Override
public int getLine() {
return line;
}
@Override
public int getColumn() {
return column;
}
@Override
public String getMainElementId() {
return mainElementId; | }
@Override
public List<String> getElementIds() {
return elementIds;
}
public String toString() {
StringBuilder string = new StringBuilder();
if (line > 0) {
string.append(" | line " + line);
}
if (column > 0) {
string.append(" | column " + column);
}
return string.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\xml\ProblemImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ReadHeaderRestController {
private static final Log LOG = LogFactory.getLog(ReadHeaderRestController.class);
@GetMapping("/")
public ResponseEntity<String> index() {
return new ResponseEntity<>("Index", HttpStatus.OK);
}
@GetMapping("/greeting")
public ResponseEntity<String> greeting(@RequestHeader(value = HttpHeaders.ACCEPT_LANGUAGE) String language) {
String greeting = "";
List<Locale.LanguageRange> ranges = Locale.LanguageRange.parse(language);
String firstLanguage = ranges.get(0).getRange();
switch (firstLanguage) {
case "es":
greeting = "Hola!";
break;
case "de":
greeting = "Hallo!";
break;
case "fr":
greeting = "Bonjour!";
break;
case "en":
default:
greeting = "Hello!";
break;
}
return new ResponseEntity<>(greeting, HttpStatus.OK);
}
@GetMapping("/double")
public ResponseEntity<String> doubleNumber(@RequestHeader("my-number") int myNumber) {
return new ResponseEntity<>(
String.format("%d * 2 = %d", myNumber, (myNumber * 2)),
HttpStatus.OK);
}
@GetMapping("/listHeaders")
public ResponseEntity<String> listAllHeaders(@RequestHeader Map<String, String> headers) {
headers.forEach((key, value) -> LOG.info(String.format("Header '%s' = %s", key, value)));
return new ResponseEntity<>(String.format("Listed %d headers", headers.size()), HttpStatus.OK); | }
@GetMapping("/multiValue")
public ResponseEntity<String> multiValue(@RequestHeader MultiValueMap<String, String> headers) {
headers.forEach((key, value) -> LOG.info(String.format("Header '%s' = %s", key, String.join("|", value))));
return new ResponseEntity<>(String.format("Listed %d headers", headers.size()), HttpStatus.OK);
}
@GetMapping("/getBaseUrl")
public ResponseEntity<String> getBaseUrl(@RequestHeader HttpHeaders headers) {
InetSocketAddress host = headers.getHost();
String url = "http://" + host.getHostName() + ":" + host.getPort();
return new ResponseEntity<>(String.format("Base URL = %s", url), HttpStatus.OK);
}
@GetMapping("/nonRequiredHeader")
public ResponseEntity<String> evaluateNonRequiredHeader(
@RequestHeader(value = "optional-header", required = false) String optionalHeader) {
return new ResponseEntity<>(
String.format("Was the optional header present? %s!", (optionalHeader == null ? "No" : "Yes")),
HttpStatus.OK);
}
@GetMapping("/default")
public ResponseEntity<String> evaluateDefaultHeaderValue(
@RequestHeader(value = "optional-header", defaultValue = "3600") int optionalHeader) {
return new ResponseEntity<>(String.format("Optional Header is %d", optionalHeader), HttpStatus.OK);
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\spring\headers\controller\ReadHeaderRestController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class BookDTO implements Serializable {
private Long id;
@NotNull
private String title;
@NotNull
private String author;
@NotNull
private LocalDate published;
@NotNull
@Min(value = 0)
private Integer quantity;
@NotNull
@DecimalMin(value = "0")
private Double price;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public LocalDate getPublished() {
return published;
}
public void setPublished(LocalDate published) {
this.published = published; | }
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BookDTO bookDTO = (BookDTO) o;
if (bookDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), bookDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "BookDTO{" +
"id=" + getId() +
", title='" + getTitle() + "'" +
", author='" + getAuthor() + "'" +
", published='" + getPublished() + "'" +
", quantity=" + getQuantity() +
", price=" + getPrice() +
"}";
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\BookDTO.java | 2 |
请完成以下Java代码 | public void setColumns (int cols)
{
m_textArea.setColumns (cols);
}
/**
* Get Columns
* @return columns
*/
public int getColumns()
{
return m_textArea.getColumns();
}
/**
* Set Rows
* @param rows
*/
public void setRows (int rows)
{
m_textArea.setRows(rows);
}
/**
* Get Rows
* @return rows
*/
public int getRows()
{
return m_textArea.getRows();
}
/**
* Set Text Caret Position
* @param pos
*/
public void setCaretPosition (int pos)
{
m_textArea.setCaretPosition (pos);
}
/**
* Get Text Caret Position
* @return position
*/
public int getCaretPosition()
{
return m_textArea.getCaretPosition();
}
/**
* Set Text Editable
* @param edit
*/
public void setEditable (boolean edit)
{
m_textArea.setEditable(edit);
}
/**
* Is Text Editable
* @return true if editable
*/
public boolean isEditable()
{
return m_textArea.isEditable();
}
/**
* Set Text Line Wrap
* @param wrap
*/
public void setLineWrap (boolean wrap)
{
m_textArea.setLineWrap (wrap);
}
/**
* Set Text Wrap Style Word
* @param word
*/
public void setWrapStyleWord (boolean word)
{
m_textArea.setWrapStyleWord (word);
}
/**
* Set Opaque
* @param isOpaque
*/
@Override | public void setOpaque (boolean isOpaque)
{
// JScrollPane & Viewport is always not Opaque
if (m_textArea == null) // during init of JScrollPane
super.setOpaque(isOpaque);
else
m_textArea.setOpaque(isOpaque);
} // setOpaque
/**
* Set Text Margin
* @param m insets
*/
public void setMargin (Insets m)
{
if (m_textArea != null)
m_textArea.setMargin(m);
} // setMargin
/**
* AddFocusListener
* @param l
*/
@Override
public void addFocusListener (FocusListener l)
{
if (m_textArea == null) // during init
super.addFocusListener(l);
else
m_textArea.addFocusListener(l);
}
/**
* Add Text Mouse Listener
* @param l
*/
@Override
public void addMouseListener (MouseListener l)
{
m_textArea.addMouseListener(l);
}
/**
* Add Text Key Listener
* @param l
*/
@Override
public void addKeyListener (KeyListener l)
{
m_textArea.addKeyListener(l);
}
/**
* Add Text Input Method Listener
* @param l
*/
@Override
public void addInputMethodListener (InputMethodListener l)
{
m_textArea.addInputMethodListener(l);
}
/**
* Get text Input Method Requests
* @return requests
*/
@Override
public InputMethodRequests getInputMethodRequests()
{
return m_textArea.getInputMethodRequests();
}
/**
* Set Text Input Verifier
* @param l
*/
@Override
public void setInputVerifier (InputVerifier l)
{
m_textArea.setInputVerifier(l);
}
@Override
public final ICopyPasteSupportEditor getCopyPasteSupport()
{
return copyPasteSupport;
}
} // CTextArea | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextArea.java | 1 |
请完成以下Java代码 | public String getMailText2 ()
{
return (String)get_Value(COLUMNNAME_MailText2);
}
/** Set Mail Text 3.
@param MailText3
Optional third text part used for Mail message
*/
public void setMailText3 (String MailText3)
{
set_Value (COLUMNNAME_MailText3, MailText3);
}
/** Get Mail Text 3.
@return Optional third text part used for Mail message
*/
public String getMailText3 ()
{
return (String)get_Value(COLUMNNAME_MailText3);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair() | {
return new KeyNamePair(get_ID(), getName());
}
/** Set Mail Template.
@param R_MailText_ID
Text templates for mailings
*/
public void setR_MailText_ID (int R_MailText_ID)
{
if (R_MailText_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_MailText_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_MailText_ID, Integer.valueOf(R_MailText_ID));
}
/** Get Mail Template.
@return Text templates for mailings
*/
public int getR_MailText_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_MailText_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_R_MailText.java | 1 |
请完成以下Java代码 | public static List<EngineInfo> getAppEngineInfos() {
return appEngineInfos;
}
/**
* Get initialization results. Only info will we available for app engines which were added in the {@link AppEngines#init()}. No {@link EngineInfo} is available for engines which were registered
* programmatically.
*/
public static EngineInfo getAppEngineInfo(String appEngineName) {
return appEngineInfosByName.get(appEngineName);
}
public static AppEngine getDefaultAppEngine() {
return getAppEngine(NAME_DEFAULT);
}
/**
* Obtain an app engine by name.
*
* @param appEngineName
* is the name of the app engine or null for the default app engine.
*/
public static AppEngine getAppEngine(String appEngineName) {
if (!isInitialized()) {
init();
}
return appEngines.get(appEngineName);
}
/**
* retries to initialize an app engine that previously failed.
*/
public static EngineInfo retry(String resourceUrl) {
LOGGER.debug("retying initializing of resource {}", resourceUrl);
try {
return initAppEngineFromResource(new URL(resourceUrl));
} catch (MalformedURLException e) {
throw new FlowableException("invalid url: " + resourceUrl, e);
}
}
/**
* provides access to app engine to application clients in a managed server environment.
*/
public static Map<String, AppEngine> getAppEngines() {
return appEngines;
}
/**
* closes all app engines. This method should be called when the server shuts down. | */
public static synchronized void destroy() {
if (isInitialized()) {
Map<String, AppEngine> engines = new HashMap<>(appEngines);
appEngines = new HashMap<>();
for (String appEngineName : engines.keySet()) {
AppEngine appEngine = engines.get(appEngineName);
try {
appEngine.close();
} catch (Exception e) {
LOGGER.error("exception while closing {}", (appEngineName == null ? "the default app engine" : "app engine " + appEngineName), e);
}
}
appEngineInfosByName.clear();
appEngineInfosByResourceUrl.clear();
appEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
AppEngines.isInitialized = isInitialized;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\AppEngines.java | 1 |
请完成以下Java代码 | public class Article {
@Identity
private Slug slug;
private Username author;
private String title;
private String content;
private Status status;
private List<Comment> comments;
private List<Username> likedBy;
enum Status {
DRAFT, PUBLISHED, HIDDEN, ARCHIVED
}
public Article(Username author, String content, String title) {
this.status = Status.DRAFT;
this.author = author;
this.title = title;
this.content = content;
this.slug = new Slug(title.toLowerCase()
.replaceAll(" ", "-"));
this.comments = new ArrayList<>();
this.likedBy = new ArrayList<>();
}
void publish() {
if (status == Status.DRAFT || status == Status.HIDDEN) {
status = Status.PUBLISHED;
}
throw new IllegalStateException("we cannot publish an article with status=" + status);
}
void hide() {
if (status == Status.PUBLISHED) {
status = Status.HIDDEN;
}
throw new IllegalStateException("we cannot hide an article with status=" + status);
}
void archive() {
if (status != Status.ARCHIVED) {
status = Status.ARCHIVED;
}
throw new IllegalStateException("the article is already archived");
}
void comment(Username user, String message) { | comments.add(new Comment(user, message));
}
void like(Username user) {
likedBy.add(user);
}
void dislike(Username user) {
likedBy.remove(user);
}
public Slug getSlug() {
return slug;
}
public Username getAuthor() {
return author;
}
public String getTitle() {
return title;
}
public String getContent() {
return content;
}
public Status getStatus() {
return status;
}
public List<Comment> getComments() {
return Collections.unmodifiableList(comments);
}
public List<Username> getLikedBy() {
return Collections.unmodifiableList(likedBy);
}
} | repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddjmolecules\article\Article.java | 1 |
请完成以下Java代码 | public PartyIdentification43 getCdtr() {
return cdtr;
}
/**
* Sets the value of the cdtr property.
*
* @param value
* allowed object is
* {@link PartyIdentification43 }
*
*/
public void setCdtr(PartyIdentification43 value) {
this.cdtr = value;
}
/**
* Gets the value of the cdtrAcct property.
*
* @return
* possible object is
* {@link CashAccount24 }
*
*/
public CashAccount24 getCdtrAcct() {
return cdtrAcct;
}
/**
* Sets the value of the cdtrAcct property.
*
* @param value
* allowed object is
* {@link CashAccount24 }
*
*/
public void setCdtrAcct(CashAccount24 value) {
this.cdtrAcct = value;
}
/**
* Gets the value of the ultmtCdtr property.
*
* @return
* possible object is
* {@link PartyIdentification43 }
*
*/
public PartyIdentification43 getUltmtCdtr() {
return ultmtCdtr;
}
/**
* Sets the value of the ultmtCdtr property.
*
* @param value
* allowed object is
* {@link PartyIdentification43 }
*
*/
public void setUltmtCdtr(PartyIdentification43 value) {
this.ultmtCdtr = value;
}
/**
* Gets the value of the tradgPty property.
*
* @return
* possible object is
* {@link PartyIdentification43 }
*
*/
public PartyIdentification43 getTradgPty() {
return tradgPty;
}
/**
* Sets the value of the tradgPty property.
*
* @param value
* allowed object is
* {@link PartyIdentification43 } | *
*/
public void setTradgPty(PartyIdentification43 value) {
this.tradgPty = value;
}
/**
* Gets the value of the prtry property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the prtry property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getPrtry().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link ProprietaryParty3 }
*
*
*/
public List<ProprietaryParty3> getPrtry() {
if (prtry == null) {
prtry = new ArrayList<ProprietaryParty3>();
}
return this.prtry;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\TransactionParties3.java | 1 |
请完成以下Java代码 | public Set<String> getProcessEngineNames() {
Set<String> processEngineNames = new HashSet<String>();
List<ProcessEngine> processEngines = getProcessEngines();
for (ProcessEngine processEngine : processEngines) {
processEngineNames.add(processEngine.getName());
}
return processEngineNames;
}
// process application service implementation /////////////////////////////////
@Override
public Set<String> getProcessApplicationNames() {
List<JmxManagedProcessApplication> processApplications = serviceContainer.getServiceValuesByType(ServiceTypes.PROCESS_APPLICATION);
Set<String> processApplicationNames = new HashSet<String>();
for (JmxManagedProcessApplication jmxManagedProcessApplication : processApplications) {
processApplicationNames.add(jmxManagedProcessApplication.getProcessApplicationName());
}
return processApplicationNames;
}
@Override
public ProcessApplicationInfo getProcessApplicationInfo(String processApplicationName) {
JmxManagedProcessApplication processApplicationService = serviceContainer.getServiceValue(ServiceTypes.PROCESS_APPLICATION, processApplicationName); | if (processApplicationService == null) {
return null;
} else {
return processApplicationService.getProcessApplicationInfo();
}
}
@Override
public ProcessApplicationReference getDeployedProcessApplication(String processApplicationName) {
JmxManagedProcessApplication processApplicationService = serviceContainer.getServiceValue(ServiceTypes.PROCESS_APPLICATION, processApplicationName);
if (processApplicationService == null) {
return null;
} else {
return processApplicationService.getProcessApplicationReference();
}
}
// Getter / Setter ////////////////////////////////////////////////////////////
public PlatformServiceContainer getServiceContainer() {
return serviceContainer;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\RuntimeContainerDelegateImpl.java | 1 |
请完成以下Java代码 | public class Todo {
private int id;
private String user;
@Size(min=10, message="Enter at least 10 Characters...")
private String desc;
private Date targetDate;
private boolean isDone;
public Todo() {
super();
}
public Todo(int id, String user, String desc, Date targetDate,
boolean isDone) {
super();
this.id = id;
this.user = user;
this.desc = desc;
this.targetDate = targetDate;
this.isDone = isDone;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
public Date getTargetDate() {
return targetDate;
}
public void setTargetDate(Date targetDate) {
this.targetDate = targetDate;
}
public boolean isDone() {
return isDone;
}
public void setDone(boolean isDone) {
this.isDone = isDone;
}
@Override
public int hashCode() { | final int prime = 31;
int result = 1;
result = prime * result + id;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Todo other = (Todo) obj;
if (id != other.id) {
return false;
}
return true;
}
@Override
public String toString() {
return String.format(
"Todo [id=%s, user=%s, desc=%s, targetDate=%s, isDone=%s]", id,
user, desc, targetDate, isDone);
}
} | repos\SpringBootForBeginners-master\02.Spring-Boot-Web-Application\src\main\java\com\in28minutes\springboot\web\model\Todo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private ProductInfo getProductInfo(@NonNull final ProductId productId)
{
return productInfoCache.computeIfAbsent(productId, productService::getById);
}
@Override
public HUPIItemProduct getPackingInfo(@NonNull final HUPIItemProductId huPIItemProductId)
{
return huService.getPackingInfo(huPIItemProductId);
}
@Override
public String getPICaption(@NonNull final HuPackingInstructionsId piId)
{
return huService.getPI(piId).getName();
}
@Override
public String getLocatorName(@NonNull final LocatorId locatorId)
{
return locatorNamesCache.computeIfAbsent(locatorId, warehouseService::getLocatorNameById);
} | @Override
public HUQRCode getQRCodeByHUId(final HuId huId)
{
return huService.getQRCodeByHuId(huId);
}
@Override
public ScheduledPackageableLocks getLocks(final ShipmentScheduleAndJobScheduleIdSet scheduleIds)
{
return pickingJobLockService.getLocks(scheduleIds);
}
@Override
public int getSalesOrderLineSeqNo(@NonNull final OrderAndLineId orderAndLineId)
{
return orderService.getSalesOrderLineSeqNo(orderAndLineId);
}
//
//
//
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\DefaultPickingJobLoaderSupportingServices.java | 2 |
请完成以下Java代码 | public void setValue(Object value, VariableScope variableScope) {
ELContext elContext = Context.getProcessEngineConfiguration()
.getExpressionManager()
.getElContext(variableScope);
try {
ExpressionSetInvocation invocation = new ExpressionSetInvocation(valueExpression, elContext, value);
Context.getProcessEngineConfiguration().getDelegateInterceptor().handleInvocation(invocation);
} catch (Exception e) {
throw new ActivitiException("Error while evaluating expression: " + expressionText, e);
}
}
@Override
public String toString() {
if (valueExpression != null) {
return valueExpression.getExpressionString();
}
return super.toString();
}
@Override
public String getExpressionText() {
return expressionText;
}
@Override
public Object getValue( | ExpressionManager expressionManager,
DelegateInterceptor delegateInterceptor,
Map<String, Object> availableVariables
) {
ELContext elContext = expressionManager.getElContext(availableVariables);
return getValueFromContext(elContext, delegateInterceptor);
}
private Object getValueFromContext(ELContext elContext, DelegateInterceptor delegateInterceptor) {
try {
ExpressionGetInvocation invocation = new ExpressionGetInvocation(valueExpression, elContext);
delegateInterceptor.handleInvocation(invocation);
return invocation.getInvocationResult();
} catch (PropertyNotFoundException pnfe) {
throw new ActivitiException("Unknown property used in expression: " + expressionText, pnfe);
} catch (MethodNotFoundException mnfe) {
throw new ActivitiException("Unknown method used in expression: " + expressionText, mnfe);
} catch (Exception ele) {
throw new ActivitiException("Error while evaluating expression: " + expressionText, ele);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\el\JuelExpression.java | 1 |
请完成以下Java代码 | public static void destroyExample() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);
process.destroy();
}
public static void destroyForciblyExample() throws IOException, InterruptedException {
ProcessBuilder builder = new ProcessBuilder("notepad.exe");
Process process = builder.start();
Thread.sleep(10000);
process.destroy();
if (process.isAlive()) {
process.destroyForcibly();
}
}
public static void outputStreamDemo() throws IOException, InterruptedException {
Logger log = Logger.getLogger(ProcessUnderstanding.class.getName());
Process pr = Runtime.getRuntime()
.exec("javac -cp src src\\main\\java\\com\\baeldung\\java9\\process\\ChildProcess.java"); | final Process process = Runtime.getRuntime()
.exec("java -cp src/main/java com.baeldung.java9.process.ChildProcess");
try (Writer w = new OutputStreamWriter(process.getOutputStream(), "UTF-8")) {
w.write("send to child\n");
}
new Thread(() -> {
try {
int c;
while ((c = process.getInputStream()
.read()) != -1)
System.out.write((byte) c);
} catch (Exception e) {
e.printStackTrace();
}
}).start();
// send to child
log.log(Level.INFO, "rc=" + process.waitFor());
}
} | repos\tutorials-master\core-java-modules\core-java-os-2\src\main\java\com\baeldung\java9\process\ProcessUnderstanding.java | 1 |
请完成以下Java代码 | public void setProcessDefinitionName(String processDefinitionName) {
this.processDefinitionName = processDefinitionName;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
if (!super.equals(o)) {
return false;
}
ProcessInstanceImpl that = (ProcessInstanceImpl) o;
return (
Objects.equals(id, that.id) &&
Objects.equals(name, that.name) &&
Objects.equals(processDefinitionId, that.processDefinitionId) &&
Objects.equals(processDefinitionKey, that.processDefinitionKey) &&
Objects.equals(initiator, that.initiator) &&
Objects.equals(startDate, that.startDate) &&
Objects.equals(completedDate, that.completedDate) &&
Objects.equals(businessKey, that.businessKey) &&
status == that.status &&
Objects.equals(parentId, that.parentId) &&
Objects.equals(processDefinitionVersion, that.processDefinitionVersion) &&
Objects.equals(processDefinitionName, that.processDefinitionName)
);
}
@Override
public int hashCode() {
return Objects.hash(
super.hashCode(),
id,
name,
processDefinitionId,
processDefinitionKey,
initiator,
startDate,
completedDate,
businessKey,
status,
parentId,
processDefinitionVersion,
processDefinitionName
);
}
@Override
public String toString() {
return (
"ProcessInstance{" + | "id='" +
id +
'\'' +
", name='" +
name +
'\'' +
", processDefinitionId='" +
processDefinitionId +
'\'' +
", processDefinitionKey='" +
processDefinitionKey +
'\'' +
", parentId='" +
parentId +
'\'' +
", initiator='" +
initiator +
'\'' +
", startDate=" +
startDate +
", completedDate=" +
completedDate +
", businessKey='" +
businessKey +
'\'' +
", status=" +
status +
", processDefinitionVersion='" +
processDefinitionVersion +
'\'' +
", processDefinitionName='" +
processDefinitionName +
'\'' +
'}'
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessInstanceImpl.java | 1 |
请完成以下Java代码 | public void setDateDoc (final @Nullable java.sql.Timestamp DateDoc)
{
set_ValueNoCheck (COLUMNNAME_DateDoc, DateDoc);
}
@Override
public java.sql.Timestamp getDateDoc()
{
return get_ValueAsTimestamp(COLUMNNAME_DateDoc);
}
@Override
public de.metas.payment.esr.model.I_ESR_Import getESR_Import()
{
return get_ValueAsPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class);
}
@Override
public void setESR_Import(final de.metas.payment.esr.model.I_ESR_Import ESR_Import) | {
set_ValueFromPO(COLUMNNAME_ESR_Import_ID, de.metas.payment.esr.model.I_ESR_Import.class, ESR_Import);
}
@Override
public void setESR_Import_ID (final int ESR_Import_ID)
{
if (ESR_Import_ID < 1)
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, ESR_Import_ID);
}
@Override
public int getESR_Import_ID()
{
return get_ValueAsInt(COLUMNNAME_ESR_Import_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_x_esr_import_in_c_bankstatement_v.java | 1 |
请完成以下Java代码 | public Object getParameterDefaultValue(@NonNull final IProcessDefaultParameter parameter)
{
if (WAREHOUSE_PARAM_NAME.equals(parameter.getColumnName()))
{
if (existQuarantineHUs())
{
final IWarehouseDAO warehouseDAO = Services.get(IWarehouseDAO.class);
final WarehouseId quarantineWarehouseId = warehouseDAO.retrieveQuarantineWarehouseId();
return quarantineWarehouseId.getRepoId();
}
final int singleWarehouseId = CollectionUtils.extractSingleElementOrDefault(
getM_ReceiptSchedules(),
I_M_ReceiptSchedule::getM_Warehouse_Dest_ID,
-1);
if (singleWarehouseId > 0)
{
return singleWarehouseId;
}
}
else if (LOCATOR_PARAM_NAME.equals(parameter.getColumnName()))
{
if (warehouseIdOrNull() != null)
{
final LocatorId defaultLocator = warehouseBL.getOrCreateDefaultLocatorId(warehouseId());
if (defaultLocator != null)
{
return defaultLocator.getRepoId();
}
}
}
return null;
}
private boolean existQuarantineHUs()
{
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
return retrieveHUsToReceive()
.stream()
.map(handlingUnitsDAO::getById)
.anyMatch(lotNumberQuarantineService::isQuarantineHU);
}
@Override
public void onParameterChanged(String parameterName)
{
if (!WAREHOUSE_PARAM_NAME.equals(parameterName))
{
return;
}
if (warehouseIdOrNull() == null)
{
locatorRepoId = 0;
return;
}
locatorRepoId = warehouseBL.getOrCreateDefaultLocatorId(warehouseId()).getRepoId();
}
@ProcessParamLookupValuesProvider(parameterName = LOCATOR_PARAM_NAME, dependsOn = WAREHOUSE_PARAM_NAME, numericKey = true)
public LookupValuesList getLocators() | {
if (warehouseRepoId <= 0)
{
return LookupValuesList.EMPTY;
}
return warehouseDAO
.getLocators(warehouseId())
.stream()
.map(locator -> IntegerLookupValue.of(locator.getM_Locator_ID(), locator.getValue()))
.collect(LookupValuesList.collect());
}
@Override
protected void customizeParametersBuilder(@NonNull final CreateReceiptsParametersBuilder parametersBuilder)
{
final LocatorId locatorId = LocatorId.ofRepoIdOrNull(warehouseIdOrNull(), locatorRepoId);
parametersBuilder.destinationLocatorIdOrNull(locatorId);
}
private WarehouseId warehouseId()
{
return WarehouseId.ofRepoId(warehouseRepoId);
}
private WarehouseId warehouseIdOrNull()
{
return WarehouseId.ofRepoIdOrNull(warehouseRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_CreateReceipt_LocatorParams.java | 1 |
请完成以下Java代码 | public class DisplayCapabilities1 {
@XmlElement(name = "DispTp", required = true)
@XmlSchemaType(name = "string")
protected UserInterface2Code dispTp;
@XmlElement(name = "NbOfLines", required = true)
protected String nbOfLines;
@XmlElement(name = "LineWidth", required = true)
protected String lineWidth;
/**
* Gets the value of the dispTp property.
*
* @return
* possible object is
* {@link UserInterface2Code }
*
*/
public UserInterface2Code getDispTp() {
return dispTp;
}
/**
* Sets the value of the dispTp property.
*
* @param value
* allowed object is
* {@link UserInterface2Code }
*
*/
public void setDispTp(UserInterface2Code value) {
this.dispTp = value;
}
/**
* Gets the value of the nbOfLines property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNbOfLines() {
return nbOfLines;
} | /**
* Sets the value of the nbOfLines property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNbOfLines(String value) {
this.nbOfLines = value;
}
/**
* Gets the value of the lineWidth property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLineWidth() {
return lineWidth;
}
/**
* Sets the value of the lineWidth property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLineWidth(String value) {
this.lineWidth = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\DisplayCapabilities1.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public JobRepository getJobRepository() throws Exception {
JobRepositoryFactoryBean factory = new JobRepositoryFactoryBean();
factory.setDataSource(dataSource());
factory.setTransactionManager(getTransactionManager());
// JobRepositoryFactoryBean's methods Throws Generic Exception,
// it would have been better to have a specific one
factory.afterPropertiesSet();
return factory.getObject();
}
@Bean(name = "dataSource")
public DataSource dataSource() {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2)
.addScript("classpath:org/springframework/batch/core/schema-drop-h2.sql")
.addScript("classpath:org/springframework/batch/core/schema-h2.sql")
.build();
} | @Bean(name = "transactionManager")
public PlatformTransactionManager getTransactionManager() {
return new ResourcelessTransactionManager();
}
@Bean(name = "jobLauncher")
public JobLauncher getJobLauncher() throws Exception {
TaskExecutorJobLauncher jobLauncher = new TaskExecutorJobLauncher();
// SimpleJobLauncher's methods Throws Generic Exception,
// it would have been better to have a specific one
jobLauncher.setJobRepository(getJobRepository());
jobLauncher.afterPropertiesSet();
return jobLauncher;
}
} | repos\tutorials-master\spring-batch\src\main\java\com\baeldung\batch\partitioner\SpringBatchPartitionConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public DeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true;
return this;
}
public DeploymentBuilder activateProcessDefinitionsOn(Date date) {
this.processDefinitionsActivationDate = date;
return this;
}
@Override
public DeploymentBuilder deploymentProperty(String propertyKey, Object propertyValue) {
deploymentProperties.put(propertyKey, propertyValue);
return this;
}
public Deployment deploy() {
return repositoryService.deploy(this);
}
// getters and setters
// //////////////////////////////////////////////////////
public DeploymentEntity getDeployment() {
return deployment; | }
public boolean isProcessValidationEnabled() {
return isProcessValidationEnabled;
}
public boolean isBpmn20XsdValidationEnabled() {
return isBpmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
public Date getProcessDefinitionsActivationDate() {
return processDefinitionsActivationDate;
}
public Map<String, Object> getDeploymentProperties() {
return deploymentProperties;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\repository\DeploymentBuilderImpl.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.