instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public de.metas.printing.model.I_AD_PrinterHW getAD_PrinterHW()
{
return get_ValueAsPO(COLUMNNAME_AD_PrinterHW_ID, de.metas.printing.model.I_AD_PrinterHW.class);
}
@Override
public void setAD_PrinterHW(de.metas.printing.model.I_AD_PrinterHW AD_PrinterHW)
{
set_ValueFromPO(COLUMNNAME_AD_PrinterHW_ID, de.metas.printing.model.I_AD_PrinterHW.class, AD_PrinterHW);
}
@Override
public void setAD_PrinterHW_ID (int AD_PrinterHW_ID)
{
if (AD_PrinterHW_ID < 1)
set_Value (COLUMNNAME_AD_PrinterHW_ID, null);
else
set_Value (COLUMNNAME_AD_PrinterHW_ID, Integer.valueOf(AD_PrinterHW_ID));
}
@Override
public int getAD_PrinterHW_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_ID);
}
@Override
public void setAD_PrinterHW_MediaSize_ID (int AD_PrinterHW_MediaSize_ID)
{
if (AD_PrinterHW_MediaSize_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_PrinterHW_MediaSize_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_PrinterHW_MediaSize_ID, Integer.valueOf(AD_PrinterHW_MediaSize_ID));
}
@Override | public int getAD_PrinterHW_MediaSize_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_PrinterHW_MediaSize_ID);
}
@Override
public void setName (java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW_MediaSize.java | 1 |
请完成以下Java代码 | public boolean matches(@NonNull final AttributesKeyPart part)
{
if (type == AttributeKeyPartPatternType.All)
{
return true;
}
else if (type == AttributeKeyPartPatternType.Other)
{
throw new AdempiereException("Invalid pattern " + this);
}
else if (type == AttributeKeyPartPatternType.None)
{
return AttributesKeyPart.NONE.equals(part);
}
else if (type == AttributeKeyPartPatternType.AttributeValueId)
{
return AttributeKeyPartType.AttributeValueId.equals(part.getType())
&& Objects.equals(this.attributeValueId, part.getAttributeValueId());
}
else if (type == AttributeKeyPartPatternType.AttributeIdAndValue)
{
return AttributeKeyPartType.AttributeIdAndValue.equals(part.getType())
&& Objects.equals(this.attributeId, part.getAttributeId())
&& (Check.isEmpty(this.value) //no value means all values allowed
|| Objects.equals(this.value, part.getValue()));
}
else if (type == AttributeKeyPartPatternType.AttributeId)
{
return AttributeKeyPartType.AttributeIdAndValue.equals(part.getType())
&& Objects.equals(this.attributeId, part.getAttributeId());
}
else
{
throw new AdempiereException("Unknown type: " + type);
}
}
boolean isWildcardMatching()
{ | return type == AttributeKeyPartPatternType.AttributeId;
}
AttributesKeyPart toAttributeKeyPart(@Nullable final AttributesKey context)
{
if (type == AttributeKeyPartPatternType.All)
{
return AttributesKeyPart.ALL;
}
else if (type == AttributeKeyPartPatternType.Other)
{
return AttributesKeyPart.OTHER;
}
else if (type == AttributeKeyPartPatternType.None)
{
return AttributesKeyPart.NONE;
}
else if (type == AttributeKeyPartPatternType.AttributeValueId)
{
return AttributesKeyPart.ofAttributeValueId(attributeValueId);
}
else if (type == AttributeKeyPartPatternType.AttributeIdAndValue)
{
return AttributesKeyPart.ofAttributeIdAndValue(attributeId, value);
}
else if (type == AttributeKeyPartPatternType.AttributeId)
{
if (context == null)
{
throw new AdempiereException("Context is required to convert `" + this + "` to " + AttributesKeyPart.class);
}
final String valueEffective = context.getValueByAttributeId(attributeId);
return AttributesKeyPart.ofAttributeIdAndValue(attributeId, valueEffective);
}
else
{
throw new AdempiereException("Unknown type: " + type);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeyPartPattern.java | 1 |
请完成以下Java代码 | public boolean isOne()
{
return (fromToMultiplier == null || fromToMultiplier.compareTo(BigDecimal.ONE) == 0)
&& (toFromMultiplier == null || toFromMultiplier.compareTo(BigDecimal.ONE) == 0);
}
public BigDecimal getFromToMultiplier()
{
if (fromToMultiplier != null)
{
return fromToMultiplier;
}
else
{
return computeInvertedMultiplier(toFromMultiplier);
}
}
public static BigDecimal computeInvertedMultiplier(@NonNull final BigDecimal multiplier)
{
if (multiplier.signum() == 0)
{
throw new AdempiereException("Multiplier shall not be ZERO"); | }
return NumberUtils.stripTrailingDecimalZeros(BigDecimal.ONE.divide(multiplier, 12, RoundingMode.HALF_UP));
}
public BigDecimal convert(@NonNull final BigDecimal qty, @NonNull final UOMPrecision precision)
{
if (qty.signum() == 0)
{
return qty;
}
if (fromToMultiplier != null)
{
return precision.round(qty.multiply(fromToMultiplier));
}
else
{
return qty.divide(toFromMultiplier, precision.toInt(), precision.getRoundingMode());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMConversionRate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | InfoContributor buildInfoContributor(BuildProperties buildProperties) {
return new BuildInfoContributor(buildProperties);
}
@Bean
@ConditionalOnEnabledInfoContributor(value = "java", fallback = InfoContributorFallback.DISABLE)
@Order(DEFAULT_ORDER)
JavaInfoContributor javaInfoContributor() {
return new JavaInfoContributor();
}
@Bean
@ConditionalOnEnabledInfoContributor(value = "os", fallback = InfoContributorFallback.DISABLE)
@Order(DEFAULT_ORDER)
OsInfoContributor osInfoContributor() {
return new OsInfoContributor();
}
@Bean
@ConditionalOnEnabledInfoContributor(value = "process", fallback = InfoContributorFallback.DISABLE)
@Order(DEFAULT_ORDER)
ProcessInfoContributor processInfoContributor() {
return new ProcessInfoContributor();
} | @Bean
@ConditionalOnEnabledInfoContributor(value = "ssl", fallback = InfoContributorFallback.DISABLE)
@Order(DEFAULT_ORDER)
SslInfoContributor sslInfoContributor(SslInfo sslInfo) {
return new SslInfoContributor(sslInfo);
}
@Bean
@ConditionalOnMissingBean
@ConditionalOnEnabledInfoContributor(value = "ssl", fallback = InfoContributorFallback.DISABLE)
SslInfo sslInfo(SslBundles sslBundles) {
return new SslInfo(sslBundles);
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\info\InfoContributorAutoConfiguration.java | 2 |
请完成以下Java代码 | public int getPP_Order_BOMLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_BOMLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.eevolution.model.I_PP_Order getPP_Order() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class);
}
@Override
public void setPP_Order(org.eevolution.model.I_PP_Order PP_Order)
{
set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order);
}
/** Set Produktionsauftrag.
@param PP_Order_ID Produktionsauftrag */
@Override
public void setPP_Order_ID (int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_Value (COLUMNNAME_PP_Order_ID, null);
else
set_Value (COLUMNNAME_PP_Order_ID, Integer.valueOf(PP_Order_ID));
}
/** Get Produktionsauftrag.
@return Produktionsauftrag */
@Override | public int getPP_Order_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Order_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP_Alternative.java | 1 |
请完成以下Java代码 | public class ErrorResponse {
@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "dd-MM-yyyy hh:mm:ss")
private Date timestamp;
@JsonProperty(value = "code")
private int code;
@JsonProperty(value = "status")
private String status;
@JsonProperty(value = "message")
private String message;
@JsonProperty(value = "details")
private String details;
public ErrorResponse() {
}
public ErrorResponse(HttpStatus httpStatus, String message, String details) {
timestamp = new Date();
this.code = httpStatus.value();
this.status = httpStatus.name();
this.message = message;
this.details = details; | }
public Date getTimestamp() {
return timestamp;
}
public int getCode() {
return code;
}
public String getStatus() {
return status;
}
public String getMessage() {
return message;
}
public String getDetails() {
return details;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-openfeign-2\src\main\java\com\baeldung\cloud\openfeign\customizederrorhandling\exception\ErrorResponse.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class FeaturePolicyConfig {
private FeaturePolicyHeaderWriter writer;
private FeaturePolicyConfig() {
}
/**
* Allows completing configuration of Feature Policy and continuing configuration
* of headers.
* @return the {@link HeadersConfigurer} for additional configuration
*/
public HeadersConfigurer<H> and() {
return HeadersConfigurer.this;
}
}
public final class PermissionsPolicyConfig {
private PermissionsPolicyHeaderWriter writer;
private PermissionsPolicyConfig() {
}
/**
* Sets the policy to be used in the response header.
* @param policy a permissions policy
* @return the {@link PermissionsPolicyConfig} for additional configuration
* @throws IllegalArgumentException if policy is null
*/
public PermissionsPolicyConfig policy(String policy) {
this.writer.setPolicy(policy);
return this;
}
}
public final class CrossOriginOpenerPolicyConfig {
private CrossOriginOpenerPolicyHeaderWriter writer;
public CrossOriginOpenerPolicyConfig() {
}
/**
* Sets the policy to be used in the {@code Cross-Origin-Opener-Policy} header
* @param openerPolicy a {@code Cross-Origin-Opener-Policy}
* @return the {@link CrossOriginOpenerPolicyConfig} for additional configuration
* @throws IllegalArgumentException if openerPolicy is null
*/
public CrossOriginOpenerPolicyConfig policy(
CrossOriginOpenerPolicyHeaderWriter.CrossOriginOpenerPolicy openerPolicy) {
this.writer.setPolicy(openerPolicy);
return this;
}
}
public final class CrossOriginEmbedderPolicyConfig {
private CrossOriginEmbedderPolicyHeaderWriter writer;
public CrossOriginEmbedderPolicyConfig() { | }
/**
* Sets the policy to be used in the {@code Cross-Origin-Embedder-Policy} header
* @param embedderPolicy a {@code Cross-Origin-Embedder-Policy}
* @return the {@link CrossOriginEmbedderPolicyConfig} for additional
* configuration
* @throws IllegalArgumentException if embedderPolicy is null
*/
public CrossOriginEmbedderPolicyConfig policy(
CrossOriginEmbedderPolicyHeaderWriter.CrossOriginEmbedderPolicy embedderPolicy) {
this.writer.setPolicy(embedderPolicy);
return this;
}
}
public final class CrossOriginResourcePolicyConfig {
private CrossOriginResourcePolicyHeaderWriter writer;
public CrossOriginResourcePolicyConfig() {
}
/**
* Sets the policy to be used in the {@code Cross-Origin-Resource-Policy} header
* @param resourcePolicy a {@code Cross-Origin-Resource-Policy}
* @return the {@link CrossOriginResourcePolicyConfig} for additional
* configuration
* @throws IllegalArgumentException if resourcePolicy is null
*/
public CrossOriginResourcePolicyConfig policy(
CrossOriginResourcePolicyHeaderWriter.CrossOriginResourcePolicy resourcePolicy) {
this.writer.setPolicy(resourcePolicy);
return this;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\HeadersConfigurer.java | 2 |
请完成以下Java代码 | protected String getDeploymentId(CommandContext commandContext) {
return null;
}
protected abstract void checkAuthorization(CommandContext commandContext);
protected abstract void checkParameters(CommandContext commandContext);
protected abstract void updateSuspensionState(CommandContext commandContext, SuspensionState suspensionState);
protected abstract void logUserOperation(CommandContext commandContext);
protected abstract String getLogEntryOperation();
protected abstract SuspensionState getNewSuspensionState();
protected String getDeploymentIdByProcessDefinition(CommandContext commandContext, String processDefinitionId) {
ProcessDefinitionEntity definition = commandContext.getProcessDefinitionManager().getCachedResourceDefinitionEntity(processDefinitionId);
if (definition == null) {
definition = commandContext.getProcessDefinitionManager().findLatestDefinitionById(processDefinitionId);
}
if (definition != null) {
return definition.getDeploymentId();
}
return null;
}
protected String getDeploymentIdByProcessDefinitionKey(CommandContext commandContext, String processDefinitionKey,
boolean tenantIdSet, String tenantId) {
ProcessDefinitionEntity definition = null;
if (tenantIdSet) { | definition = commandContext.getProcessDefinitionManager().findLatestProcessDefinitionByKeyAndTenantId(processDefinitionKey, tenantId);
} else {
// randomly use a latest process definition's deployment id from one of the tenants
List<ProcessDefinitionEntity> definitions = commandContext.getProcessDefinitionManager().findLatestProcessDefinitionsByKey(processDefinitionKey);
definition = definitions.isEmpty() ? null : definitions.get(0);
}
if (definition != null) {
return definition.getDeploymentId();
}
return null;
}
protected String getDeploymentIdByJobDefinition(CommandContext commandContext, String jobDefinitionId) {
JobDefinitionManager jobDefinitionManager = commandContext.getJobDefinitionManager();
JobDefinitionEntity jobDefinition = jobDefinitionManager.findById(jobDefinitionId);
if (jobDefinition != null) {
if (jobDefinition.getProcessDefinitionId() != null) {
return getDeploymentIdByProcessDefinition(commandContext, jobDefinition.getProcessDefinitionId());
}
}
return null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\AbstractSetStateCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | LogFileWebEndpoint logFileWebEndpoint(ObjectProvider<LogFile> logFile, LogFileWebEndpointProperties properties) {
return new LogFileWebEndpoint(logFile.getIfAvailable(), properties.getExternalFile());
}
private static final class LogFileCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
Environment environment = context.getEnvironment();
String config = getLogFileConfig(environment, LogFile.FILE_NAME_PROPERTY);
ConditionMessage.Builder message = ConditionMessage.forCondition("Log File");
if (StringUtils.hasText(config)) {
return ConditionOutcome.match(message.found(LogFile.FILE_NAME_PROPERTY).items(config));
}
config = getLogFileConfig(environment, LogFile.FILE_PATH_PROPERTY);
if (StringUtils.hasText(config)) { | return ConditionOutcome.match(message.found(LogFile.FILE_PATH_PROPERTY).items(config));
}
config = environment.getProperty("management.endpoint.logfile.external-file");
if (StringUtils.hasText(config)) {
return ConditionOutcome.match(message.found("management.endpoint.logfile.external-file").items(config));
}
return ConditionOutcome.noMatch(message.didNotFind("logging file").atAll());
}
private String getLogFileConfig(Environment environment, String configName) {
return environment.resolvePlaceholders("${" + configName + ":}");
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\logging\LogFileWebEndpointAutoConfiguration.java | 2 |
请完成以下Java代码 | public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((author == null) ? 0 : author.hashCode());
long temp;
temp = Double.doubleToLongBits(cost);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + ((isbn == null) ? 0 : isbn.hashCode());
result = prime * result + ((publisher == null) ? 0 : publisher.hashCode());
result = prime * result + ((title == null) ? 0 : title.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Book other = (Book) obj;
if (author == null) {
if (other.author != null)
return false;
} else if (!author.equals(other.author)) | return false;
if (Double.doubleToLongBits(cost) != Double.doubleToLongBits(other.cost))
return false;
if (isbn == null) {
if (other.isbn != null)
return false;
} else if (!isbn.equals(other.isbn))
return false;
if (publisher == null) {
if (other.publisher != null)
return false;
} else if (!publisher.equals(other.publisher))
return false;
if (title == null) {
if (other.title != null)
return false;
} else if (!title.equals(other.title))
return false;
return true;
}
} | repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\bsontojson\Book.java | 1 |
请完成以下Java代码 | public BigDecimal getCompleteOrderDiscount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CompleteOrderDiscount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{ | return get_ValueAsInt(COLUMNNAME_SeqNo);
}
/**
* Type AD_Reference_ID=540836
* Reference name: C_CompensationGroup_SchemaLine_Type
*/
public static final int TYPE_AD_Reference_ID=540836;
/** Revenue = R */
public static final String TYPE_Revenue = "R";
/** Flatrate = F */
public static final String TYPE_Flatrate = "F";
@Override
public void setType (final @Nullable java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\order\model\X_C_CompensationGroup_SchemaLine.java | 1 |
请完成以下Java代码 | public IQueryFilter<I_M_ShipmentSchedule> getShipmentSchedulesQueryFiltersEffective()
{
final CompositeQueryFilter<I_M_ShipmentSchedule> result = CompositeQueryFilter.newInstance(I_M_ShipmentSchedule.class);
if (this.scheduleIds != null && !this.scheduleIds.isEmpty())
{
result.addOnlyActiveRecordsFilter();
result.addInArrayFilter(I_M_ShipmentSchedule.COLUMNNAME_M_ShipmentSchedule_ID, this.scheduleIds.getShipmentScheduleIds());
}
if (this.queryFilters != null)
{
result.addFilter(this.queryFilters);
}
if (result.isEmpty())
{
throw new AdempiereException("At least scheduleIds or queryFilters shall be set: " + this);
} | return result;
}
public Set<PickingJobScheduleId> getPickingJobScheduleIds()
{
if (scheduleIds == null || scheduleIds.isEmpty()) {return ImmutableSet.of();}
return scheduleIds.getJobScheduleIds();
}
public Set<PickingJobScheduleId> getPickingJobScheduleIds(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
if (scheduleIds == null || scheduleIds.isEmpty()) {return ImmutableSet.of();}
return scheduleIds.getJobScheduleIds(shipmentScheduleId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentScheduleWorkPackageParameters.java | 1 |
请完成以下Java代码 | public String getParameterAsString(final String parameterName)
{
return params.getParameterAsString(parameterName);
}
@Override
public int getParameterAsInt(final String parameterName, final int defaultValue)
{
return params.getParameterAsInt(parameterName, defaultValue);
}
@Override
public <T extends RepoIdAware> T getParameterAsId(String parameterName, Class<T> type)
{
return params.getParameterAsId(parameterName, type);
}
@Override
public BigDecimal getParameterAsBigDecimal(final String parameterName)
{
return params.getParameterAsBigDecimal(parameterName);
}
@Override
public Timestamp getParameterAsTimestamp(final String parameterName)
{
return params.getParameterAsTimestamp(parameterName);
}
@Override
public LocalDate getParameterAsLocalDate(final String parameterName)
{
return params.getParameterAsLocalDate(parameterName); | }
@Override
public ZonedDateTime getParameterAsZonedDateTime(final String parameterName)
{
return params.getParameterAsZonedDateTime(parameterName);
}
@Nullable
@Override
public Instant getParameterAsInstant(final String parameterName)
{
return params.getParameterAsInstant(parameterName);
}
@Override
public boolean getParameterAsBool(final String parameterName)
{
return params.getParameterAsBool(parameterName);
}
@Nullable
@Override
public Boolean getParameterAsBoolean(final String parameterName, @Nullable final Boolean defaultValue)
{
return params.getParameterAsBoolean(parameterName, defaultValue);
}
@Override
public <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType)
{
return params.getParameterAsEnum(parameterName, enumType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\ForwardingParams.java | 1 |
请完成以下Java代码 | public ELContext buildWithCustomFunctions(List<CustomFunctionProvider> customFunctionProviders) {
CompositeELResolver elResolver = createCompositeResolver();
ActivitiElContext elContext = new ActivitiElContext(elResolver);
try {
addDateFunctions(elContext);
addListFunctions(elContext);
if (customFunctionProviders != null) {
customFunctionProviders.forEach(provider -> {
try {
provider.addCustomFunctions(elContext);
} catch (Exception e) {
logger.error("Error setting up EL custom functions", e);
}
});
}
} catch (NoSuchMethodException e) {
logger.error("Error setting up EL custom functions", e);
} | return elContext;
}
private void addResolvers(CompositeELResolver compositeResolver) {
Stream.ofNullable(resolvers).flatMap(Collection::stream).forEach(compositeResolver::add);
}
private CompositeELResolver createCompositeResolver() {
CompositeELResolver elResolver = new CompositeELResolver();
elResolver.add(
new ReadOnlyMapELResolver((Objects.nonNull(variables) ? new HashMap<>(variables) : Collections.emptyMap()))
);
addResolvers(elResolver);
return elResolver;
}
} | repos\Activiti-develop\activiti-core-common\activiti-expression-language\src\main\java\org\activiti\core\el\ELContextBuilder.java | 1 |
请完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<DmnExpressionImpl> getConditions() {
return conditions;
}
public void setConditions(List<DmnExpressionImpl> conditions) {
this.conditions = conditions;
}
public List<DmnExpressionImpl> getConclusions() {
return conclusions;
} | public void setConclusions(List<DmnExpressionImpl> conclusions) {
this.conclusions = conclusions;
}
@Override
public String toString() {
return "DmnDecisionTableRuleImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", conditions=" + conditions +
", conclusions=" + conclusions +
'}';
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionTableRuleImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void postProcessEngineBuild(final ProcessEngine processEngine) {
requireNonNull(adminUser);
final IdentityService identityService = processEngine.getIdentityService();
final AuthorizationService authorizationService = processEngine.getAuthorizationService();
if (userAlreadyExists(identityService, adminUser)) {
return;
}
createUser(identityService, adminUser);
// create group
if (identityService.createGroupQuery().groupId(CAMUNDA_ADMIN).count() == 0) {
Group camundaAdminGroup = identityService.newGroup(CAMUNDA_ADMIN);
camundaAdminGroup.setName("camunda BPM Administrators");
camundaAdminGroup.setType(Groups.GROUP_TYPE_SYSTEM);
identityService.saveGroup(camundaAdminGroup);
}
// create ADMIN authorizations on all built-in resources
for (Resource resource : Resources.values()) {
if (authorizationService.createAuthorizationQuery().groupIdIn(CAMUNDA_ADMIN).resourceType(resource).resourceId(ANY).count() == 0) {
AuthorizationEntity userAdminAuth = new AuthorizationEntity(AUTH_TYPE_GRANT);
userAdminAuth.setGroupId(CAMUNDA_ADMIN);
userAdminAuth.setResource(resource);
userAdminAuth.setResourceId(ANY);
userAdminAuth.addPermission(ALL);
authorizationService.saveAuthorization(userAdminAuth);
} | }
identityService.createMembership(adminUser.getId(), CAMUNDA_ADMIN);
LOG.creatingInitialAdminUser(adminUser);
}
static boolean userAlreadyExists(IdentityService identityService, User adminUser) {
final User existingUser = identityService.createUserQuery()
.userId(adminUser.getId())
.singleResult();
if (existingUser != null) {
LOG.skipAdminUserCreation(existingUser);
return true;
}
return false;
}
static User createUser(final IdentityService identityService, final User adminUser) {
User newUser = identityService.newUser(adminUser.getId());
BeanUtils.copyProperties(adminUser, newUser);
identityService.saveUser(newUser);
return newUser;
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\configuration\impl\custom\CreateAdminUserConfiguration.java | 2 |
请完成以下Java代码 | public void save(final Properties ctx, final int windowNo, final IInfoWindowGridRowBuilders builders)
{
for (final Map.Entry<Integer, BigDecimal> e : record2qty.entrySet())
{
final Integer recordKey = e.getKey();
if (recordKey == null)
{
continue;
}
final BigDecimal qty = e.getValue();
if (qty == null || qty.signum() == 0)
{
continue;
}
final OrderLineProductQtyGridRowBuilder productQtyBuilder = new OrderLineProductQtyGridRowBuilder();
final Integer productId = record2productId.get(recordKey);
// productQtyBuilder.setSource(recordKey, productId, qty);
productQtyBuilder.setSource(productId, qty);
builders.addGridTabRowBuilder(recordKey, productQtyBuilder);
}
}
@Override
public void init(final IInfoSimple parent, final I_AD_InfoColumn infoColumn, final String searchText)
{
this.parent = parent;
infoColumnDef = infoColumn;
checkbox = new JCheckBox(infoColumn.getName());
checkbox.addActionListener(e -> {
InfoProductQtyController.this.parent.setIgnoreLoading(checkbox.isSelected());
InfoProductQtyController.this.parent.executeQuery();
});
updateDisplay();
}
@Override
public I_AD_InfoColumn getAD_InfoColumn()
{
return infoColumnDef;
}
@Override
public int getParameterCount()
{
return 1;
}
@Override
public String getLabel(final int index)
{
return null;
}
@Override
public Object getParameterComponent(final int index)
{
return checkbox;
}
@Override
public Object getParameterToComponent(final int index)
{ | return null;
}
@Override
public Object getParameterValue(final int index, final boolean returnValueTo)
{
return null;
}
@Override
public String[] getWhereClauses(final List<Object> params)
{
if (!checkbox.isEnabled() || !checkbox.isSelected())
{
return null;
}
if (record2productId.isEmpty())
{
return new String[] { "1=2" };
}
final String productColumnName = org.compiere.model.I_M_Product.Table_Name + "." + org.compiere.model.I_M_Product.COLUMNNAME_M_Product_ID;
final StringBuilder whereClause = new StringBuilder(productColumnName + " IN " + DB.buildSqlList(record2productId.values(), params));
if (gridConvertAfterLoadDelegate != null)
{
final String productComb = gridConvertAfterLoadDelegate.getProductCombinations();
if (productComb != null)
{
whereClause.append(productComb);
}
}
//
// 05135: We need just to display rows that have Qtys, but DON'T discard other filtering criterias
// return new String[] { WHERECLAUSE_CLEAR_PREVIOUS, whereClause, WHERECLAUSE_STOP};
return new String[] { whereClause.toString() };
}
@Override
public String getText()
{
return null;
}
@Override
public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel)
{
// nothing
}
@Override
public String getProductCombinations()
{
// nothing to do
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductQtyController.java | 1 |
请完成以下Java代码 | public static void setUp() {
databaseName = "baeldung";
testCollectionName = "vehicle";
if (mongoClient == null) {
mongoClient = new MongoClient("localhost", 27017);
database = mongoClient.getDatabase(databaseName);
collection = database.getCollection(testCollectionName);
}
}
public static void updateOperations() {
UpdateOptions options = new UpdateOptions().upsert(true);
UpdateResult updateResult = collection.updateOne(Filters.eq("modelName", "X5"), Updates.combine(Updates.set("companyName", "Hero Honda")), options);
System.out.println("updateResult:- " + updateResult);
}
public static void updateSetOnInsertOperations() {
UpdateOptions options = new UpdateOptions().upsert(true);
UpdateResult updateSetOnInsertResult = collection.updateOne(Filters.eq("modelName", "GTPR"),
Updates.combine(Updates.set("companyName", "Hero Honda"), Updates.setOnInsert("launchYear", 2022), Updates.setOnInsert("type", "Bike"), Updates.setOnInsert("registeredNo", "EPS 5562")), options);
System.out.println("updateSetOnInsertResult:- " + updateSetOnInsertResult);
}
public static void findOneAndUpdateOperations() {
FindOneAndUpdateOptions upsertOptions = new FindOneAndUpdateOptions();
upsertOptions.returnDocument(ReturnDocument.AFTER);
upsertOptions.upsert(true);
Document resultDocument = collection.findOneAndUpdate(Filters.eq("modelName", "X7"), Updates.set("companyName", "Hero Honda"), upsertOptions);
System.out.println("resultDocument:- " + resultDocument);
}
public static void replaceOneOperations() {
UpdateOptions options = new UpdateOptions().upsert(true);
Document replaceDocument = new Document();
replaceDocument.append("modelName", "GTPP")
.append("companyName", "Hero Honda")
.append("launchYear", 2022)
.append("type", "Bike")
.append("registeredNo", "EPS 5562");
UpdateResult updateReplaceResult = collection.replaceOne(Filters.eq("modelName", "GTPP"), replaceDocument, options); | System.out.println("updateReplaceResult:- " + updateReplaceResult);
}
public static void main(String args[]) {
//
// Connect to cluster (default is localhost:27017)
//
setUp();
//
// Update with upsert operation
//
updateOperations();
//
// Update with upsert operation using setOnInsert
//
updateSetOnInsertOperations();
//
// Update with upsert operation using findOneAndUpdate
//
findOneAndUpdateOperations();
//
// Update with upsert operation using replaceOneOperations
//
replaceOneOperations();
}
} | repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\update\UpsertOperations.java | 1 |
请完成以下Java代码 | public BoundaryEvent newInstance(ModelTypeInstanceContext instanceContext) {
return new BoundaryEventImpl(instanceContext);
}
});
cancelActivityAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_CANCEL_ACTIVITY)
.defaultValue(true)
.build();
attachedToRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ATTACHED_TO_REF)
.required()
.qNameAttributeReference(Activity.class)
.build();
typeBuilder.build();
}
public BoundaryEventImpl(ModelTypeInstanceContext context) {
super(context);
} | @Override
public BoundaryEventBuilder builder() {
return new BoundaryEventBuilder((BpmnModelInstance) modelInstance, this);
}
public boolean cancelActivity() {
return cancelActivityAttribute.getValue(this);
}
public void setCancelActivity(boolean cancelActivity) {
cancelActivityAttribute.setValue(this, cancelActivity);
}
public Activity getAttachedTo() {
return attachedToRefAttribute.getReferenceTargetElement(this);
}
public void setAttachedTo(Activity attachedTo) {
attachedToRefAttribute.setReferenceTargetElement(this, attachedTo);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\BoundaryEventImpl.java | 1 |
请完成以下Java代码 | public <T> T unwrap(Class<T> cls) {
return delegate.unwrap(cls);
}
public Object getDelegate() {
return delegate.getDelegate();
}
public void close() {
log.info("[I229] close");
delegate.close();
}
public boolean isOpen() {
boolean isOpen = delegate.isOpen();
log.info("[I236] isOpen: " + isOpen);
return isOpen;
}
public EntityTransaction getTransaction() {
log.info("[I240] getTransaction()");
return delegate.getTransaction();
}
public EntityManagerFactory getEntityManagerFactory() {
return delegate.getEntityManagerFactory();
}
public CriteriaBuilder getCriteriaBuilder() {
return delegate.getCriteriaBuilder();
}
public Metamodel getMetamodel() {
return delegate.getMetamodel();
}
public <T> EntityGraph<T> createEntityGraph(Class<T> rootType) {
return delegate.createEntityGraph(rootType);
}
public EntityGraph<?> createEntityGraph(String graphName) { | return delegate.createEntityGraph(graphName);
}
public EntityGraph<?> getEntityGraph(String graphName) {
return delegate.getEntityGraph(graphName);
}
public <T> List<EntityGraph<? super T>> getEntityGraphs(Class<T> entityClass) {
return delegate.getEntityGraphs(entityClass);
}
public EntityManagerWrapper(EntityManager delegate) {
this.delegate = delegate;
}
}
} | repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\CarsODataJPAServiceFactory.java | 1 |
请完成以下Java代码 | private Map<AsyncBatchId, List<CreateShipmentInfoCandidate>> getShipmentInfoCandidateByAsyncBatchId(@NonNull final List<JsonCreateShipmentInfo> createShipmentInfos)
{
final List<CreateShipmentInfoCandidate> createShipmentCandidates = createShipmentInfos.stream()
.map(this::buildCreateShipmentCandidate)
.collect(ImmutableList.toImmutableList());
final Map<ShipmentScheduleId, CreateShipmentInfoCandidate> candidateInfoById = Maps.uniqueIndex(createShipmentCandidates, CreateShipmentInfoCandidate::getShipmentScheduleId);
final ImmutableMap<AsyncBatchId, ShipmentScheduleAndJobScheduleIdSet> asyncBatchId2ScheduleIds = shipmentService.groupSchedulesByAsyncBatch(ShipmentScheduleAndJobScheduleIdSet.ofShipmentScheduleIds(candidateInfoById.keySet()));
return asyncBatchId2ScheduleIds.entrySet()
.stream()
.collect(
Collectors.toMap(
Map.Entry::getKey,
entry -> {
final Set<ShipmentScheduleId> shipmentScheduleIds = entry.getValue().getShipmentScheduleIds();
return shipmentScheduleIds.stream()
.map(candidateInfoById::get)
.collect(ImmutableList.toImmutableList());
}
)
);
}
@NonNull
private CreateShipmentInfoCandidate buildCreateShipmentCandidate(@NonNull final JsonCreateShipmentInfo jsonCreateShipmentInfo)
{
final ShipmentScheduleId shipmentScheduleId = extractShipmentScheduleId(jsonCreateShipmentInfo);
return CreateShipmentInfoCandidate.builder()
.createShipmentInfo(jsonCreateShipmentInfo)
.shipmentScheduleId(shipmentScheduleId)
.build();
} | private ShippingInfoCache newShippingInfoCache()
{
return ShippingInfoCache.builder()
.shipmentScheduleBL(shipmentScheduleBL)
.scheduleEffectiveBL(scheduleEffectiveBL)
.shipperDAO(shipperDAO)
.productDAO(productDAO)
.build();
}
@Value
@Builder
private static class CreateShipmentInfoCandidate
{
@NonNull
ShipmentScheduleId shipmentScheduleId;
@NonNull
JsonCreateShipmentInfo createShipmentInfo;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\shipping\JsonShipmentService.java | 1 |
请完成以下Java代码 | public void setTtlNetNtryAmt(BigDecimal value) {
this.ttlNetNtryAmt = value;
}
/**
* Gets the value of the cdtDbtInd property.
*
* @return
* possible object is
* {@link CreditDebitCode }
*
*/
public CreditDebitCode getCdtDbtInd() {
return cdtDbtInd;
}
/**
* Sets the value of the cdtDbtInd property.
*
* @param value
* allowed object is
* {@link CreditDebitCode }
*
*/
public void setCdtDbtInd(CreditDebitCode value) {
this.cdtDbtInd = value;
}
/**
* Gets the value of the fcstInd property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isFcstInd() {
return fcstInd;
}
/**
* Sets the value of the fcstInd property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setFcstInd(Boolean value) {
this.fcstInd = value;
}
/**
* Gets the value of the bkTxCd property.
*
* @return
* possible object is
* {@link BankTransactionCodeStructure4 }
*
*/ | public BankTransactionCodeStructure4 getBkTxCd() {
return bkTxCd;
}
/**
* Sets the value of the bkTxCd property.
*
* @param value
* allowed object is
* {@link BankTransactionCodeStructure4 }
*
*/
public void setBkTxCd(BankTransactionCodeStructure4 value) {
this.bkTxCd = value;
}
/**
* Gets the value of the avlbty 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 avlbty property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAvlbty().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CashBalanceAvailability2 }
*
*
*/
public List<CashBalanceAvailability2> getAvlbty() {
if (avlbty == null) {
avlbty = new ArrayList<CashBalanceAvailability2>();
}
return this.avlbty;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TotalsPerBankTransactionCode2.java | 1 |
请完成以下Java代码 | public void setHeader(final String header)
{
this.header = header;
}
private void setHeader(final String adLanguage, final String headerTrl)
{
Check.assumeNotEmpty(adLanguage, "adLanguage is not empty");
if (headerTrl == null)
{
return;
}
if (headerTrls == null)
{
headerTrls = new HashMap<>();
}
headerTrls.put(adLanguage, headerTrl);
}
public void setDescription(final String description)
{
this.description = description;
}
private void setDescription(final String adLanguage, final String descriptionTrl)
{
Check.assumeNotEmpty(adLanguage, "adLanguage is not empty");
if (descriptionTrl == null)
{
return;
}
if (descriptionTrls == null)
{
descriptionTrls = new HashMap<>();
}
descriptionTrls.put(adLanguage, descriptionTrl);
}
public void setHelp(final String help)
{
this.help = help;
}
private void setHelp(final String adLanguage, final String helpTrl)
{
Check.assumeNotEmpty(adLanguage, "adLanguage is not empty");
if (helpTrls == null)
{
helpTrls = new HashMap<>();
}
helpTrls.put(adLanguage, helpTrl);
}
@Nullable
public ReferenceId getAD_Reference_Value_ID()
{
return AD_Reference_Value_ID;
}
/**
* Get Column Name or SQL .. with/without AS
*
* @param withAS include AS ColumnName for virtual columns in select statements
* @return column name
*/
public String getColumnSQL(final boolean withAS)
{
// metas
if (ColumnClass != null)
{
return "NULL";
}
// metas end | if (ColumnSQL != null && !ColumnSQL.isEmpty())
{
if (withAS)
{
return ColumnSQL + " AS " + ColumnName;
}
else
{
return ColumnSQL;
}
}
return ColumnName;
} // getColumnSQL
public ColumnSql getColumnSql(@NonNull final String ctxTableName)
{
return ColumnSql.ofSql(getColumnSQL(false), ctxTableName);
}
/**
* Is Virtual Column
*
* @return column is virtual
*/
public boolean isVirtualColumn()
{
return (ColumnSQL != null && !ColumnSQL.isEmpty())
|| (ColumnClass != null && !ColumnClass.isEmpty());
} // isColumnVirtual
public boolean isReadOnly()
{
return IsReadOnly;
}
public boolean isUpdateable()
{
return IsUpdateable;
}
public boolean isAlwaysUpdateable()
{
return IsAlwaysUpdateable;
}
public boolean isKey()
{
return IsKey;
}
public boolean isEncryptedField()
{
return IsEncryptedField;
}
public boolean isEncryptedColumn()
{
return IsEncryptedColumn;
}
public boolean isSelectionColumn()
{
return defaultFilterDescriptor != null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridFieldVO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void deleteCorrespondingFailedRecordIfExists(@NonNull final ExternalId externalId)
{
failedTimeBookingRepository.getOptionalByExternalIdAndSystem(externalId.getExternalSystem(), externalId.getId())
.ifPresent(failedTimeBooking -> failedTimeBookingRepository.delete(failedTimeBooking.getFailedTimeBookingId()));
}
private void extractAndPropagateAdempiereException(final CompletableFuture completableFuture)
{
try
{
completableFuture.get();
}
catch (final ExecutionException ex)
{
throw AdempiereException.wrapIfNeeded(ex.getCause());
}
catch (final InterruptedException ex1)
{
throw AdempiereException.wrapIfNeeded(ex1);
}
}
private void checkIfTheEffortCanBeBooked(@NonNull final ImportTimeBookingInfo importTimeBookingInfo, @NonNull final IssueEntity targetIssue)
{
if (!targetIssue.isProcessed() || targetIssue.getProcessedTimestamp() == null)
{
return;//nothing else to check ( issues that are not processed yet are used for booking effort )
}
final LocalDate effortBookedDate = TimeUtil.asLocalDate(importTimeBookingInfo.getBookedDate());
final LocalDate processedIssueDate = TimeUtil.asLocalDate(targetIssue.getProcessedTimestamp());
final boolean effortWasBookedOnAProcessedIssue = effortBookedDate.isAfter(processedIssueDate);
if (effortWasBookedOnAProcessedIssue)
{
final I_AD_User performingUser = userDAO.getById(importTimeBookingInfo.getPerformingUserId()); | throw new AdempiereException("Time bookings cannot be added for already processed issues!")
.appendParametersToMessage()
.setParameter("ImportTimeBookingInfo", importTimeBookingInfo)
.setParameter("Performing user", performingUser.getName())
.setParameter("Note", "This FailedTimeBooking record will not be automatically deleted!");
}
}
private void storeFailed(
@NonNull final OrgId orgId,
@NonNull final ImportTimeBookingInfo importTimeBookingInfo,
@NonNull final String errorMsg)
{
final FailedTimeBooking failedTimeBooking = FailedTimeBooking.builder()
.orgId(orgId)
.externalId(importTimeBookingInfo.getExternalTimeBookingId().getId())
.externalSystem(importTimeBookingInfo.getExternalTimeBookingId().getExternalSystem())
.errorMsg(errorMsg)
.build();
failedTimeBookingRepository.save(failedTimeBooking);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\timebooking\importer\TimeBookingsImporterService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public boolean isRunning() {
this.lifecycleLock.lock();
try {
return this.running;
}
finally {
this.lifecycleLock.unlock();
}
}
@Override
public void afterSingletonsInstantiated() {
try {
this.topology = getObject().build(this.properties);
this.infrastructureCustomizer.configureTopology(this.topology);
TopologyDescription description = this.topology.describe();
LOGGER.debug(description::toString);
}
catch (Exception e) {
throw new RuntimeException(e);
}
}
private StreamsBuilder createStreamBuilder() {
if (this.properties == null) {
return new StreamsBuilder();
}
else {
StreamsConfig streamsConfig = new StreamsConfig(this.properties);
TopologyConfig topologyConfig = new TopologyConfig(streamsConfig);
return new StreamsBuilder(topologyConfig);
}
}
/** | * Called whenever a {@link KafkaStreams} is added or removed.
*
* @since 2.5.3
*
*/
public interface Listener {
/**
* A new {@link KafkaStreams} was created.
* @param id the streams id (factory bean name).
* @param streams the streams;
*/
default void streamsAdded(String id, KafkaStreams streams) {
}
/**
* An existing {@link KafkaStreams} was removed.
* @param id the streams id (factory bean name).
* @param streams the streams;
*/
default void streamsRemoved(String id, KafkaStreams streams) {
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\config\StreamsBuilderFactoryBean.java | 2 |
请完成以下Java代码 | public Message postProcessMessage(Message message) throws AmqpException {
try {
ByteArrayOutputStream zipped = new ByteArrayOutputStream();
OutputStream zipper = getCompressorStream(zipped);
FileCopyUtils.copy(new ByteArrayInputStream(message.getBody()), zipper);
byte[] compressed = zipped.toByteArray();
if (this.logger.isTraceEnabled()) {
this.logger.trace("Compressed " + message.getBody().length + " to " + compressed.length);
}
MessageProperties originalProperties = message.getMessageProperties();
MessagePropertiesBuilder messagePropertiesBuilder =
this.copyProperties
? MessagePropertiesBuilder.fromClonedProperties(originalProperties)
: MessagePropertiesBuilder.fromProperties(originalProperties);
if (this.autoDecompress) {
messagePropertiesBuilder.setHeader(MessageProperties.SPRING_AUTO_DECOMPRESS, true);
}
MessageProperties messageProperties =
messagePropertiesBuilder.setContentEncoding(getEncoding() +
(!StringUtils.hasText(originalProperties.getContentEncoding())
? ""
: this.encodingDelimiter + originalProperties.getContentEncoding()))
.build();
return new Message(compressed, messageProperties);
}
catch (IOException e) {
throw new AmqpIOException(e);
}
} | @Override
public int getOrder() {
return this.order;
}
/**
* Set the order.
* @param order the order, default 0.
* @see Ordered
*/
protected void setOrder(int order) {
this.order = order;
}
/**
* Get the stream.
* @param stream The output stream to write the compressed data to.
* @return the compressor output stream.
* @throws IOException IOException
*/
protected abstract OutputStream getCompressorStream(OutputStream stream) throws IOException;
/**
* Get the encoding.
* @return the content-encoding header.
*/
protected abstract String getEncoding();
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\support\postprocessor\AbstractCompressingPostProcessor.java | 1 |
请完成以下Java代码 | public void setELContext(ELContext context) {
this.context = context;
}
@SuppressWarnings("null") // args[i] can't be null due to earlier checks
public Object invoke(ELContext context, Object... args) throws ELException {
Objects.requireNonNull(context, "context is null");
int formalParamCount = 0;
if (formalParameters != null) {
formalParamCount = formalParameters.size();
}
int argCount = 0;
if (args != null) {
argCount = args.length;
}
if (formalParamCount > argCount) {
throw new ELException("Only '" + argCount + "' arguments were provided for a lambda expression that requires at least '" + formalParamCount + "''");
}
// Build the argument map
// Start with the arguments from any outer expressions so if there is
// any overlap the local arguments have priority
Map<String, Object> lambdaArguments = new HashMap<>(nestedArguments);
for (int i = 0; i < formalParamCount; i++) {
lambdaArguments.put(formalParameters.get(i), args[i]);
} | context.enterLambdaScope(lambdaArguments);
try {
Object result = expression.getValue(context);
// Make arguments from this expression available to any nested
// expression
if (result instanceof LambdaExpression) {
((LambdaExpression) result).nestedArguments.putAll(lambdaArguments);
}
return result;
} finally {
context.exitLambdaScope();
}
}
public Object invoke(Object... args) {
return invoke(context, args);
}
public List<String> getFormalParameters() {
return formalParameters;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\LambdaExpression.java | 1 |
请完成以下Java代码 | private int endIndexSearch(int[] sortedArray, int target) {
int left = 0;
int right = sortedArray.length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (sortedArray[mid] == target) {
result = mid;
left = mid + 1;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
} | private int startIndexSearch(int[] sortedArray, int target) {
int left = 0;
int right = sortedArray.length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (sortedArray[mid] == target) {
result = mid;
right = mid - 1;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\binarysearch\BinarySearch.java | 1 |
请完成以下Java代码 | public static void main(String[] args) throws IOException {
// Test readGZipFile method
List<String> fileContents = readGZipFile(filePath);
System.out.println("Contents of GZIP file:");
fileContents.forEach(System.out::println);
// Test findInZipFile method
String searchTerm = "Line 1 content";
List<String> foundLines = findInZipFile(filePath, searchTerm);
System.out.println("Lines containing '" + searchTerm + "' in GZIP file:");
foundLines.forEach(System.out::println);
// Test useContentsOfZipFile method
System.out.println("Using contents of GZIP file with consumer:");
useContentsOfZipFile(filePath, linesStream -> {
linesStream.filter(line -> line.length() > 10).forEach(System.out::println);
});
}
public static List<String> readGZipFile(String filePath) throws IOException {
List<String> lines = new ArrayList<>();
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
String line;
while ((line = bufferedReader.readLine()) != null) {
lines.add(line);
} | }
return lines;
}
public static List<String> findInZipFile(String filePath, String toFind) throws IOException {
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
return bufferedReader.lines().filter(line -> line.contains(toFind)).collect(toList());
}
}
public static void useContentsOfZipFile(String filePath, Consumer<Stream<String>> consumer) throws IOException {
try (InputStream inputStream = new FileInputStream(filePath);
GZIPInputStream gzipInputStream = new GZIPInputStream(inputStream);
InputStreamReader inputStreamReader = new InputStreamReader(gzipInputStream);
BufferedReader bufferedReader = new BufferedReader(inputStreamReader)) {
consumer.accept(bufferedReader.lines());
}
}
} | repos\tutorials-master\core-java-modules\core-java-io-5\src\main\java\com\baeldung\usinggzipInputstream\Main.java | 1 |
请完成以下Java代码 | public void setMethod (final @Nullable java.lang.String Method)
{
set_Value (COLUMNNAME_Method, Method);
}
@Override
public java.lang.String getMethod()
{
return get_ValueAsString(COLUMNNAME_Method);
}
@Override
public void setPath (final @Nullable java.lang.String Path)
{
set_Value (COLUMNNAME_Path, Path);
}
@Override
public java.lang.String getPath()
{
return get_ValueAsString(COLUMNNAME_Path);
}
@Override
public void setRemoteAddr (final @Nullable java.lang.String RemoteAddr)
{
set_Value (COLUMNNAME_RemoteAddr, RemoteAddr);
}
@Override
public java.lang.String getRemoteAddr()
{
return get_ValueAsString(COLUMNNAME_RemoteAddr);
}
@Override
public void setRemoteHost (final @Nullable java.lang.String RemoteHost)
{
set_Value (COLUMNNAME_RemoteHost, RemoteHost);
}
@Override
public java.lang.String getRemoteHost()
{
return get_ValueAsString(COLUMNNAME_RemoteHost);
}
@Override
public void setRequestURI (final @Nullable java.lang.String RequestURI)
{
set_Value (COLUMNNAME_RequestURI, RequestURI);
}
@Override
public java.lang.String getRequestURI()
{
return get_ValueAsString(COLUMNNAME_RequestURI);
}
/**
* Status AD_Reference_ID=541316
* Reference name: StatusList
*/
public static final int STATUS_AD_Reference_ID=541316;
/** Empfangen = Empfangen */
public static final String STATUS_Empfangen = "Empfangen";
/** Verarbeitet = Verarbeitet */
public static final String STATUS_Verarbeitet = "Verarbeitet";
/** Fehler = Fehler */
public static final String STATUS_Fehler = "Fehler"; | @Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
@Override
public void setTime (final java.sql.Timestamp Time)
{
set_Value (COLUMNNAME_Time, Time);
}
@Override
public java.sql.Timestamp getTime()
{
return get_ValueAsTimestamp(COLUMNNAME_Time);
}
@Override
public void setUI_Trace_ExternalId (final @Nullable java.lang.String UI_Trace_ExternalId)
{
set_Value (COLUMNNAME_UI_Trace_ExternalId, UI_Trace_ExternalId);
}
@Override
public java.lang.String getUI_Trace_ExternalId()
{
return get_ValueAsString(COLUMNNAME_UI_Trace_ExternalId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Request_Audit.java | 1 |
请完成以下Java代码 | public class ClaimTaskPayload implements Payload {
private String id;
private String taskId;
private String assignee;
public ClaimTaskPayload() {
this.id = UUID.randomUUID().toString();
}
public ClaimTaskPayload(String taskId, String assignee) {
this();
this.taskId = taskId;
this.assignee = assignee;
}
@Override
public String getId() {
return id; | }
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
} | repos\Activiti-develop\activiti-api\activiti-api-task-model\src\main\java\org\activiti\api\task\model\payloads\ClaimTaskPayload.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public User userDTOToUser(UserDTO userDTO) {
if (userDTO == null) {
return null;
} else {
User user = new User();
user.setId(userDTO.getId());
user.setLogin(userDTO.getLogin());
user.setFirstName(userDTO.getFirstName());
user.setLastName(userDTO.getLastName());
user.setEmail(userDTO.getEmail());
user.setImageUrl(userDTO.getImageUrl());
user.setActivated(userDTO.isActivated());
user.setLangKey(userDTO.getLangKey());
Set<Authority> authorities = this.authoritiesFromStrings(userDTO.getAuthorities());
user.setAuthorities(authorities);
return user;
}
}
private Set<Authority> authoritiesFromStrings(Set<String> authoritiesAsString) {
Set<Authority> authorities = new HashSet<>();
if(authoritiesAsString != null){
authorities = authoritiesAsString.stream().map(string -> {
Authority auth = new Authority();
auth.setName(string);
return auth; | }).collect(Collectors.toSet());
}
return authorities;
}
public User userFromId(Long id) {
if (id == null) {
return null;
}
User user = new User();
user.setId(id);
return user;
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\mapper\UserMapper.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getExportFilePrefix()
{
return exportFilePrefix;
}
@Override
public I_AD_User getFrom()
{
return from;
}
/**
* @return <code>null</code>
*/
@Override
public String getMessage()
{
return MESSAGE;
}
/**
* @return the title of the process
*/
@Override | public String getSubject()
{
return subject;
}
/**
* @return the title of the process
*/
@Override
public String getTitle()
{
return title;
}
@Override
public String getTo()
{
return to;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\report\email\service\impl\BPartnerEmailParams.java | 2 |
请完成以下Java代码 | private static String getIndexByCode(String roleCode) {
for (RoleIndexConfigEnum e : RoleIndexConfigEnum.values()) {
if (e.roleCode.equals(roleCode)) {
return e.componentUrl;
}
}
return null;
}
public static String getIndexByRoles(List<String> roles) {
String[] rolesArray = roles.toArray(new String[roles.size()]);
for (RoleIndexConfigEnum e : RoleIndexConfigEnum.values()) {
if (oConvertUtils.isIn(e.roleCode,rolesArray)){
return e.componentUrl;
}
}
return null;
}
public String getRoleCode() { | return roleCode;
}
public void setRoleCode(String roleCode) {
this.roleCode = roleCode;
}
public String getComponentUrl() {
return componentUrl;
}
public void setComponentUrl(String componentUrl) {
this.componentUrl = componentUrl;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\constant\enums\RoleIndexConfigEnum.java | 1 |
请完成以下Java代码 | public List<String> shortcutFieldOrder() {
return Arrays.asList("defaultLocale");
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
if (exchange.getRequest()
.getHeaders()
.getAcceptLanguage()
.isEmpty()) {
String queryParamLocale = exchange.getRequest()
.getQueryParams()
.getFirst("locale");
Locale requestLocale = Optional.ofNullable(queryParamLocale)
.map(l -> Locale.forLanguageTag(l))
.orElse(config.getDefaultLocale());
exchange.getRequest()
.mutate()
.headers(h -> h.setAcceptLanguageAsLocales(Collections.singletonList(requestLocale)));
}
String allOutgoingRequestLanguages = exchange.getRequest()
.getHeaders()
.getAcceptLanguage()
.stream()
.map(range -> range.getRange())
.collect(Collectors.joining(","));
logger.info("Modify request output - Request contains Accept-Language header: {}", allOutgoingRequestLanguages);
ServerWebExchange modifiedExchange = exchange.mutate()
.request(originalRequest -> originalRequest.uri(UriComponentsBuilder.fromUri(exchange.getRequest()
.getURI()) | .replaceQueryParams(new LinkedMultiValueMap<String, String>())
.build()
.toUri()))
.build();
logger.info("Removed all query params: {}", modifiedExchange.getRequest()
.getURI());
return chain.filter(modifiedExchange);
};
}
public static class Config {
private Locale defaultLocale;
public Config() {
}
public Locale getDefaultLocale() {
return defaultLocale;
}
public void setDefaultLocale(String defaultLocale) {
this.defaultLocale = Locale.forLanguageTag(defaultLocale);
};
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\ModifyRequestGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public class PdfEditor {
private static final String SOURCE = "src/main/resources/baeldung.pdf";
private static final String DESTINATION = "src/main/resources/baeldung-modified.pdf";
public static void main(String[] args) throws IOException {
PdfReader reader = new PdfReader(SOURCE);
PdfWriter writer = new PdfWriter(DESTINATION);
PdfDocument pdfDocument = new PdfDocument(reader, writer);
addContentToDocument(pdfDocument);
}
private static void addContentToDocument(PdfDocument pdfDocument) throws MalformedURLException {
// 4.1. add form
PdfFormField personal = PdfFormField.createEmptyField(pdfDocument);
personal.setFieldName("information");
PdfTextFormField name = PdfFormField.createText(pdfDocument, new Rectangle(35, 400, 100, 30), "name", "");
personal.addKid(name);
PdfAcroForm.getAcroForm(pdfDocument, true)
.addField(personal, pdfDocument.getFirstPage());
// 4.2. add new page
pdfDocument.addNewPage(1);
// 4.3. add annotation
PdfAnnotation ann = new PdfTextAnnotation(new Rectangle(40, 435, 0, 0)).setTitle(new PdfString("name"))
.setContents("Your name");
pdfDocument.getPage(2)
.addAnnotation(ann);
// create document form pdf document
Document document = new Document(pdfDocument);
// 4.4. add an image
ImageData imageData = ImageDataFactory.create("src/main/resources/baeldung.png");
Image image = new Image(imageData).scaleAbsolute(550, 100)
.setFixedPosition(1, 10, 50);
document.add(image); | // 4.5. add a paragraph
Text title = new Text("This is a demo").setFontSize(16);
Text author = new Text("Baeldung tutorials.");
Paragraph p = new Paragraph().setFontSize(8)
.add(title)
.add(" from ")
.add(author);
document.add(p);
// 4.6. add a table
Table table = new Table(UnitValue.createPercentArray(2));
table.addHeaderCell("#");
table.addHeaderCell("company");
table.addCell("name");
table.addCell("baeldung");
document.add(table);
// close the document
// this automatically closes the pdfDocument, which then closes automatically the pdfReader and pdfWriter
document.close();
}
} | repos\tutorials-master\text-processing-libraries-modules\pdf-2\src\main\java\com\baeldung\pdfedition\PdfEditor.java | 1 |
请完成以下Java代码 | public void setUserDetailsPasswordService(ReactiveUserDetailsPasswordService userDetailsPasswordService) {
Assert.notNull(userDetailsPasswordService, "userDetailsPasswordService cannot be null");
this.userDetailsPasswordService = userDetailsPasswordService;
}
/**
* Sets the strategy which will be used to validate the loaded <tt>UserDetails</tt>
* object after authentication occurs.
* @param postAuthenticationChecks The {@link UserDetailsChecker}
* @since 5.2
*/
public void setPostAuthenticationChecks(UserDetailsChecker postAuthenticationChecks) {
Assert.notNull(this.postAuthenticationChecks, "postAuthenticationChecks cannot be null");
this.postAuthenticationChecks = postAuthenticationChecks;
}
/**
* @since 5.5
*/
@Override
public void setMessageSource(MessageSource messageSource) {
Assert.notNull(messageSource, "messageSource cannot be null"); | this.messages = new MessageSourceAccessor(messageSource);
}
/**
* Sets the {@link ReactiveCompromisedPasswordChecker} to be used before creating a
* successful authentication. Defaults to {@code null}.
* @param compromisedPasswordChecker the {@link CompromisedPasswordChecker} to use
* @since 6.3
*/
public void setCompromisedPasswordChecker(ReactiveCompromisedPasswordChecker compromisedPasswordChecker) {
this.compromisedPasswordChecker = compromisedPasswordChecker;
}
/**
* Allows subclasses to retrieve the <code>UserDetails</code> from an
* implementation-specific location.
* @param username The username to retrieve
* @return the user information. If authentication fails, a Mono error is returned.
*/
protected abstract Mono<UserDetails> retrieveUser(String username);
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authentication\AbstractUserDetailsReactiveAuthenticationManager.java | 1 |
请完成以下Java代码 | public class X_T_Query_Selection_ToDelete extends org.compiere.model.PO implements I_T_Query_Selection_ToDelete, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1105719445L;
/** Standard Constructor */
public X_T_Query_Selection_ToDelete (Properties ctx, int T_Query_Selection_ToDelete_ID, String trxName)
{
super (ctx, T_Query_Selection_ToDelete_ID, trxName);
}
/** Load Constructor */
public X_T_Query_Selection_ToDelete (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setExecutor_UUID (java.lang.String Executor_UUID)
{
set_Value (COLUMNNAME_Executor_UUID, Executor_UUID);
}
@Override
public java.lang.String getExecutor_UUID()
{
return (java.lang.String)get_Value(COLUMNNAME_Executor_UUID);
} | @Override
public void setT_Query_Selection_ToDelete_ID (int T_Query_Selection_ToDelete_ID)
{
if (T_Query_Selection_ToDelete_ID < 1)
set_ValueNoCheck (COLUMNNAME_T_Query_Selection_ToDelete_ID, null);
else
set_ValueNoCheck (COLUMNNAME_T_Query_Selection_ToDelete_ID, Integer.valueOf(T_Query_Selection_ToDelete_ID));
}
@Override
public int getT_Query_Selection_ToDelete_ID()
{
return get_ValueAsInt(COLUMNNAME_T_Query_Selection_ToDelete_ID);
}
@Override
public void setUUID (java.lang.String UUID)
{
set_ValueNoCheck (COLUMNNAME_UUID, 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_ToDelete.java | 1 |
请完成以下Java代码 | public class TestSourceCodeProjectContributor<T extends TypeDeclaration, C extends CompilationUnit<T>, S extends SourceCode<T, C>>
implements ProjectContributor {
private final ProjectDescription description;
private final Supplier<S> sourceFactory;
private final SourceCodeWriter<S> sourceWriter;
private final ObjectProvider<TestApplicationTypeCustomizer<?>> testApplicationTypeCustomizers;
private final ObjectProvider<TestSourceCodeCustomizer<?, ?, ?>> testSourceCodeCustomizers;
public TestSourceCodeProjectContributor(ProjectDescription description, Supplier<S> sourceFactory,
SourceCodeWriter<S> sourceWriter,
ObjectProvider<TestApplicationTypeCustomizer<?>> testApplicationTypeCustomizers,
ObjectProvider<TestSourceCodeCustomizer<?, ?, ?>> testSourceCodeCustomizers) {
this.description = description;
this.sourceFactory = sourceFactory;
this.sourceWriter = sourceWriter;
this.testApplicationTypeCustomizers = testApplicationTypeCustomizers;
this.testSourceCodeCustomizers = testSourceCodeCustomizers;
}
@Override
public void contribute(Path projectRoot) throws IOException {
S sourceCode = this.sourceFactory.get();
String testName = this.description.getApplicationName() + "Tests";
C compilationUnit = sourceCode.createCompilationUnit(this.description.getPackageName(), testName); | T testApplicationType = compilationUnit.createTypeDeclaration(testName);
customizeTestApplicationType(testApplicationType);
customizeTestSourceCode(sourceCode);
this.sourceWriter.writeTo(
this.description.getBuildSystem().getTestSource(projectRoot, this.description.getLanguage()),
sourceCode);
}
@SuppressWarnings("unchecked")
private void customizeTestApplicationType(TypeDeclaration testApplicationType) {
List<TestApplicationTypeCustomizer<?>> customizers = this.testApplicationTypeCustomizers.orderedStream()
.collect(Collectors.toList());
LambdaSafe.callbacks(TestApplicationTypeCustomizer.class, customizers, testApplicationType)
.invoke((customizer) -> customizer.customize(testApplicationType));
}
@SuppressWarnings("unchecked")
private void customizeTestSourceCode(S sourceCode) {
List<TestSourceCodeCustomizer<?, ?, ?>> customizers = this.testSourceCodeCustomizers.orderedStream()
.collect(Collectors.toList());
LambdaSafe.callbacks(TestSourceCodeCustomizer.class, customizers, sourceCode)
.invoke((customizer) -> customizer.customize(sourceCode));
}
} | repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\TestSourceCodeProjectContributor.java | 1 |
请完成以下Java代码 | public String getX12DE355(@NonNull final UomId uomId)
{
final I_C_UOM uom = uomsRepo.getById(uomId);
return uom.getX12DE355();
}
public List<I_C_BPartner_Product> getBPartnerProductRecords(final Set<ProductId> productIds)
{
return partnerProductsRepo.retrieveForProductIds(productIds);
}
public List<I_M_HU_PI_Item_Product> getMHUPIItemProductRecords(final Set<ProductId> productIds)
{
return huPIItemProductDAO.retrieveAllForProducts(productIds);
}
public List<UOMConversionsMap> getProductUOMConversions(final Set<ProductId> productIds)
{
if (productIds.isEmpty())
{
return ImmutableList.of();
}
return productIds.stream().map(uomConversionDAO::getProductConversions).collect(ImmutableList.toImmutableList());
}
public Stream<I_M_Product_Category> streamAllProductCategories()
{
return productsRepo.streamAllProductCategories();
}
public List<I_C_BPartner> getPartnerRecords(@NonNull final ImmutableSet<BPartnerId> manufacturerIds) | {
return queryBL.createQueryBuilder(I_C_BPartner.class)
.addInArrayFilter(I_C_BPartner.COLUMN_C_BPartner_ID, manufacturerIds)
.create()
.list();
}
@NonNull
public JsonCreatedUpdatedInfo extractCreatedUpdatedInfo(@NonNull final I_M_Product_Category record)
{
final ZoneId orgZoneId = orgDAO.getTimeZone(OrgId.ofRepoId(record.getAD_Org_ID()));
return JsonCreatedUpdatedInfo.builder()
.created(TimeUtil.asZonedDateTime(record.getCreated(), orgZoneId))
.createdBy(UserId.optionalOfRepoId(record.getCreatedBy()).orElse(UserId.SYSTEM))
.updated(TimeUtil.asZonedDateTime(record.getUpdated(), orgZoneId))
.updatedBy(UserId.optionalOfRepoId(record.getUpdatedBy()).orElse(UserId.SYSTEM))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\product\ProductsServicesFacade.java | 1 |
请完成以下Java代码 | public int getC_PaymentTerm_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_PaymentTerm_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Rechnungsdatum.
@param DateInvoiced
Datum auf der Rechnung
*/
@Override
public void setDateInvoiced (java.sql.Timestamp DateInvoiced)
{
set_Value (COLUMNNAME_DateInvoiced, DateInvoiced);
}
/** Get Rechnungsdatum.
@return Datum auf der Rechnung
*/
@Override
public java.sql.Timestamp getDateInvoiced ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateInvoiced);
}
/** Set Datum Fälligkeit.
@param DueDate
Datum, zu dem Zahlung fällig wird
*/
@Override
public void setDueDate (java.sql.Timestamp DueDate)
{
set_Value (COLUMNNAME_DueDate, DueDate);
}
/** Get Datum Fälligkeit.
@return Datum, zu dem Zahlung fällig wird
*/
@Override
public java.sql.Timestamp getDueDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DueDate);
}
/** Set Dunning Grace Date.
@param DunningGrace Dunning Grace Date */
@Override
public void setDunningGrace (java.sql.Timestamp DunningGrace)
{
set_Value (COLUMNNAME_DunningGrace, DunningGrace);
}
/** Get Dunning Grace Date.
@return Dunning Grace Date */
@Override
public java.sql.Timestamp getDunningGrace ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DunningGrace);
}
/** Set Summe Gesamt.
@param GrandTotal
Summe über Alles zu diesem Beleg | */
@Override
public void setGrandTotal (java.math.BigDecimal GrandTotal)
{
set_Value (COLUMNNAME_GrandTotal, GrandTotal);
}
/** Get Summe Gesamt.
@return Summe über Alles zu diesem Beleg
*/
@Override
public java.math.BigDecimal getGrandTotal ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrandTotal);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set In Dispute.
@param IsInDispute
Document is in dispute
*/
@Override
public void setIsInDispute (boolean IsInDispute)
{
set_Value (COLUMNNAME_IsInDispute, Boolean.valueOf(IsInDispute));
}
/** Get In Dispute.
@return Document is in dispute
*/
@Override
public boolean isInDispute ()
{
Object oo = get_Value(COLUMNNAME_IsInDispute);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Offener Betrag.
@param OpenAmt Offener Betrag */
@Override
public void setOpenAmt (java.math.BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Offener Betrag.
@return Offener Betrag */
@Override
public java.math.BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_Dunning_Candidate_Invoice_v1.java | 1 |
请完成以下Java代码 | public void run() {
System.out.println(Thread.currentThread().getName() + "初始化任务开始。。。。。。");
try {
sleep(5);
} finally {
countDownLatch.countDown();
}
sleep(5);
System.out.println(Thread.currentThread().getName() + "初始化任务完毕后,处理业务逻辑。。。。。。");
}
}
/**
* 一个线程两个扣减点
*/
static class InitWoerk implements Runnable {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "初始化工作开始第一步》》》》》");
try {
sleep(5);
} finally {
countDownLatch.countDown();
}
System.out.println(Thread.currentThread().getName() + "初始化工作开始第二步》》》》》");
try {
sleep(5);
} finally {
countDownLatch.countDown();
}
System.out.println(Thread.currentThread().getName() + "初始化工作处理业务逻辑》》》》》");
}
}
/**
* 业务线程
*/
static class BusinessWoerk implements Runnable { | @Override
public void run() {
try {
System.out.println(Thread.currentThread().getName() + "初始化线程还未完成,业务线程阻塞----------");
countDownLatch.await(1, TimeUnit.MINUTES);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + "初始化工作完成业务线程开始工作----------");
System.out.println(Thread.currentThread().getName() + "初始化工作完成业务线程开始工作----------");
System.out.println(Thread.currentThread().getName() + "初始化工作完成业务线程开始工作----------");
System.out.println(Thread.currentThread().getName() + "初始化工作完成业务线程开始工作----------");
}
}
private static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} | repos\spring-boot-student-master\spring-boot-student-concurrent\src\main\java\com\xiaolyuh\CountDownLatchTest.java | 1 |
请完成以下Java代码 | private PackageableRow createPackageableRow(final PackageableList packageables)
{
Check.assume(!packageables.isEmpty(), "packageables is not empty");
final BPartnerId customerId = packageables.getSingleCustomerId().get();
final LookupValue customer = Objects.requireNonNull(bpartnerLookup.get().findById(customerId));
final WarehouseTypeId warehouseTypeId = packageables.getSingleValue(Packageable::getWarehouseTypeId).orElse(null);
final ITranslatableString warehouseTypeName;
if (warehouseTypeId != null)
{
warehouseTypeName = warehousesRepo.getWarehouseTypeById(warehouseTypeId).getName();
}
else
{
warehouseTypeName = null;
}
final ShipperId shipperId = packageables.getSingleValue(Packageable::getShipperId).orElse(null);
final LookupValue shipper = shipperLookup.get().findById(shipperId);
final OrderId salesOrderId = packageables.getSingleValue(Packageable::getSalesOrderId).get();
final String salesOrderDocumentNo = packageables.getSingleValue(Packageable::getSalesOrderDocumentNo).get();
final String poReference = packageables.getSingleValue(Packageable::getPoReference).orElse(null);
final UserId lockedByUserId = packageables.getSingleValue(Packageable::getLockedBy).orElse(null);
final LookupValue lockedByUser = userLookup.get().findById(lockedByUserId);
final ZoneId timeZone = packageables.getSingleValue(Packageable::getOrgId).map(orgDAO::getTimeZone).get();
return PackageableRow.builder() | .orderId(salesOrderId)
.poReference(poReference)
.orderDocumentNo(salesOrderDocumentNo)
.customer(customer)
.warehouseTypeId(warehouseTypeId)
.warehouseTypeName(warehouseTypeName)
.lockedByUser(lockedByUser)
.lines(packageables.size())
.timeZone(timeZone)
.shipper(shipper)
.lineNetAmt(buildNetAmtTranslatableString(packageables))
.packageables(packageables)
.build();
}
private ITranslatableString buildNetAmtTranslatableString(final PackageableList packageables)
{
return packageables.stream()
.map(Packageable::getSalesOrderLineNetAmt)
.filter(Objects::nonNull)
.collect(Money.sumByCurrencyAndStream())
.map(moneyService::toTranslatableString)
.collect(TranslatableStrings.joining(", "));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingV2\packageable\PackageableRowsRepository.java | 1 |
请完成以下Java代码 | public void setHUAttributesDAO(final IHUAttributesDAO huAttributesDAO)
{
this.huAttributesDAO = huAttributesDAO;
for (final IAttributeStorageFactory factory : factories)
{
factory.setHUAttributesDAO(huAttributesDAO);
}
}
@Override
public IHUStorageDAO getHUStorageDAO()
{
return getHUStorageFactory().getHUStorageDAO();
}
@Override
public IHUStorageFactory getHUStorageFactory()
{
return huStorageFactory;
}
@Override | public void setHUStorageFactory(final IHUStorageFactory huStorageFactory)
{
this.huStorageFactory = huStorageFactory;
for (final IAttributeStorageFactory factory : factories)
{
factory.setHUStorageFactory(huStorageFactory);
}
}
@Override
public void flush()
{
for (final IAttributeStorageFactory factory : factories)
{
factory.flush();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\CompositeAttributeStorageFactory.java | 1 |
请完成以下Java代码 | public void releaseLock() {
executeCommand(new ReleaseLockCmd(lockName, engineType, false));
LOGGER.debug("successfully released lock {}", lockName);
hasAcquiredLock = false;
}
@Override
public void releaseAndDeleteLock() {
executeCommand(new ReleaseLockCmd(lockName, engineType, true));
LOGGER.debug("successfully released and deleted lock {}", lockName);
hasAcquiredLock = false;
}
@Override
public <T> T waitForLockRunAndRelease(Duration waitTime, Supplier<T> supplier) {
waitForLock(waitTime);
try { | return supplier.get();
} finally {
releaseLock();
}
}
protected <T> T executeCommand(Command<T> command) {
return commandExecutor.execute(lockCommandConfig, command);
}
protected Duration getLockPollRate() {
return lockPollRate;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\lock\LockManagerImpl.java | 1 |
请完成以下Java代码 | protected boolean executeShortRunning(Runnable runnable) {
try {
workManager.schedule(new CommonjWorkRunnableAdapter(runnable));
return true;
} catch (WorkRejectedException e) {
logger.log(Level.FINE, "Work rejected", e);
} catch (WorkException e) {
logger.log(Level.WARNING, "WorkException while scheduling jobs for execution", e);
}
return false;
}
protected boolean scheduleLongRunning(Runnable acquisitionRunnable) {
// initialize the workManager here, because we have access to the initial context
// of the calling thread (application), so the jndi lookup is working -> see JCA 1.6 specification
if(workManager == null) {
workManager = lookupWorkMananger();
}
try {
workManager.schedule(new CommonjDeamonWorkRunnableAdapter(acquisitionRunnable));
return true; | } catch (WorkException e) {
logger.log(Level.WARNING, "Could not schedule Job Acquisition Runnable: "+e.getMessage(), e);
return false;
}
}
public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return new JcaInflowExecuteJobsRunnable(jobIds, processEngine, ra);
}
// getters / setters ////////////////////////////////////
public WorkManager getWorkManager() {
return workManager;
}
} | repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\commonj\CommonJWorkManagerExecutorService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultGlobalExceptionHandler extends ResponseEntityExceptionHandler {
private static final Logger LOGGER = LoggerFactory.getLogger(DefaultGlobalExceptionHandler.class);
@Override
protected ResponseEntity<Object> handleExceptionInternal(Exception ex, @Nullable Object body, HttpHeaders headers, HttpStatus status, WebRequest request) {
HttpResult httpResult = HttpResult.failure(status.is5xxServerError() ? ErrorCode.serverError.getDesc() : ErrorCode.paramError.getDesc());
LOGGER.error("handleException, ex caught, contextPath={}, httpResult={}, ex.msg={}", request.getContextPath(), JSON.toJSONString(httpResult), ex.getMessage());
return super.handleExceptionInternal(ex, httpResult, headers, status, request);
}
@ExceptionHandler(Exception.class)
protected ResponseEntity handleException(HttpServletRequest request, Exception ex) {
boolean is5xxServerError;
HttpStatus httpStatus;
HttpResult httpResult;
if (ex instanceof UserFriendlyException) {
UserFriendlyException userFriendlyException = (UserFriendlyException) ex;
is5xxServerError = userFriendlyException.getHttpStatusCode() >= 500;
httpStatus = HttpStatus.valueOf(userFriendlyException.getHttpStatusCode());
httpResult = HttpResult.failure(userFriendlyException.getErrorCode(), userFriendlyException.getMessage());
} else if (ex instanceof IllegalArgumentException) {
// Spring assertions are used in parameter judgment. requireTrue will throw an IllegalArgumentException. The client cannot handle 5xx exceptions, so 200 is still returned.
httpStatus = HttpStatus.OK;
is5xxServerError = false; | httpResult = HttpResult.failure("Parameter verification error or data abnormality!");
} else {
httpStatus = HttpStatus.INTERNAL_SERVER_ERROR;
is5xxServerError = true;
httpResult = HttpResult.failure(ErrorCode.serverError.getDesc());
}
if (is5xxServerError) {
LOGGER.error("handleException, ex caught, uri={}, httpResult={}", request.getRequestURI(), JSON.toJSONString(httpResult), ex);
} else {
LOGGER.error("handleException, ex caught, uri={}, httpResult={}, ex.msg={}", request.getRequestURI(), JSON.toJSONString(httpResult), ex.getMessage());
}
return new ResponseEntity<>(httpResult, httpStatus);
}
} | repos\springboot-demo-master\Aviator\src\main\java\com\et\exception\DefaultGlobalExceptionHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void deptRoleUserAdd(String userId, String newRoleId, String oldRoleId) {
List<String> add = getDiff(oldRoleId,newRoleId);
if(add!=null && add.size()>0) {
List<SysDepartRoleUser> list = new ArrayList<>();
for (String roleId : add) {
if(oConvertUtils.isNotEmpty(roleId)) {
SysDepartRoleUser rolepms = new SysDepartRoleUser(userId, roleId);
list.add(rolepms);
}
}
this.saveBatch(list);
}
List<String> remove = getDiff(newRoleId,oldRoleId);
if(remove!=null && remove.size()>0) {
for (String roleId : remove) {
this.remove(new QueryWrapper<SysDepartRoleUser>().lambda().eq(SysDepartRoleUser::getUserId, userId).eq(SysDepartRoleUser::getDroleId, roleId));
}
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void removeDeptRoleUser(List<String> userIds, String depId) {
for(String userId : userIds){
List<SysDepartRole> sysDepartRoleList = sysDepartRoleMapper.selectList(new QueryWrapper<SysDepartRole>().eq("depart_id",depId));
List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
if(roleIds != null && roleIds.size()>0){
QueryWrapper<SysDepartRoleUser> query = new QueryWrapper<>();
query.eq("user_id",userId).in("drole_id",roleIds);
this.remove(query);
}
}
}
/** | * 从diff中找出main中没有的元素
* @param main
* @param diff
* @return
*/
private List<String> getDiff(String main, String diff){
if(oConvertUtils.isEmpty(diff)) {
return null;
}
if(oConvertUtils.isEmpty(main)) {
return Arrays.asList(diff.split(","));
}
String[] mainArr = main.split(",");
String[] diffArr = diff.split(",");
Map<String, Integer> map = new HashMap(5);
for (String string : mainArr) {
map.put(string, 1);
}
List<String> res = new ArrayList<String>();
for (String key : diffArr) {
if(oConvertUtils.isNotEmpty(key) && !map.containsKey(key)) {
res.add(key);
}
}
return res;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysDepartRoleUserServiceImpl.java | 2 |
请完成以下Java代码 | public class CorrelationUtil {
public static String getCorrelationKey(String elementName, CommandContext commandContext, ExecutionEntity executionEntity) {
return getCorrelationKey(elementName, commandContext, executionEntity.getCurrentFlowElement(), executionEntity);
}
public static String getCorrelationKey(String elementName, CommandContext commandContext, FlowElement flowElement, ExecutionEntity executionEntity) {
String correlationKey = null;
if (flowElement != null) {
List<ExtensionElement> eventCorrelations = flowElement.getExtensionElements().get(elementName);
if (eventCorrelations != null && !eventCorrelations.isEmpty()) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
ExpressionManager expressionManager = processEngineConfiguration.getExpressionManager();
Map<String, Object> correlationParameters = new HashMap<>();
for (ExtensionElement eventCorrelation : eventCorrelations) {
String name = eventCorrelation.getAttributeValue(null, "name");
String valueExpression = eventCorrelation.getAttributeValue(null, "value");
if (StringUtils.isNotEmpty(valueExpression)) { | if (executionEntity != null) {
Object value = expressionManager.createExpression(valueExpression).getValue(executionEntity);
correlationParameters.put(name, value);
} else {
correlationParameters.put(name, valueExpression);
}
} else {
correlationParameters.put(name, null);
}
}
correlationKey = CommandContextUtil.getEventRegistry().generateKey(correlationParameters);
}
}
return correlationKey;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\CorrelationUtil.java | 1 |
请完成以下Java代码 | public static String insertSeparatorEveryNCharacters(
@NonNull final String string,
@NonNull final String groupSeparator,
final int groupSize)
{
if (groupSize < 1)
{
return string;
}
final StringBuilder result = new StringBuilder(string);
int insertPosition = groupSize;
while (insertPosition < result.length())
{
result.insert(insertPosition, groupSeparator);
insertPosition += groupSize + groupSeparator.length();
}
return result.toString();
}
public static Map<String, String> parseURLQueryString(@Nullable final String query)
{
final String queryNorm = trimBlankToNull(query);
if (queryNorm == null)
{
return ImmutableMap.of();
}
final HashMap<String, String> params = new HashMap<>();
for (final String param : queryNorm.split("&"))
{
final String key;
final String value;
final int idx = param.indexOf("=");
if (idx < 0)
{
key = param;
value = null;
}
else
{
key = param.substring(0, idx);
value = param.substring(idx + 1);
}
params.put(key, value); | }
return params;
}
@Nullable
public static String ucFirst(@Nullable final String str)
{
if (str == null || str.isEmpty())
{
return str;
}
final char first = str.charAt(0);
if (!Character.isLetter(first))
{
return str;
}
final char capital = Character.toUpperCase(first);
if(first == capital)
{
return str;
}
final StringBuilder sb = new StringBuilder(str);
sb.setCharAt(0, capital);
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\StringUtils.java | 1 |
请完成以下Java代码 | public void setA_Finance_Meth (String A_Finance_Meth)
{
set_Value (COLUMNNAME_A_Finance_Meth, A_Finance_Meth);
}
/** Get Finance Method.
@return Finance Method */
public String getA_Finance_Meth ()
{
return (String)get_Value(COLUMNNAME_A_Finance_Meth);
}
/** Set Investment Credit.
@param A_Investment_CR Investment Credit */
public void setA_Investment_CR (int A_Investment_CR)
{
set_Value (COLUMNNAME_A_Investment_CR, Integer.valueOf(A_Investment_CR));
}
/** Get Investment Credit.
@return Investment Credit */
public int getA_Investment_CR ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_A_Investment_CR);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Purchased New?.
@param A_New_Used Purchased New? */
public void setA_New_Used (boolean A_New_Used)
{
set_Value (COLUMNNAME_A_New_Used, Boolean.valueOf(A_New_Used));
}
/** Get Purchased New?.
@return Purchased New? */
public boolean isA_New_Used ()
{
Object oo = get_Value(COLUMNNAME_A_New_Used);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Account State.
@param A_State
State of the Credit Card or Account holder
*/
public void setA_State (String A_State)
{
set_Value (COLUMNNAME_A_State, A_State);
}
/** Get Account State.
@return State of the Credit Card or Account holder
*/
public String getA_State ()
{
return (String)get_Value(COLUMNNAME_A_State); | }
/** Set Tax Entity.
@param A_Tax_Entity Tax Entity */
public void setA_Tax_Entity (String A_Tax_Entity)
{
set_Value (COLUMNNAME_A_Tax_Entity, A_Tax_Entity);
}
/** Get Tax Entity.
@return Tax Entity */
public String getA_Tax_Entity ()
{
return (String)get_Value(COLUMNNAME_A_Tax_Entity);
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Tax.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HUWithExpiryDatesRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
private final IHUStatusBL huStatusBL = Services.get(IHUStatusBL.class);
public Stream<HUWithExpiryDates> streamByWarnDateExceeded(@NonNull final LocalDate today)
{
final Timestamp todayTS = TimeUtil.asTimestamp(today);
return queryBL.createQueryBuilder(I_M_HU_BestBefore_V.class)
.addCompareFilter(I_M_HU_BestBefore_V.COLUMN_HU_ExpiredWarnDate, Operator.LESS_OR_EQUAL, todayTS, DateTruncQueryFilterModifier.DAY)
.addNotEqualsFilter(I_M_HU_BestBefore_V.COLUMN_HU_Expired, HUAttributeConstants.ATTR_Expired_Value_Expired)
.orderBy(I_M_HU_BestBefore_V.COLUMN_M_HU_ID)
.create()
.iterateAndStream()
.map(record -> ofRecordOrNull(record));
}
private static HUWithExpiryDates ofRecordOrNull(@Nullable final I_M_HU_BestBefore_V record)
{
if (record == null)
{
return null;
}
return HUWithExpiryDates.builder()
.huId(HuId.ofRepoId(record.getM_HU_ID()))
.bestBeforeDate(TimeUtil.asLocalDate(record.getHU_BestBeforeDate()))
.expiryWarnDate(TimeUtil.asLocalDate(record.getHU_ExpiredWarnDate()))
.build();
}
public HUWithExpiryDates getByIdIfWarnDateExceededOrNull(
@NonNull final HuId huId, | @Nullable final LocalDate expiryWarnDate)
{
final Timestamp timestamp = TimeUtil.asTimestamp(expiryWarnDate);
final I_M_HU_BestBefore_V recordOrdNull = queryBL.createQueryBuilder(I_M_HU_BestBefore_V.class)
.addCompareFilter(I_M_HU_BestBefore_V.COLUMN_HU_ExpiredWarnDate, Operator.LESS_OR_EQUAL, timestamp, DateTruncQueryFilterModifier.DAY)
.addNotEqualsFilter(I_M_HU_BestBefore_V.COLUMN_HU_Expired, HUAttributeConstants.ATTR_Expired_Value_Expired)
.addEqualsFilter(I_M_HU_BestBefore_V.COLUMN_M_HU_ID, huId)
.create()
.firstOnly(I_M_HU_BestBefore_V.class);
return ofRecordOrNull(recordOrdNull);
}
public HUWithExpiryDates getById(@NonNull final HuId huId)
{
final I_M_HU_BestBefore_V recordOrdNull = queryBL.createQueryBuilder(I_M_HU_BestBefore_V.class)
.addEqualsFilter(I_M_HU_BestBefore_V.COLUMN_M_HU_ID, huId)
.create()
.firstOnly(I_M_HU_BestBefore_V.class);
return ofRecordOrNull(recordOrdNull);
}
public Iterator<HuId> getAllWithBestBeforeDate()
{
return handlingUnitsDAO.createHUQueryBuilder()
.addOnlyWithAttributeNotNull(AttributeConstants.ATTR_BestBeforeDate)
.addHUStatusesToInclude(huStatusBL.getQtyOnHandStatuses())
.createQuery()
.iterateIds(HuId::ofRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\expiry\HUWithExpiryDatesRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public DistributionJob complete(@NonNull final DistributionJob job)
{
// just to make sure there is nothing reserved to this job
distributionJobHUReservationService.releaseAllReservations(job);
final DDOrderId ddOrderId = job.getDdOrderId();
ddOrderService.close(ddOrderId);
ddOrderService.print(ddOrderId);
return getJobById(ddOrderId);
}
public void abort(@NonNull final DistributionJob job)
{
abort().job(job).execute();
}
private DistributionJobAbortCommand.DistributionJobAbortCommandBuilder abort()
{
return DistributionJobAbortCommand.builder()
.ddOrderService(ddOrderService)
.distributionJobHUReservationService(distributionJobHUReservationService);
}
public void abortAll(@NonNull final UserId responsibleId)
{
final List<DistributionJob> jobs = newLoader().loadByQuery(DistributionJobQueries.ddOrdersAssignedToUser(responsibleId));
if (jobs.isEmpty())
{
return;
}
abort().jobs(jobs).execute();
}
public JsonGetNextEligiblePickFromLineResponse getNextEligiblePickFromLine(@NonNull final JsonGetNextEligiblePickFromLineRequest request, @NonNull final UserId callerId)
{
final DistributionJobId jobId = DistributionJobId.ofWFProcessId(request.getWfProcessId());
final DistributionJob job = getJobById(jobId);
job.assertCanEdit(callerId); | final HUQRCode huQRCode = huService.resolveHUQRCode(request.getHuQRCode());
final ProductId productId;
if (request.getProductScannedCode() != null)
{
productId = productService.getProductIdByScannedProductCode(request.getProductScannedCode());
huService.assetHUContainsProduct(huQRCode, productId);
}
else
{
productId = huService.getSingleProductId(huQRCode);
}
final DistributionJobLineId nextEligiblePickFromLineId;
if (request.getLineId() != null)
{
final DistributionJobLine line = job.getLineById(request.getLineId());
nextEligiblePickFromLineId = line.isEligibleForPicking() ? line.getId() : null;
}
else
{
nextEligiblePickFromLineId = job.getNextEligiblePickFromLineId(productId).orElse(null);
}
return JsonGetNextEligiblePickFromLineResponse.builder()
.lineId(nextEligiblePickFromLineId)
.build();
}
public void printMaterialInTransitReport(
@NonNull final UserId userId,
@NonNull final String adLanguage)
{
@NonNull final LocatorId inTransitLocatorId = warehouseService.getTrolleyByUserId(userId)
.map(LocatorQRCode::getLocatorId)
.orElseThrow(() -> new AdempiereException("No trolley found for user: " + userId));
ddOrderMoveScheduleService.printMaterialInTransitReport(inTransitLocatorId, adLanguage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionRestService.java | 2 |
请完成以下Java代码 | public Map<String, Object> setSession (HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
request.getSession().setAttribute("message", request.getRequestURL());
map.put("request Url", request.getRequestURL());
return map;
}
@RequestMapping(value = "/getSession")
public Object getSession (HttpServletRequest request){
Map<String, Object> map = new HashMap<>();
map.put("sessionId", request.getSession().getId());
map.put("message", request.getSession().getAttribute("message"));
return map;
}
@RequestMapping(value = "/index")
public String index (HttpServletRequest request){
String msg="index content";
Object user= request.getSession().getAttribute("user"); | if (user==null){
msg="please login first!";
}
return msg;
}
@RequestMapping(value = "/login")
public String login (HttpServletRequest request,String userName,String password){
String msg="logon failure!";
User user= userRepository.findByUserName(userName);
if (user!=null && user.getPassword().equals(password)){
request.getSession().setAttribute("user",user);
msg="login successful!";
}
return msg;
}
} | repos\spring-boot-leaning-master\1.x\第10课:Redis实现数据缓存和Session共享\spring-boot-redis-session\src\main\java\com\neo\web\UserController.java | 1 |
请完成以下Java代码 | public class Backtracking implements RestoreIPAddress {
public List<String> restoreIPAddresses(String s) {
List<String> result = new ArrayList<>();
backtrack(result, s, new ArrayList<>(), 0);
return result;
}
private void backtrack(List<String> result, String s, List<String> current, int index) {
if (current.size() == 4) {
if (index == s.length()) {
result.add(String.join(".", current));
}
return;
}
for (int len = 1; len <= 3; len++) {
if (index + len > s.length()) break; | String part = s.substring(index, index + len);
if (isValid(part)) {
current.add(part);
backtrack(result, s, current, index + len);
current.remove(current.size() - 1);
}
}
}
private boolean isValid(String part) {
if (part.length() > 1 && part.startsWith("0")) return false;
int num = Integer.parseInt(part);
return num >= 0 && num <= 255;
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-operations-advanced-3\src\main\java\com\baeldung\restoreipaddress\Backtracking.java | 1 |
请完成以下Java代码 | public class PersonDto {
private Long id;
private String name;
private String role;
public PersonDto(Long id, String name) {
this.id = id;
this.name = name;
}
public PersonDto(Long id, String name, String role) {
this(id, name);
this.role = role;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getRole() {
return role;
} | public void setRole(String role) {
this.role = role;
}
@Override
public int hashCode() {
return Objects.hash(id, name);
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
PersonDto other = (PersonDto) obj;
return Objects.equals(id, other.id) && Objects.equals(name, other.name);
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa-3\src\main\java\com\baeldung\hibernate\union\dto\PersonDto.java | 1 |
请完成以下Java代码 | public void setSummary (java.lang.String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
}
/** Get Zusammenfassung.
@return Textual summary of this request
*/
@Override
public java.lang.String getSummary ()
{
return (java.lang.String)get_Value(COLUMNNAME_Summary);
}
/** Set Mitteilung.
@param TextMsg
Text Message
*/ | @Override
public void setTextMsg (java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SchedulerLog.java | 1 |
请完成以下Java代码 | public void validateBTM(final I_C_BPartner partner)
{
final IMsgBL msgBL = Services.get(IMsgBL.class);
final String btm = partner.getBTM();
final boolean hasNarcoticPermission = partner.isPharmaCustomerNarcoticsPermission() || partner.isPharmaVendorNarcoticsPermission();
if (Check.isEmpty(btm))
{
if (hasNarcoticPermission)
{
throw new AdempiereException(ERR_NarcoticPermissions_Valid_BTM, partner)
.markAsUserValidationError();
} | // If the partner doesn't have permissions, BTM is not relevant.
return;
}
final boolean isValidBTM = PharmaModulo11Validator.isValid(btm);
if (!isValidBTM)
{
final ITranslatableString invalidBTMMessage = msgBL.getTranslatableMsgText(ERR_InvalidBTM, btm);
throw new AdempiereException(invalidBTMMessage)
.markAsUserValidationError();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\vertical\pharma\model\interceptor\C_BPartner.java | 1 |
请完成以下Java代码 | private @Nullable Authentication authentication(Map<String, Object> metadata) {
byte[] authenticationMetadata = (byte[]) metadata.get("authentication");
if (authenticationMetadata == null) {
return null;
}
ByteBuf rawAuthentication = ByteBufAllocator.DEFAULT.buffer();
try {
rawAuthentication.writeBytes(authenticationMetadata);
if (!AuthMetadataCodec.isWellKnownAuthType(rawAuthentication)) {
return null;
}
WellKnownAuthType wellKnownAuthType = AuthMetadataCodec.readWellKnownAuthType(rawAuthentication);
if (WellKnownAuthType.SIMPLE.equals(wellKnownAuthType)) {
return simple(rawAuthentication);
}
if (WellKnownAuthType.BEARER.equals(wellKnownAuthType)) {
return bearer(rawAuthentication);
}
throw new IllegalArgumentException("Unknown Mime Type " + wellKnownAuthType);
}
finally {
rawAuthentication.release();
}
}
private Authentication simple(ByteBuf rawAuthentication) {
ByteBuf rawUsername = AuthMetadataCodec.readUsername(rawAuthentication); | String username = rawUsername.toString(StandardCharsets.UTF_8);
ByteBuf rawPassword = AuthMetadataCodec.readPassword(rawAuthentication);
String password = rawPassword.toString(StandardCharsets.UTF_8);
return UsernamePasswordAuthenticationToken.unauthenticated(username, password);
}
private Authentication bearer(ByteBuf rawAuthentication) {
char[] rawToken = AuthMetadataCodec.readBearerTokenAsCharArray(rawAuthentication);
String token = new String(rawToken);
return new BearerTokenAuthenticationToken(token);
}
private static MetadataExtractor createDefaultExtractor() {
DefaultMetadataExtractor result = new DefaultMetadataExtractor(new ByteArrayDecoder());
result.metadataToExtract(AUTHENTICATION_MIME_TYPE, byte[].class, "authentication");
return result;
}
} | repos\spring-security-main\rsocket\src\main\java\org\springframework\security\rsocket\authentication\AuthenticationPayloadExchangeConverter.java | 1 |
请完成以下Java代码 | public boolean isAuthorizationEnabled() {
return wrappedConfiguration.isAuthorizationEnabled();
}
@Override
public String getAuthorizationCheckRevokes() {
return wrappedConfiguration.getAuthorizationCheckRevokes();
}
@Override
protected InputStream getMyBatisXmlConfigurationSteam() {
String str = buildMappings(mappingFiles);
return new ByteArrayInputStream(str.getBytes());
}
protected String buildMappings(List<String> mappingFiles) {
List<String> mappings = new ArrayList<String>(mappingFiles);
mappings.addAll(Arrays.asList(DEFAULT_MAPPING_FILES));
StringBuilder builder = new StringBuilder();
for (String mappingFile: mappings) {
builder.append(String.format("<mapper resource=\"%s\" />\n", mappingFile));
} | String mappingsFileTemplate = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"\n" +
"<!DOCTYPE configuration PUBLIC \"-//mybatis.org//DTD Config 3.0//EN\" \"http://mybatis.org/dtd/mybatis-3-config.dtd\">\n" +
"\n" +
"<configuration>\n" +
" <settings>\n" +
" <setting name=\"lazyLoadingEnabled\" value=\"false\" />\n" +
" </settings>\n" +
" <mappers>\n" +
"%s\n" +
" </mappers>\n" +
"</configuration>";
return String.format(mappingsFileTemplate, builder.toString());
}
public ProcessEngineConfigurationImpl getWrappedConfiguration() {
return wrappedConfiguration;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\db\QuerySessionFactory.java | 1 |
请完成以下Java代码 | public class ValidFromToMatchesQueryFilter<T> implements IQueryFilter<T>, ISqlQueryFilter
{
private final String validFromColumnName;
private final String validToColumnName;
private final Date dateValue;
private boolean sqlBuilt;
private String sqlWhereClause = null;
private List<Object> sqlParams = null;
public ValidFromToMatchesQueryFilter(final ModelColumn<T, ?> validFromColumn, final ModelColumn<T, ?> validToColumn, final Date dateValue)
{
super();
this.validFromColumnName = validFromColumn == null ? null : validFromColumn.getColumnName();
this.validToColumnName = validToColumn == null ? null : validToColumn.getColumnName();
this.dateValue = (Date)dateValue.clone();
}
@Override
public String getSql()
{
buildSql();
return sqlWhereClause;
}
@Override
public List<Object> getSqlParams(final Properties ctx)
{
buildSql();
return sqlParams;
}
private final void buildSql()
{
if (sqlBuilt)
{
return;
}
final StringBuilder sqlWhereClause = new StringBuilder();
final ImmutableList.Builder<Object> sqlParams = ImmutableList.builder();
// (ValidFrom IS NULL OR ValidFrom <= Date)
if (validFromColumnName != null)
{
sqlWhereClause.append("(");
sqlWhereClause.append(validFromColumnName).append(" IS NULL");
sqlWhereClause.append(" OR ").append(validFromColumnName).append(" <= ?");
sqlWhereClause.append(")");
sqlParams.add(dateValue);
}
// (ValidTo IS NULL OR ValidTo >= Date)
if (validToColumnName != null)
{
if (sqlWhereClause.length() > 0)
{
sqlWhereClause.append(" AND ");
}
sqlWhereClause.append("(");
sqlWhereClause.append(validToColumnName).append(" IS NULL");
sqlWhereClause.append(" OR ").append(validToColumnName).append(" >= ?");
sqlWhereClause.append(")");
sqlParams.add(dateValue);
}
this.sqlWhereClause = sqlWhereClause.toString(); | this.sqlParams = sqlParams.build();
this.sqlBuilt = true;
}
@Override
public boolean accept(final T model)
{
final Date validFrom = getDate(model, validFromColumnName);
if (validFrom != null && validFrom.compareTo(dateValue) > 0)
{
return false;
}
final Date validTo = getDate(model, validToColumnName);
if (validTo != null && validTo.compareTo(dateValue) < 0)
{
return false;
}
return true;
}
private final Date getDate(final T model, final String dateColumnName)
{
if (dateColumnName == null)
{
return null;
}
if (!InterfaceWrapperHelper.hasModelColumnName(model, dateColumnName))
{
return null;
}
final Optional<Date> date = InterfaceWrapperHelper.getValue(model, dateColumnName);
return date.orElse(null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\ValidFromToMatchesQueryFilter.java | 1 |
请完成以下Java代码 | public void setUserMember(String userId) {
this.userId = userId;
}
@CamundaQueryParam("groupMember")
public void setGroupMember(String groupId) {
this.groupId = groupId;
}
@CamundaQueryParam(value = "includingGroupsOfUser", converter = BooleanConverter.class)
public void setIncludingGroupsOfUser(Boolean includingGroupsOfUser) {
this.includingGroupsOfUser = includingGroupsOfUser;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected TenantQuery createNewQuery(ProcessEngine engine) {
return engine.getIdentityService().createTenantQuery();
}
@Override
protected void applyFilters(TenantQuery query) {
if (id != null) {
query.tenantId(id);
}
if (name != null) {
query.tenantName(name);
} | if (nameLike != null) {
query.tenantNameLike(nameLike);
}
if (userId != null) {
query.userMember(userId);
}
if (groupId != null) {
query.groupMember(groupId);
}
if (Boolean.TRUE.equals(includingGroupsOfUser)) {
query.includingGroupsOfUser(true);
}
}
@Override
protected void applySortBy(TenantQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) {
query.orderByTenantId();
} else if (sortBy.equals(SORT_BY_TENANT_NAME_VALUE)) {
query.orderByTenantName();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\TenantQueryDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public GetBearerRequest toGetBearerRequest()
{
return GetBearerRequest.builder()
.grantType("client_credentials")
.clientId(clientId)
.clientSecret(clientSecret)
.build();
}
public void updateBearer(@NonNull final String bearer, @NonNull final Instant validUntil)
{
this.bearer = bearer;
this.validUntil = validUntil;
}
public boolean isExpired() | {
return bearer == null || Instant.now().isAfter(validUntil);
}
@NonNull
public String getBearerNotNull()
{
if (bearer == null)
{
throw new RuntimeException("AuthToken.bearer is null!");
}
return bearer;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\api\ShopwareClient.java | 2 |
请在Spring Boot框架中完成以下Java代码 | class KafkaStreamsConfig {
@Value("${kafka.topics.iot}")
private String iotTopicName;
@Bean
public Serde<IotSensorData> iotSerde() {
return Serdes.serdeFrom(new JsonSerializer<>(), new JsonDeserializer<>(IotSensorData.class));
}
@Bean
public KStream<String, IotSensorData> iotStream(StreamsBuilder streamsBuilder) {
KStream<String, IotSensorData> stream = streamsBuilder.stream(iotTopicName, Consumed.with(Serdes.String(), iotSerde()));
stream.split()
.branch((key, value) -> value.getSensorType() != null,
Branched.withConsumer(ks -> ks.to((key, value, recordContext) -> String.format("%s_%s", iotTopicName, value.getSensorType()))))
.noDefaultBranch();
return stream;
}
@Bean | public KStream<String, IotSensorData> iotBrancher(StreamsBuilder streamsBuilder) {
KStream<String, IotSensorData> stream = streamsBuilder.stream(iotTopicName, Consumed.with(Serdes.String(), iotSerde()));
new KafkaStreamBrancher<String, IotSensorData>()
.branch((key, value) -> "temp".equals(value.getSensorType()), (ks) -> ks.to(iotTopicName + "_temp"))
.branch((key, value) -> "move".equals(value.getSensorType()), (ks) -> ks.to(iotTopicName + "_move"))
.branch((key, value) -> "hum".equals(value.getSensorType()), (ks) -> ks.to(iotTopicName + "_hum"))
.defaultBranch(ks -> ks.to(String.format("%s_unknown", iotTopicName)))
.onTopOf(stream);
return stream;
}
@Bean
public KStream<String, IotSensorData> iotTopicExtractor(StreamsBuilder streamsBuilder) {
KStream<String, IotSensorData> stream = streamsBuilder.stream(iotTopicName, Consumed.with(Serdes.String(), iotSerde()));
TopicNameExtractor<String, IotSensorData> sensorTopicExtractor = (key, value, recordContext) -> String.format("%s_%s", iotTopicName, value.getSensorType());
stream.to(sensorTopicExtractor);
return stream;
}
} | repos\tutorials-master\spring-kafka-2\src\main\java\com\baeldung\spring\kafka\kafkasplitting\KafkaStreamsConfig.java | 2 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("rfqResponsesProducerFactory", rfqResponsesProducerFactory)
.add("rfqResponsePublisher", rfqResponsePublisher)
.toString();
}
@Override
public IRfQResponseProducer newRfQResponsesProducerFor(final I_C_RfQ rfq)
{
Check.assumeNotNull(rfq, "rfq not null");
final IRfQResponseProducer producer = rfqResponsesProducerFactory.newRfQResponsesProducerFor(rfq);
if (producer != null)
{
return producer;
}
// Fallback to default producer
return new DefaultRfQResponseProducer();
}
@Override
public IRfQConfiguration addRfQResponsesProducerFactory(final IRfQResponseProducerFactory factory)
{
rfqResponsesProducerFactory.addRfQResponsesProducerFactory(factory);
return this;
}
@Override
public IRfQResponseRankingStrategy newRfQResponseRankingStrategyFor(final I_C_RfQ rfq)
{ | // TODO: implement custom providers
return new DefaultRfQResponseRankingStrategy();
}
@Override
public IRfQResponsePublisher getRfQResponsePublisher()
{
return rfqResponsePublisher;
}
@Override
public IRfQConfiguration addRfQResponsePublisher(final IRfQResponsePublisher publisher)
{
rfqResponsePublisher.addRfQResponsePublisher(publisher);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java\de\metas\rfq\impl\RfQConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public I_C_InvoiceLine createInvoiceLine(final String trxName)
{
return InterfaceWrapperHelper.create(Env.getCtx(), I_C_InvoiceLine.class, trxName);
}
@Override
public List<I_C_LandedCost> retrieveLandedCosts(
final I_C_InvoiceLine invoiceLine, final String whereClause,
final String trxName)
{
final List<I_C_LandedCost> list = new ArrayList<>();
String sql = "SELECT * FROM C_LandedCost WHERE C_InvoiceLine_ID=? ";
if (whereClause != null)
{
sql += whereClause;
}
final PreparedStatement pstmt = DB.prepareStatement(sql, trxName);
ResultSet rs = null;
try
{
pstmt.setInt(1, invoiceLine.getC_InvoiceLine_ID());
rs = pstmt.executeQuery();
while (rs.next())
{
MLandedCost lc = new MLandedCost(Env.getCtx(), rs, trxName);
list.add(lc);
}
}
catch (Exception e)
{
logger.error("getLandedCost", e);
} | finally
{
DB.close(rs, pstmt);
}
return list;
} // getLandedCost
@Override
public I_C_LandedCost createLandedCost(String trxName)
{
return new MLandedCost(Env.getCtx(), 0, trxName);
}
@Override
public List<I_C_InvoiceTax> retrieveTaxes(org.compiere.model.I_C_Invoice invoice)
{
final MInvoice invoicePO = LegacyAdapters.convertToPO(invoice);
final MInvoiceTax[] resultArray = invoicePO.getTaxes(true);
final List<I_C_InvoiceTax> result = new ArrayList<>();
for (final MInvoiceTax tax : resultArray)
{
result.add(tax);
}
// NOTE: make sure we are returning a read-write list because some API rely on this (doing sorting)
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceDAO.java | 2 |
请完成以下Java代码 | private I_M_HU_PI_Item_Product extractHUPIItemProductOrNull(@NonNull final IHUPackingAware huPackingAware)
{
final HUPIItemProductId piItemProductId = HUPIItemProductId.ofRepoIdOrNull(huPackingAware.getM_HU_PI_Item_Product_ID());
return piItemProductId != null
? piPIItemProductBL.getRecordById(piItemProductId)
: null;
}
@Override
public boolean isInfiniteCapacityTU(final IHUPackingAware huPackingAware)
{
final IHUPIItemProductBL piItemProductBL = Services.get(IHUPIItemProductBL.class);
final HUPIItemProductId piItemProductId = HUPIItemProductId.ofRepoIdOrNone(huPackingAware.getM_HU_PI_Item_Product_ID());
return piItemProductBL.isInfiniteCapacity(piItemProductId);
}
@Override
public void setQtyTUFromQtyLU(final IHUPackingAware record)
{
final BigDecimal qtyLUs = record.getQtyLU();
if (qtyLUs == null)
{
return;
}
final BigDecimal capacity = calculateLUCapacity(record);
if (capacity == null)
{
return;
}
final BigDecimal qtyTUs = qtyLUs.multiply(capacity);
record.setQtyTU(qtyTUs);
}
@Override
public void setQtyLUFromQtyTU(final IHUPackingAware record)
{
final BigDecimal qtyTUs = record.getQtyTU(); | if (qtyTUs == null)
{
return;
}
final BigDecimal capacity = calculateLUCapacity(record);
if (capacity == null)
{
return;
}
final BigDecimal qtyLUs = qtyTUs.divide(capacity, RoundingMode.UP);
record.setQtyLU(qtyLUs);
}
@Override
public void validateLUQty(final BigDecimal luQty)
{
final int maxLUQty = sysConfigBL.getIntValue(SYS_CONFIG_MAXQTYLU, SYS_CONFIG_MAXQTYLU_DEFAULT_VALUE);
if (luQty != null && luQty.compareTo(BigDecimal.valueOf(maxLUQty)) > 0)
{
throw new AdempiereException(MSG_MAX_LUS_EXCEEDED);
}
}
private I_C_UOM extractUOMOrNull(final IHUPackingAware huPackingAware)
{
final int uomId = huPackingAware.getC_UOM_ID();
return uomId > 0
? uomDAO.getById(uomId)
: null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\HUPackingAwareBL.java | 1 |
请完成以下Java代码 | public Criteria andProductCategoryIdNotIn(List<Long> values) {
addCriterion("product_category_id not in", values, "productCategoryId");
return (Criteria) this;
}
public Criteria andProductCategoryIdBetween(Long value1, Long value2) {
addCriterion("product_category_id between", value1, value2, "productCategoryId");
return (Criteria) this;
}
public Criteria andProductCategoryIdNotBetween(Long value1, Long value2) {
addCriterion("product_category_id not between", value1, value2, "productCategoryId");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition; | this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberProductCategoryRelationExample.java | 1 |
请完成以下Java代码 | public final class OrderId
{
@JsonProperty("gatewayId") @NonNull private final ShipperGatewayId shipperGatewayId;
@JsonProperty("orderId") @NonNull private final String orderIdAsString;
@JsonIgnore @Nullable private Integer orderIdAsInt = null; // lazy
@JsonCreator
private OrderId(
@JsonProperty("gatewayId") @NonNull final ShipperGatewayId shipperGatewayId,
@JsonProperty("orderId") @NonNull final String orderIdAsString)
{
Check.assumeNotEmpty(orderIdAsString, "orderIdAsString is not empty");
this.shipperGatewayId = shipperGatewayId;
this.orderIdAsString = orderIdAsString;
this.orderIdAsInt = null;
}
private OrderId(
@NonNull final ShipperGatewayId shipperGatewayId,
@NonNull final DeliveryOrderId deliveryOrderId)
{
this.shipperGatewayId = shipperGatewayId;
this.orderIdAsString = String.valueOf(deliveryOrderId.getRepoId());
this.orderIdAsInt = deliveryOrderId.getRepoId();
}
public static OrderId of(@NonNull final ShipperGatewayId shipperGatewayId, @NonNull final String orderIdAsString)
{
return new OrderId(shipperGatewayId, orderIdAsString);
}
public static OrderId of(@NonNull final ShipperGatewayId shipperGatewayId, @NonNull final DeliveryOrderId deliveryOrderId)
{
return new OrderId(shipperGatewayId, deliveryOrderId);
} | public int getOrderIdAsInt()
{
if (orderIdAsInt == null)
{
try
{
orderIdAsInt = Integer.parseInt(orderIdAsString);
}
catch (final Exception ex)
{
throw new IllegalArgumentException("orderId shall be integer but it was: " + orderIdAsString, ex);
}
}
return orderIdAsInt;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.spi\src\main\java\de\metas\shipper\gateway\spi\model\OrderId.java | 1 |
请完成以下Java代码 | public class EmptyBodyFilter extends AbstractEmptyBodyFilter {
@Override
public HttpServletRequestWrapper wrapRequest(HttpServletRequest req, boolean isBodyEmpty, PushbackInputStream requestBody) {
return new HttpServletRequestWrapper(req) {
@Override
public ServletInputStream getInputStream() throws IOException {
return new ServletInputStream() {
final InputStream inputStream = getRequestBody(isBodyEmpty, requestBody);
@Override
public int read() throws IOException {
return inputStream.read();
}
@Override
public int available() throws IOException {
return inputStream.available();
}
@Override
public void close() throws IOException {
inputStream.close();
}
@Override | public synchronized void mark(int readlimit) {
inputStream.mark(readlimit);
}
@Override
public synchronized void reset() throws IOException {
inputStream.reset();
}
@Override
public boolean markSupported() {
return inputStream.markSupported();
}
};
}
@Override
public BufferedReader getReader() throws IOException {
return EmptyBodyFilter.this.getReader(this.getInputStream());
}
};
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\filter\EmptyBodyFilter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PurchaseRowChangeRequest
{
@Getter(AccessLevel.PRIVATE)
Quantity qtyToPurchase;
@Getter(AccessLevel.PRIVATE)
BigDecimal qtyToPurchaseWithoutUOM;
ZonedDateTime purchaseDatePromised;
@Builder
private PurchaseRowChangeRequest(
final BigDecimal qtyToPurchaseWithoutUOM,
final Quantity qtyToPurchase,
final ZonedDateTime purchaseDatePromised)
{
if (qtyToPurchase != null && qtyToPurchaseWithoutUOM != null)
{
throw new AdempiereException("Only qtyToPurchase or qtyToPurchaseWithoutUOM shall be specified but not both");
}
this.qtyToPurchase = qtyToPurchase;
this.qtyToPurchaseWithoutUOM = qtyToPurchaseWithoutUOM;
this.purchaseDatePromised = purchaseDatePromised;
}
public static PurchaseRowChangeRequest of(@NonNull final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
Check.assumeNotEmpty(fieldChangeRequests, "field change requests shall not be empty");
final PurchaseRowChangeRequestBuilder builder = builder();
for (final JSONDocumentChangedEvent fieldChangeRequest : fieldChangeRequests)
{
final String fieldName = fieldChangeRequest.getPath();
if (PurchaseRow.FIELDNAME_QtyToPurchase.equals(fieldName))
{
final BigDecimal qtyToPurchase = fieldChangeRequest.getValueAsBigDecimal();
Check.assumeNotNull(qtyToPurchase, "Parameter qtyToPurchase is not null for {}", fieldChangeRequest);
builder.qtyToPurchaseWithoutUOM(qtyToPurchase);
}
else if (PurchaseRow.FIELDNAME_DatePromised.equals(fieldName)) | {
final ZonedDateTime datePromised = fieldChangeRequest.getValueAsZonedDateTime();
Check.assumeNotNull(datePromised, "Parameter datePromised is not null for {}", fieldChangeRequest);
builder.purchaseDatePromised(datePromised);
}
else
{
throw new AdempiereException("Field " + fieldName + " is not editable");
}
}
return builder.build();
}
public Quantity getQtyToPurchase(@NonNull final Supplier<I_C_UOM> defaultUOMSupplier)
{
if (getQtyToPurchase() != null)
{
return getQtyToPurchase();
}
else if (getQtyToPurchaseWithoutUOM() != null)
{
final BigDecimal qtyToPurchase = getQtyToPurchaseWithoutUOM();
return Quantity.of(qtyToPurchase, defaultUOMSupplier.get());
}
else
{
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseRowChangeRequest.java | 2 |
请完成以下Java代码 | public boolean isBlacklisted(final int workpackageProcessorId)
{
return blacklist.containsKey(workpackageProcessorId);
}
public void addToBlacklist(final int packageProcessorId, String packageProcessorClassname, Exception e)
{
final ConfigurationException exception = ConfigurationException.wrapIfNeeded(e);
final BlackListItem blacklistItemToAdd = new BlackListItem(packageProcessorId, packageProcessorClassname, exception);
blacklist.put(packageProcessorId, blacklistItemToAdd);
logger.warn("Processor blacklisted: " + blacklistItemToAdd, exception);
}
public void removeFromBlacklist(final int packageProcessorId)
{
final BlackListItem blacklistItem = blacklist.remove(packageProcessorId);
if (blacklistItem != null)
{
logger.info("Processor removed from blacklist: " + blacklistItem);
}
}
public void assertNotBlacklisted(final int workpackageProcessorId)
{ | final BlackListItem blacklistItem = blacklist.get(workpackageProcessorId);
if (blacklistItem != null)
{
blacklistItem.incrementHitCount();
throw new ConfigurationException("Already blacklisted: " + blacklistItem, blacklistItem.getException());
}
}
public List<BlackListItem> getItems()
{
return new ArrayList<BlackListItem>(blacklist.values());
}
public void clear()
{
blacklist.clear();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\WorkpackageProcessorBlackList.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void process() {
template.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
// We use MySQL 8 InnoDB.
// The default isolation level for InnoDB is REPEATABLE READ, therefore
// we need to switch to READ_COMMITTED to reveal how Hibernate session-level
// repeatable reads works
template.setIsolationLevel(Isolation.READ_COMMITTED.value());
// Transaction A
template.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
Author authorA1 = authorRepository.findById(1L).orElseThrow();
System.out.println("Author A1: " + authorA1.getName() + "\n");
// Transaction B
template.execute(new TransactionCallbackWithoutResult() {
@Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
Author authorB = authorRepository.findById(1L).orElseThrow();
authorB.setName("Alicia Tom");
System.out.println("Author B: " + authorB.getName() + "\n");
} | });
// Direct fetching via findById(), find() and get() doesn't trigger a SELECT
// It loads the author directly from Persistence Context
Author authorA2 = authorRepository.findById(1L).orElseThrow();
System.out.println("\nAuthor A2: " + authorA2.getName() + "\n");
// JPQL entity queries take advantage of session-level repeatable reads
// The data snapshot returned by the triggered SELECT is ignored
Author authorViaJpql = authorRepository.fetchByIdJpql(1L);
System.out.println("Author via JPQL: " + authorViaJpql.getName() + "\n");
// SQL entity queries take advantage of session-level repeatable reads
// The data snapshot returned by the triggered SELECT is ignored
Author authorViaSql = authorRepository.fetchByIdSql(1L);
System.out.println("Author via SQL: " + authorViaSql.getName() + "\n");
// JPQL query projections always load the latest database state
String nameViaJpql = authorRepository.fetchNameByIdJpql(1L);
System.out.println("Author name via JPQL: " + nameViaJpql + "\n");
// SQL query projections always load the latest database state
String nameViaSql = authorRepository.fetchNameByIdSql(1L);
System.out.println("Author name via SQL: " + nameViaSql + "\n");
}
});
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootSessionRepeatableReads\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class C_Workplace
{
private final IPickingSlotBL pickingSlotBL = Services.get(IPickingSlotBL.class);
public C_Workplace()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@CalloutMethod(columnNames = I_C_Workplace.COLUMNNAME_M_Warehouse_ID)
public void resetPickingSlotId(@NonNull final I_C_Workplace workplace)
{
workplace.setM_PickingSlot_ID(-1);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_C_Workplace.COLUMNNAME_M_PickingSlot_ID)
public void validatePickingSlot(@NonNull final I_C_Workplace workplace)
{ | final PickingSlotId pickingSlotId = PickingSlotId.ofRepoIdOrNull(workplace.getM_PickingSlot_ID());
if (pickingSlotId == null)
{
return;
}
final I_M_PickingSlot pickingSlot = pickingSlotBL.getById(pickingSlotId);
if (pickingSlot.getM_Warehouse_ID() != workplace.getM_Warehouse_ID())
{
throw new AdempiereException("Different Warehouses on Picking Slot: " + pickingSlot.getM_PickingSlot_ID() + " and on Workplace: "
+ workplace.getC_Workplace_ID());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\workplace\interceptor\C_Workplace.java | 2 |
请完成以下Java代码 | public void setRemote_Addr (final @Nullable java.lang.String Remote_Addr)
{
set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr);
}
@Override
public java.lang.String getRemote_Addr()
{
return get_ValueAsString(COLUMNNAME_Remote_Addr);
}
@Override
public void setRemote_Host (final @Nullable java.lang.String Remote_Host)
{
set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host);
}
@Override | public java.lang.String getRemote_Host()
{
return get_ValueAsString(COLUMNNAME_Remote_Host);
}
@Override
public void setWebSession (final @Nullable java.lang.String WebSession)
{
set_ValueNoCheck (COLUMNNAME_WebSession, WebSession);
}
@Override
public java.lang.String getWebSession()
{
return get_ValueAsString(COLUMNNAME_WebSession);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Session.java | 1 |
请完成以下Java代码 | public void createVariable(boolean isAdmin, CreateTaskVariablePayload createTaskVariablePayload) {
if (!isAdmin) {
assertCanModifyTask(getInternalTask(createTaskVariablePayload.getTaskId()));
}
taskVariablesValidator.handleCreateTaskVariablePayload(createTaskVariablePayload);
assertVariableDoesNotExist(createTaskVariablePayload);
taskService.setVariableLocal(
createTaskVariablePayload.getTaskId(),
createTaskVariablePayload.getName(),
createTaskVariablePayload.getValue()
);
}
private void assertVariableDoesNotExist(CreateTaskVariablePayload createTaskVariablePayload) {
Map<String, VariableInstance> variables = taskService.getVariableInstancesLocal(
createTaskVariablePayload.getTaskId()
);
if (variables != null && variables.containsKey(createTaskVariablePayload.getName())) {
throw new IllegalStateException("Variable already exists");
}
}
public void updateVariable(boolean isAdmin, UpdateTaskVariablePayload updateTaskVariablePayload) {
if (!isAdmin) {
assertCanModifyTask(getInternalTask(updateTaskVariablePayload.getTaskId()));
}
taskVariablesValidator.handleUpdateTaskVariablePayload(updateTaskVariablePayload);
assertVariableExists(updateTaskVariablePayload);
taskService.setVariableLocal(
updateTaskVariablePayload.getTaskId(),
updateTaskVariablePayload.getName(),
updateTaskVariablePayload.getValue()
);
} | private void assertVariableExists(UpdateTaskVariablePayload updateTaskVariablePayload) {
Map<String, VariableInstance> variables = taskService.getVariableInstancesLocal(
updateTaskVariablePayload.getTaskId()
);
if (variables == null) {
throw new IllegalStateException("Variable does not exist");
}
if (!variables.containsKey(updateTaskVariablePayload.getName())) {
throw new IllegalStateException("Variable does not exist");
}
}
public void handleCompleteTaskPayload(CompleteTaskPayload completeTaskPayload) {
completeTaskPayload.setVariables(
taskVariablesValidator.handlePayloadVariables(completeTaskPayload.getVariables())
);
}
public void handleSaveTaskPayload(SaveTaskPayload saveTaskPayload) {
saveTaskPayload.setVariables(taskVariablesValidator.handlePayloadVariables(saveTaskPayload.getVariables()));
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskRuntimeHelper.java | 1 |
请完成以下Java代码 | public void setC_AcctSchema_ID (int C_AcctSchema_ID)
{
if (C_AcctSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID));
}
/** Get Accounting Schema.
@return Rules for accounting
*/
public int getC_AcctSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_BPartner getC_BPartner() throws RuntimeException
{
return (I_C_BPartner)MTable.get(getCtx(), I_C_BPartner.Table_Name)
.getPO(getC_BPartner_ID(), get_TrxName()); }
/** Set Business Partner .
@param C_BPartner_ID
Identifies a Business Partner
*/
public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Business Partner .
@return Identifies a Business Partner
*/
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getE_Expense_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getE_Expense_Acct(), get_TrxName()); }
/** Set Employee Expense.
@param E_Expense_Acct
Account for Employee Expenses
*/
public void setE_Expense_Acct (int E_Expense_Acct) | {
set_Value (COLUMNNAME_E_Expense_Acct, Integer.valueOf(E_Expense_Acct));
}
/** Get Employee Expense.
@return Account for Employee Expenses
*/
public int getE_Expense_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_E_Expense_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getE_Prepayment_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getE_Prepayment_Acct(), get_TrxName()); }
/** Set Employee Prepayment.
@param E_Prepayment_Acct
Account for Employee Expense Prepayments
*/
public void setE_Prepayment_Acct (int E_Prepayment_Acct)
{
set_Value (COLUMNNAME_E_Prepayment_Acct, Integer.valueOf(E_Prepayment_Acct));
}
/** Get Employee Prepayment.
@return Account for Employee Expense Prepayments
*/
public int getE_Prepayment_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_E_Prepayment_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Employee_Acct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void publishProductChangedEvent(final ProductId productId)
{
final MSV3ServerConfig serverConfig = getServerConfig();
final PZN pzn = getPZNByProductId(productId);
final int qtyOnHand = getQtyOnHand(serverConfig, productId);
final MSV3StockAvailability item = MSV3StockAvailability.builder()
.pzn(pzn.getValueAsLong())
.qty(qtyOnHand)
.build();
final MSV3StockAvailabilityUpdatedEvent event = MSV3StockAvailabilityUpdatedEvent.ofSingle(
item,
eventVersionGenerator.getNextEventVersion());
msv3ServerPeerService.publishStockAvailabilityUpdatedEvent(event);
}
@Async
public void publishProductDeletedEvent(final ProductId productId)
{
final PZN pzn = getPZNByProductId(productId);
final MSV3StockAvailability item = MSV3StockAvailability.builder()
.pzn(pzn.getValueAsLong())
.delete(true)
.build();
final MSV3StockAvailabilityUpdatedEvent event = MSV3StockAvailabilityUpdatedEvent.ofSingle(
item,
eventVersionGenerator.getNextEventVersion());
msv3ServerPeerService.publishStockAvailabilityUpdatedEvent(event);
}
public void publishProductExcludeAddedOrChanged(
final ProductId productId,
@NonNull final BPartnerId newBPartnerId,
final BPartnerId oldBPartnerId)
{
final PZN pzn = getPZNByProductId(productId);
final MSV3ProductExcludesUpdateEventBuilder eventBuilder = MSV3ProductExcludesUpdateEvent.builder();
if (oldBPartnerId != null && !Objects.equals(newBPartnerId, oldBPartnerId))
{
eventBuilder.item(MSV3ProductExclude.builder() | .pzn(pzn)
.bpartnerId(oldBPartnerId.getRepoId())
.delete(true)
.build());
}
eventBuilder.item(MSV3ProductExclude.builder()
.pzn(pzn)
.bpartnerId(newBPartnerId.getRepoId())
.build());
msv3ServerPeerService.publishProductExcludes(eventBuilder.build());
}
public void publishProductExcludeDeleted(final ProductId productId, final BPartnerId... bpartnerIds)
{
final PZN pzn = getPZNByProductId(productId);
final List<MSV3ProductExclude> eventItems = Stream.of(bpartnerIds)
.filter(Objects::nonNull)
.distinct()
.map(bpartnerId -> MSV3ProductExclude.builder()
.pzn(pzn)
.bpartnerId(bpartnerId.getRepoId())
.delete(true)
.build())
.collect(ImmutableList.toImmutableList());
if (eventItems.isEmpty())
{
return;
}
msv3ServerPeerService.publishProductExcludes(MSV3ProductExcludesUpdateEvent.builder()
.items(eventItems)
.build());
}
private int getPublishAllStockAvailabilityBatchSize()
{
return Services
.get(ISysConfigBL.class)
.getIntValue(SYSCONFIG_STOCK_AVAILABILITY_BATCH_SIZE, 500);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer-metasfresh\src\main\java\de\metas\vertical\pharma\msv3\server\peer\metasfresh\services\MSV3StockAvailabilityService.java | 2 |
请完成以下Java代码 | public DefaultSyncHttpGraphQlClientBuilder header(String name, String... values) {
this.restClientBuilder.defaultHeader(name, values);
return this;
}
@Override
public DefaultSyncHttpGraphQlClientBuilder headers(Consumer<HttpHeaders> headersConsumer) {
this.restClientBuilder.defaultHeaders(headersConsumer);
return this;
}
@Override
@SuppressWarnings("removal")
public DefaultSyncHttpGraphQlClientBuilder messageConverters(Consumer<List<HttpMessageConverter<?>>> configurer) {
this.restClientBuilder.messageConverters(configurer);
return this;
}
@Override
public DefaultSyncHttpGraphQlClientBuilder configureMessageConverters(Consumer<HttpMessageConverters.ClientBuilder> configurer) {
this.restClientBuilder.configureMessageConverters(configurer);
return this;
}
@Override
public DefaultSyncHttpGraphQlClientBuilder restClient(Consumer<RestClient.Builder> configurer) {
configurer.accept(this.restClientBuilder);
return this;
}
@Override
@SuppressWarnings("unchecked")
public HttpSyncGraphQlClient build() {
this.restClientBuilder.configureMessageConverters((builder) -> {
builder.registerDefaults().configureMessageConverters((converter) -> {
if (HttpMessageConverterDelegate.isJsonConverter(converter)) {
setJsonConverter((HttpMessageConverter<Object>) converter);
}
});
});
RestClient restClient = this.restClientBuilder.build();
HttpSyncGraphQlTransport transport = new HttpSyncGraphQlTransport(restClient);
GraphQlClient graphQlClient = super.buildGraphQlClient(transport); | return new DefaultHttpSyncGraphQlClient(graphQlClient, restClient, getBuilderInitializer());
}
/**
* Default {@link HttpSyncGraphQlClient} implementation.
*/
private static class DefaultHttpSyncGraphQlClient
extends AbstractDelegatingGraphQlClient implements HttpSyncGraphQlClient {
private final RestClient restClient;
private final Consumer<AbstractGraphQlClientSyncBuilder<?>> builderInitializer;
DefaultHttpSyncGraphQlClient(
GraphQlClient delegate, RestClient restClient,
Consumer<AbstractGraphQlClientSyncBuilder<?>> builderInitializer) {
super(delegate);
Assert.notNull(restClient, "RestClient is required");
Assert.notNull(builderInitializer, "`builderInitializer` is required");
this.restClient = restClient;
this.builderInitializer = builderInitializer;
}
@Override
public DefaultSyncHttpGraphQlClientBuilder mutate() {
DefaultSyncHttpGraphQlClientBuilder builder = new DefaultSyncHttpGraphQlClientBuilder(this.restClient);
this.builderInitializer.accept(builder);
return builder;
}
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultSyncHttpGraphQlClientBuilder.java | 1 |
请完成以下Java代码 | public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Model Validation Class.
@param ModelValidationClass Model Validation Class */
public void setModelValidationClass (String ModelValidationClass)
{
set_Value (COLUMNNAME_ModelValidationClass, ModelValidationClass);
}
/** Get Model Validation Class.
@return Model Validation Class */
public String getModelValidationClass ()
{
return (String)get_Value(COLUMNNAME_ModelValidationClass);
}
/** 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 Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ModelValidator.java | 1 |
请完成以下Java代码 | public class PaymentIdentification1 {
@XmlElement(name = "InstrId")
protected String instrId;
@XmlElement(name = "EndToEndId", required = true)
protected String endToEndId;
/**
* Gets the value of the instrId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInstrId() {
return instrId;
}
/**
* Sets the value of the instrId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInstrId(String value) {
this.instrId = value; | }
/**
* Gets the value of the endToEndId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getEndToEndId() {
return endToEndId;
}
/**
* Sets the value of the endToEndId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setEndToEndId(String value) {
this.endToEndId = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\PaymentIdentification1.java | 1 |
请完成以下Java代码 | public RequestEntity<?> convert(OAuth2UserRequest userRequest) {
ClientRegistration clientRegistration = userRequest.getClientRegistration();
HttpMethod httpMethod = getHttpMethod(clientRegistration);
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
URI uri = UriComponentsBuilder
.fromUriString(clientRegistration.getProviderDetails().getUserInfoEndpoint().getUri())
.build()
.toUri();
RequestEntity<?> request;
if (HttpMethod.POST.equals(httpMethod)) {
headers.setContentType(DEFAULT_CONTENT_TYPE);
MultiValueMap<String, String> formParameters = new LinkedMultiValueMap<>();
formParameters.add(OAuth2ParameterNames.ACCESS_TOKEN, userRequest.getAccessToken().getTokenValue());
request = new RequestEntity<>(formParameters, headers, httpMethod, uri);
}
else {
headers.setBearerAuth(userRequest.getAccessToken().getTokenValue()); | request = new RequestEntity<>(headers, httpMethod, uri);
}
return request;
}
private HttpMethod getHttpMethod(ClientRegistration clientRegistration) {
if (AuthenticationMethod.FORM
.equals(clientRegistration.getProviderDetails().getUserInfoEndpoint().getAuthenticationMethod())) {
return HttpMethod.POST;
}
return HttpMethod.GET;
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\userinfo\OAuth2UserRequestEntityConverter.java | 1 |
请完成以下Java代码 | public static JsonRawMaterialsIssueLineStep of(RawMaterialsIssueStep step, JsonOpts jsonOpts)
{
final JsonRawMaterialsIssueLineStepBuilder builder = builder()
.id(String.valueOf(step.getId().getRepoId()))
.isAlternativeIssue(step.isAlternativeIssue())
.productId(String.valueOf(step.getProductId().getRepoId()))
.productName(step.getProductName().translate(jsonOpts.getAdLanguage()))
.locatorName(step.getIssueFromLocator().getCaption())
.locatorQrCode(step.getIssueFromLocator().getQrCode().toGlobalQRCodeJsonString())
.huQRCode(Optional.ofNullable(step.getIssueFromHU().getBarcode())
.map(HUQRCode::toRenderedJson)
.orElse(null))
.huId(step.getIssueFromHU().getId().toHUValue())
.uom(step.getQtyToIssue().getUOMSymbol())
.qtyHUCapacity(step.getIssueFromHU().getHuCapacity().toBigDecimal())
.qtyToIssue(step.getQtyToIssue().toBigDecimal());
final PPOrderIssueSchedule.Issued issued = step.getIssued();
if (issued != null)
{
builder.qtyIssued(issued.getQtyIssued().toBigDecimal());
final QtyRejectedWithReason qtyRejected = issued.getQtyRejected();
if (qtyRejected != null)
{
builder.qtyRejected(qtyRejected.toBigDecimal());
builder.qtyRejectedReasonCode(qtyRejected.getReasonCode().toJson());
}
}
if (step.getScaleTolerance() != null)
{
final JsonScaleTolerance jsonScaleTolerance = JsonScaleTolerance.builder() | .negativeTolerance(step.getScaleTolerance().getNegativeTolerance().toBigDecimal())
.positiveTolerance(step.getScaleTolerance().getPositiveTolerance().toBigDecimal())
.build();
builder.scaleTolerance(jsonScaleTolerance);
}
return builder.build();
}
@Value
@Builder
public static class JsonScaleTolerance
{
@NonNull
BigDecimal positiveTolerance;
@NonNull
BigDecimal negativeTolerance;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\workflows_api\activity_handlers\issue\json\JsonRawMaterialsIssueLineStep.java | 1 |
请完成以下Java代码 | public int getM_AttributeSetInstance_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSetInstance_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setQtyDeliveredInUOM (final @Nullable BigDecimal QtyDeliveredInUOM)
{
set_Value (COLUMNNAME_QtyDeliveredInUOM, QtyDeliveredInUOM);
}
@Override
public BigDecimal getQtyDeliveredInUOM()
{ | final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEntered (final BigDecimal QtyEntered)
{
set_Value (COLUMNNAME_QtyEntered, QtyEntered);
}
@Override
public BigDecimal getQtyEntered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEntered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInvoicedInUOM (final @Nullable BigDecimal QtyInvoicedInUOM)
{
set_Value (COLUMNNAME_QtyInvoicedInUOM, QtyInvoicedInUOM);
}
@Override
public BigDecimal getQtyInvoicedInUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_CallOrderSummary.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void confirmDelivery(String orderId, String expressNo, String userId) {
// 构造受理上下文
OrderProcessContext<String> context = buildContext(orderId, userId, expressNo, ProcessReqEnum.ConfirmDelivery);
// 受理下单请求
processEngine.process(context);
}
@Override
public void confirmReceive(String orderId, String userId) {
// 构造受理上下文
OrderProcessContext<String> context = buildContext(orderId, userId,null, ProcessReqEnum.ConfirmReceive);
// 受理下单请求
processEngine.process(context);
}
/**
* 请求参数校验
* @param req 请求参数
* @param expCodeEnum 异常枚举
* @param <T> 请求参数类型
*/
private <T> void checkParam(T req, ExpCodeEnum expCodeEnum) {
if (req == null) {
throw new CommonBizException(expCodeEnum);
}
} | private <T> OrderProcessContext<String> buildContext(String orderId, String userId, T reqData, ProcessReqEnum processReqEnum) {
OrderProcessContext context = new OrderProcessContext();
// 受理请求
OrderProcessReq req = new OrderProcessReq();
req.setProcessReqEnum(processReqEnum);
req.setUserId(userId);
if (StringUtils.isNotEmpty(orderId)) {
req.setOrderId(orderId);
}
if (reqData != null) {
req.setReqData(reqData);
}
context.setOrderProcessReq(req);
return context;
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\service\OrderServiceImpl.java | 2 |
请完成以下Java代码 | public static boolean dbTypeIsMySql(DbType dbType) {
return dbTypeIf(dbType, DbType.MYSQL, DbType.MARIADB, DbType.CLICK_HOUSE, DbType.SQLITE);
}
public static boolean dbTypeIsOracle(DbType dbType) {
return dbTypeIf(dbType, DbType.ORACLE, DbType.ORACLE_12C, DbType.DM);
}
/**
* 是否是达梦
*/
public static boolean dbTypeIsDm(DbType dbType) {
return dbTypeIf(dbType, DbType.DM);
}
public static boolean dbTypeIsSqlServer(DbType dbType) {
return dbTypeIf(dbType, DbType.SQL_SERVER, DbType.SQL_SERVER2005);
}
public static boolean dbTypeIsPostgre(DbType dbType) {
return dbTypeIf(dbType, DbType.POSTGRE_SQL, DbType.KINGBASE_ES, DbType.GAUSS);
}
/**
* 根据枚举类 获取数据库类型的字符串
* @param dbType
* @return
*/
public static String getDbTypeString(DbType dbType){
if(DbType.DB2.equals(dbType)){
return DataBaseConstant.DB_TYPE_DB2;
}else if(DbType.HSQL.equals(dbType)){
return DataBaseConstant.DB_TYPE_HSQL;
}else if(dbTypeIsOracle(dbType)){
return DataBaseConstant.DB_TYPE_ORACLE;
}else if(dbTypeIsSqlServer(dbType)){ | return DataBaseConstant.DB_TYPE_SQLSERVER;
}else if(dbTypeIsPostgre(dbType)){
return DataBaseConstant.DB_TYPE_POSTGRESQL;
}
return DataBaseConstant.DB_TYPE_MYSQL;
}
/**
* 根据枚举类 获取数据库方言字符串
* @param dbType
* @return
*/
public static String getDbDialect(DbType dbType){
return dialectMap.get(dbType.getDb());
}
/**
* 判断数据库类型
*/
public static boolean dbTypeIf(DbType dbType, DbType... correctTypes) {
for (DbType type : correctTypes) {
if (type.equals(dbType)) {
return true;
}
}
return false;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\dynamic\db\DbTypeUtils.java | 1 |
请完成以下Java代码 | protected void invokeVariableLifecycleListenersUpdate(CoreVariableInstance variableInstance, AbstractVariableScope sourceScope) {
invokeVariableLifecycleListenersUpdate(variableInstance, sourceScope, getVariableInstanceLifecycleListeners());
}
protected void invokeVariableLifecycleListenersUpdate(CoreVariableInstance variableInstance, AbstractVariableScope sourceScope,
List<VariableInstanceLifecycleListener<CoreVariableInstance>> lifecycleListeners) {
for (VariableInstanceLifecycleListener<CoreVariableInstance> lifecycleListener : lifecycleListeners) {
lifecycleListener.onUpdate(variableInstance, sourceScope);
}
}
public void setVariableLocal(String variableName, Object value, boolean skipJavaSerializationFormatCheck) {
TypedValue typedValue = Variables.untypedValue(value);
setVariableLocal(variableName, typedValue, getSourceActivityVariableScope(), skipJavaSerializationFormatCheck);
}
@Override
public void setVariableLocal(String variableName, Object value) {
setVariableLocal(variableName, value, false);
}
@Override
public void removeVariable(String variableName) {
removeVariable(variableName, getSourceActivityVariableScope());
}
protected void removeVariable(String variableName, AbstractVariableScope sourceActivityExecution) {
if (getVariableStore().containsKey(variableName)) {
removeVariableLocal(variableName, sourceActivityExecution);
return;
}
AbstractVariableScope parentVariableScope = getParentVariableScope();
if (parentVariableScope!=null) {
if (sourceActivityExecution==null) {
parentVariableScope.removeVariable(variableName);
} else {
parentVariableScope.removeVariable(variableName, sourceActivityExecution);
}
}
} | @Override
public void removeVariableLocal(String variableName) {
removeVariableLocal(variableName, getSourceActivityVariableScope());
}
protected AbstractVariableScope getSourceActivityVariableScope() {
return this;
}
protected void removeVariableLocal(String variableName, AbstractVariableScope sourceActivityExecution) {
if (getVariableStore().containsKey(variableName)) {
CoreVariableInstance variableInstance = getVariableStore().getVariable(variableName);
invokeVariableLifecycleListenersDelete(variableInstance, sourceActivityExecution);
getVariableStore().removeVariable(variableName);
}
}
public ELContext getCachedElContext() {
return cachedElContext;
}
public void setCachedElContext(ELContext cachedElContext) {
this.cachedElContext = cachedElContext;
}
@Override
public void dispatchEvent(VariableEvent variableEvent) {
// default implementation does nothing
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\variable\scope\AbstractVariableScope.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BPartnerQueryService
{
public BPartnerQuery createQuery(@NonNull final OrgAndBPartnerCompositeLookupKeyList queryLookupKeys)
{
return createBPartnerQuery(queryLookupKeys.getCompositeLookupKeys(), queryLookupKeys.getOrgId());
}
public BPartnerQuery createQueryFailIfNotExists(
@NonNull final BPartnerCompositeLookupKey queryLookupKey,
@Nullable final OrgId orgId)
{
final BPartnerQueryBuilder queryBuilder = BPartnerQuery.builder()
.failIfNotExists(true);
if (orgId != null)
{
queryBuilder.onlyOrgId(orgId);
}
addKeyToQueryBuilder(queryLookupKey, queryBuilder);
return queryBuilder.build();
}
private static BPartnerQuery createBPartnerQuery(
@NonNull final Collection<BPartnerCompositeLookupKey> bpartnerLookupKeys,
@Nullable final OrgId onlyOrgId)
{
final BPartnerQueryBuilder query = BPartnerQuery.builder();
if (onlyOrgId != null)
{
query.onlyOrgId(onlyOrgId)
.onlyOrgId(OrgId.ANY);
}
for (final BPartnerCompositeLookupKey bpartnerLookupKey : bpartnerLookupKeys)
{
addKeyToQueryBuilder(bpartnerLookupKey, query);
} | return query.build();
}
private static void addKeyToQueryBuilder(final BPartnerCompositeLookupKey bpartnerLookupKey, final BPartnerQueryBuilder queryBuilder)
{
final JsonExternalId jsonExternalId = bpartnerLookupKey.getJsonExternalId();
if (jsonExternalId != null)
{
queryBuilder.externalId(JsonConverters.fromJsonOrNull(jsonExternalId));
}
final String value = bpartnerLookupKey.getCode();
if (isNotBlank(value))
{
queryBuilder.bpartnerValue(value.trim());
}
final GLN gln = bpartnerLookupKey.getGln();
if (gln != null)
{
queryBuilder.gln(gln);
}
final GlnWithLabel glnWithLabel = bpartnerLookupKey.getGlnWithLabel();
if (glnWithLabel != null)
{
queryBuilder.gln(glnWithLabel.getGln());
queryBuilder.glnLookupLabel(glnWithLabel.getLabel());
}
final MetasfreshId metasfreshId = bpartnerLookupKey.getMetasfreshId();
if (metasfreshId != null)
{
queryBuilder.bPartnerId(BPartnerId.ofRepoId(metasfreshId.getValue()));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\BPartnerQueryService.java | 2 |
请完成以下Java代码 | public void log(final String message, final Throwable e)
{
if (e == null)
{
log.warn(message);
}
log.error(message, e);
} // log
/**
* Log debug
*
* @param message message
*/
@Override
public void log(String message)
{ | log.debug(message);
} // log
@Override
public String getServletName()
{
return NAME;
}
@Override
public String getServletInfo()
{
return "Server Monitor";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\adempiere\serverRoot\servlet\ServerMonitor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class VetController {
private final VetRepository vetRepository;
public VetController(VetRepository vetRepository) {
this.vetRepository = vetRepository;
}
@GetMapping("/vets.html")
public String showVetList(@RequestParam(defaultValue = "1") int page, Model model) {
// Here we are returning an object of type 'Vets' rather than a collection of Vet
// objects so it is simpler for Object-Xml mapping
Vets vets = new Vets();
Page<Vet> paginated = findPaginated(page);
vets.getVetList().addAll(paginated.toList());
return addPaginationModel(page, paginated, model);
}
private String addPaginationModel(int page, Page<Vet> paginated, Model model) {
List<Vet> listVets = paginated.getContent();
model.addAttribute("currentPage", page);
model.addAttribute("totalPages", paginated.getTotalPages());
model.addAttribute("totalItems", paginated.getTotalElements());
model.addAttribute("listVets", listVets);
return "vets/vetList";
}
private Page<Vet> findPaginated(int page) { | int pageSize = 5;
Pageable pageable = PageRequest.of(page - 1, pageSize);
return vetRepository.findAll(pageable);
}
@GetMapping({ "/vets" })
public @ResponseBody Vets showResourcesVetList() {
// Here we are returning an object of type 'Vets' rather than a collection of Vet
// objects so it is simpler for JSon/Object mapping
Vets vets = new Vets();
vets.getVetList().addAll(this.vetRepository.findAll());
return vets;
}
} | repos\spring-petclinic-main\src\main\java\org\springframework\samples\petclinic\vet\VetController.java | 2 |
请完成以下Java代码 | public int getM_Demand_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Demand_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 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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Demand.java | 1 |
请完成以下Java代码 | 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 Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
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 Details.
@param TextDetails Details */
public void setTextDetails (String TextDetails)
{
set_Value (COLUMNNAME_TextDetails, TextDetails); | }
/** Get Details.
@return Details */
public String getTextDetails ()
{
return (String)get_Value(COLUMNNAME_TextDetails);
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Topic Action.
@param TopicAction Topic Action */
public void setTopicAction (String TopicAction)
{
set_Value (COLUMNNAME_TopicAction, TopicAction);
}
/** Get Topic Action.
@return Topic Action */
public String getTopicAction ()
{
return (String)get_Value(COLUMNNAME_TopicAction);
}
/** Set Topic Status.
@param TopicStatus Topic Status */
public void setTopicStatus (String TopicStatus)
{
set_Value (COLUMNNAME_TopicStatus, TopicStatus);
}
/** Get Topic Status.
@return Topic Status */
public String getTopicStatus ()
{
return (String)get_Value(COLUMNNAME_TopicStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Topic.java | 1 |
请完成以下Java代码 | public String getScript() {
return script;
}
/**
* @see Builder#scopeContainer(VariableContainer)
*/
public VariableContainer getScopeContainer() {
return scopeContainer;
}
/**
* @see Builder#inputVariableContainer(VariableContainer)
*/
public VariableContainer getInputVariableContainer() {
return inputVariableContainer;
}
/**
* @see Builder#storeScriptVariables
*/
public boolean isStoreScriptVariables() {
return storeScriptVariables;
}
/**
* @see Builder#additionalResolver(Resolver)
*/
public List<Resolver> getAdditionalResolvers() {
return additionalResolvers;
} | /**
* @see Builder#traceEnhancer(ScriptTraceEnhancer)
*/
public ScriptTraceEnhancer getTraceEnhancer() {
return traceEnhancer;
}
@Override
public String toString() {
return new StringJoiner(", ", ScriptEngineRequest.class.getSimpleName() + "[", "]")
.add("language='" + language + "'")
.add("script='" + script + "'")
.add("variableContainer=" + scopeContainer)
.add("storeScriptVariables=" + storeScriptVariables)
.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptEngineRequest.java | 1 |
请完成以下Java代码 | public void setM_ProductBOM_ID (int M_ProductBOM_ID)
{
if (M_ProductBOM_ID < 1)
set_Value (COLUMNNAME_M_ProductBOM_ID, null);
else
set_Value (COLUMNNAME_M_ProductBOM_ID, Integer.valueOf(M_ProductBOM_ID));
}
/** Get BOM Product.
@return Bill of Material Component Product
*/
public int getM_ProductBOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ProductBOM_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getM_ProductBOM_ID()));
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Product.
@param M_Product_ID
Product, Service, Item
*/
public void setM_Product_ID (int M_Product_ID)
{ | if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Product.
@return Product, Service, Item
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_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_M_Product_BOM.java | 1 |
请完成以下Java代码 | public int getDoc_User_ID()
{
return getCreatedBy();
} // getDoc_User_ID
/**
* Get Document Approval Amount
*
* @return DR amount
*/
@Override
public BigDecimal getApprovalAmt()
{
return getTotalDr();
} // getApprovalAmt
/**
* Document Status is Complete or Closed
*
* @return true if CO, CL or RE
*/
@Deprecated
public boolean isComplete()
{
return Services.get(IGLJournalBL.class).isComplete(this);
} // isComplete
// metas: cg: 02476 | private static void setAmtPrecision(final I_GL_Journal journal)
{
final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoIdOrNull(journal.getC_AcctSchema_ID());
if (acctSchemaId == null)
{
return;
}
final AcctSchema as = Services.get(IAcctSchemaDAO.class).getById(acctSchemaId);
final CurrencyPrecision precision = as.getStandardPrecision();
final BigDecimal controlAmt = precision.roundIfNeeded(journal.getControlAmt());
journal.setControlAmt(controlAmt);
}
} // MJournal | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\model\MJournal.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PickingJobWarehouseService
{
@NonNull private final IWarehouseBL warehouseBL = Services.get(IWarehouseBL.class);
@NonNull private final WorkplaceService workplaceService;
public String getLocatorNameById(final LocatorId locatorId)
{
return warehouseBL.getLocatorById(locatorId).getValue();
}
public ImmutableSet<LocatorId> getLocatorIdsOfTheSamePickingGroup(@NonNull final WarehouseId warehouseId)
{
return warehouseBL.getLocatorIdsOfTheSamePickingGroup(warehouseId);
} | public Optional<Workplace> getWorkplaceByUserId(@NonNull final UserId userId)
{
return workplaceService.getWorkplaceByUserId(userId);
}
public Optional<WarehouseId> getWarehouseIdByUserId(@NonNull final UserId userId)
{
return workplaceService.getWarehouseIdByUserId(userId);
}
public Set<LocatorId> getPickFromLocatorIds(final Workplace workplace)
{
return workplaceService.getPickFromLocatorIds(workplace);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\service\external\warehouse\PickingJobWarehouseService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static class SessionExpirationProperties {
private int maxInactiveIntervalSeconds;
public int getMaxInactiveIntervalSeconds() {
return this.maxInactiveIntervalSeconds;
}
public void setMaxInactiveIntervalSeconds(int maxInactiveIntervalSeconds) {
this.maxInactiveIntervalSeconds = maxInactiveIntervalSeconds;
}
public void setMaxInactiveInterval(Duration duration) {
int maxInactiveIntervalInSeconds = duration != null
? Long.valueOf(duration.toSeconds()).intValue()
: GemFireHttpSessionConfiguration.DEFAULT_MAX_INACTIVE_INTERVAL_IN_SECONDS;
setMaxInactiveIntervalSeconds(maxInactiveIntervalInSeconds);
}
}
public static class SessionRegionProperties {
private String name;
public String getName() {
return this.name;
} | public void setName(String name) {
this.name = name;
}
}
public static class SessionSerializerProperties {
private String beanName;
public String getBeanName() {
return this.beanName;
}
public void setBeanName(String beanName) {
this.beanName = beanName;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\SpringSessionProperties.java | 2 |
请完成以下Java代码 | public void setNestedProcessInstanceId(String nestedProcessInstanceId) {
this.nestedProcessInstanceId = nestedProcessInstanceId;
}
@Override
public String getNestedProcessInstanceId() {
return nestedProcessInstanceId;
}
public void setLinkedProcessInstanceId(String linkedProcessInstanceId) {
this.linkedProcessInstanceId = linkedProcessInstanceId;
}
@Override
public String getLinkedProcessInstanceId() {
return linkedProcessInstanceId;
}
public void setLinkedProcessInstanceType(String linkedProcessInstanceType) {
this.linkedProcessInstanceType = linkedProcessInstanceType;
}
@Override
public String getLinkedProcessInstanceType() {
return linkedProcessInstanceType;
}
@Override
public ProcessEvents getEventType() {
return ProcessEvents.PROCESS_STARTED;
}
@Override
public String toString() {
return (
"ProcessStartedEventImpl{" + | super.toString() +
"nestedProcessDefinitionId='" +
nestedProcessDefinitionId +
'\'' +
", nestedProcessInstanceId='" +
nestedProcessInstanceId +
'\'' +
", linkedProcessInstanceId='" +
linkedProcessInstanceId +
'\'' +
", linkedProcessInstanceType='" +
linkedProcessInstanceType +
'\'' +
'}'
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\impl\ProcessStartedEventImpl.java | 1 |
请完成以下Java代码 | static void updatePriceAndTax(@NonNull final I_C_Invoice_Candidate ic, @NonNull final PriceAndTax priceAndTax)
{
//
// Pricing System & Currency
if (priceAndTax.getPricingSystemId() != null)
{
ic.setM_PricingSystem_ID(priceAndTax.getPricingSystemId().getRepoId());
}
if (priceAndTax.getPriceListVersionId() != null)
{
ic.setM_PriceList_Version_ID(priceAndTax.getPriceListVersionId().getRepoId());
}
if (priceAndTax.getCurrencyId() != null)
{
ic.setC_Currency_ID(priceAndTax.getCurrencyId().getRepoId());
}
//
// Price & Discount
if (priceAndTax.getPriceEntered() != null)
{
ic.setPriceEntered(priceAndTax.getPriceEntered()); // task 06727
}
if (priceAndTax.getPriceActual() != null)
{
ic.setPriceActual(priceAndTax.getPriceActual());
}
if (priceAndTax.getPriceUOMId() != null)
{
ic.setPrice_UOM_ID(priceAndTax.getPriceUOMId().getRepoId());
}
if (priceAndTax.getDiscount() != null)
{
ic.setDiscount(Percent.toBigDecimalOrZero(priceAndTax.getDiscount()));
}
if (priceAndTax.getInvoicableQtyBasedOn() != null)
{
ic.setInvoicableQtyBasedOn(priceAndTax.getInvoicableQtyBasedOn().getCode());
}
// | // Tax
if (priceAndTax.getTaxIncluded() != null)
{
ic.setIsTaxIncluded(priceAndTax.getTaxIncluded());
}
if (priceAndTax.getTaxId() != null)
{
ic.setC_Tax_ID(priceAndTax.getTaxId().getRepoId());
}
//
// Compensation group
if (priceAndTax.getCompensationGroupBaseAmt() != null)
{
ic.setGroupCompensationBaseAmt(priceAndTax.getCompensationGroupBaseAmt());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\IInvoiceCandInvalidUpdater.java | 1 |
请完成以下Java代码 | public CurrencyConversionContext getCurrencyConversionContext(@NonNull final I_M_InOut inout)
{
final CurrencyConversionContext conversionCtx = currencyBL.createCurrencyConversionContext(
inout.getDateAcct().toInstant(),
(CurrencyConversionTypeId)null,
ClientId.ofRepoId(inout.getAD_Client_ID()),
OrgId.ofRepoId(inout.getAD_Org_ID()));
return conversionCtx;
}
@Override
public Money getCOGSBySalesOrderId(
@NonNull final OrderLineId salesOrderLineId,
@NonNull final AcctSchemaId acctSchemaId)
{
final List<FactAcctQuery> factAcctQueries = getLineIdsByOrderLineIds(ImmutableSet.of(salesOrderLineId))
.stream()
.map(inoutAndLineId -> FactAcctQuery.builder()
.acctSchemaId(acctSchemaId)
.accountConceptualName(AccountConceptualName.ofString(I_M_Product_Acct.COLUMNNAME_P_COGS_Acct))
.tableName(I_M_InOut.Table_Name)
.recordId(inoutAndLineId.getInOutId().getRepoId())
.lineId(inoutAndLineId.getInOutLineId().getRepoId())
.build())
.collect(Collectors.toList());
return factAcctBL.getAcctBalance(factAcctQueries)
.orElseGet(() -> Money.zero(acctSchemaBL.getAcctCurrencyId(acctSchemaId)));
}
@Override
public ImmutableSet<I_M_InOut> getNotVoidedNotReversedForOrderId(@NonNull final OrderId orderId)
{
final InOutQuery query = InOutQuery.builder()
.orderId(orderId) | .excludeDocStatuses(ImmutableSet.of(DocStatus.Voided, DocStatus.Reversed))
.build();
return inOutDAO.retrieveByQuery(query).collect(ImmutableSet.toImmutableSet());
}
@Override
public void setShipperId(@NonNull final I_M_InOut inout)
{
inout.setM_Shipper_ID(ShipperId.toRepoId(findShipperId(inout)));
}
private ShipperId findShipperId(@NonNull final I_M_InOut inout)
{
if (inout.getDropShip_BPartner_ID() > 0 && inout.getDropShip_Location_ID() > 0)
{
final Optional<ShipperId> deliveryAddressShipperId = bpartnerDAO.getShipperIdByBPLocationId(BPartnerLocationId.ofRepoId(inout.getDropShip_BPartner_ID(), inout.getDropShip_Location_ID()));
if (deliveryAddressShipperId.isPresent())
{
return deliveryAddressShipperId.get(); // we are done
}
}
return bpartnerDAO.getShipperId(CoalesceUtil.coalesceSuppliersNotNull(
() -> BPartnerId.ofRepoIdOrNull(inout.getDropShip_BPartner_ID()),
() -> BPartnerId.ofRepoIdOrNull(inout.getC_BPartner_ID())));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\impl\InOutBL.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.