instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public void setBytes(byte[] bytes) {
this.bytes = bytes;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public Object getPersistentState() {
return ResourceEntityImpl.class;
}
public void setGenerated(boolean generated) { | this.generated = generated;
}
/**
* Indicated whether or not the resource has been generated while deploying rather than being actual part of the deployment.
*/
public boolean isGenerated() {
return generated;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
return "ResourceEntity[id=" + id + ", name=" + name + "]";
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ResourceEntityImpl.java | 1 |
请完成以下Java代码 | public LocalDate getDocumentDate(final DocumentTableFields docFields)
{
final I_C_RemittanceAdvice remittanceAdvice = extractRemittanceAdvice(docFields);
return TimeUtil.asLocalDate(remittanceAdvice.getDateDoc());
}
@Override
public String completeIt(final DocumentTableFields docFields)
{
final I_C_RemittanceAdvice remittanceAdviceRecord = extractRemittanceAdvice(docFields);
final RemittanceAdviceId remittanceAdviceId = RemittanceAdviceId.ofRepoId(remittanceAdviceRecord.getC_RemittanceAdvice_ID());
final RemittanceAdvice remittanceAdvice = remittanceAdviceRepository.getRemittanceAdvice(remittanceAdviceId);
remittanceAdviceService.resolveRemittanceAdviceLines(remittanceAdvice);
remittanceAdviceRepository.updateRemittanceAdvice(remittanceAdvice);
remittanceAdvice.validateCompleteAction();
remittanceAdviceRecord.setDocAction(X_C_RemittanceAdvice.DOCACTION_Re_Activate);
remittanceAdviceRecord.setProcessed(true);
return X_C_RemittanceAdvice.DOCSTATUS_Completed;
}
@Override | public void reactivateIt(final DocumentTableFields docFields)
{
final I_C_RemittanceAdvice remittanceAdvice = extractRemittanceAdvice(docFields);
if (remittanceAdvice.getC_Payment_ID() > 0)
{
throw new AdempiereException("A payment was already created!");
}
remittanceAdvice.setProcessed(false);
remittanceAdvice.setDocAction(X_C_RemittanceAdvice.DOCACTION_Complete);
}
private static I_C_RemittanceAdvice extractRemittanceAdvice(final DocumentTableFields docFields)
{
return InterfaceWrapperHelper.create(docFields, I_C_RemittanceAdvice.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\remittanceadvice\document\C_RemittanceAdvice_DocHandler.java | 1 |
请完成以下Java代码 | public void setCarrier_Product_ID (final int Carrier_Product_ID)
{
if (Carrier_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_Carrier_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Carrier_Product_ID, Carrier_Product_ID);
}
@Override
public int getCarrier_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_Carrier_Product_ID);
}
@Override
public void setExternalId (final java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
} | @Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_Product.java | 1 |
请完成以下Java代码 | public int hashCode() {
int prime = 31;
int result = 1;
result = prime * result + ((model == null) ? 0 : model.hashCode());
result = prime * result + ((typeName == null) ? 0 : typeName.hashCode());
result = prime * result + ((typeNamespace == null) ? 0 : typeNamespace.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;
}
ModelElementTypeImpl other = (ModelElementTypeImpl) obj;
if (model == null) {
if (other.model != null) { | return false;
}
} else if (!model.equals(other.model)) {
return false;
}
if (typeName == null) {
if (other.typeName != null) {
return false;
}
} else if (!typeName.equals(other.typeName)) {
return false;
}
if (typeNamespace == null) {
if (other.typeNamespace != null) {
return false;
}
} else if (!typeNamespace.equals(other.typeNamespace)) {
return false;
}
return true;
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\ModelElementTypeImpl.java | 1 |
请完成以下Java代码 | public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Confirmed.
@param IsConfirmed
Assignment is confirmed
*/
public void setIsConfirmed (boolean IsConfirmed)
{
set_ValueNoCheck (COLUMNNAME_IsConfirmed, Boolean.valueOf(IsConfirmed));
}
/** Get Confirmed.
@return Assignment is confirmed
*/
public boolean isConfirmed ()
{
Object oo = get_Value(COLUMNNAME_IsConfirmed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Set Quantity.
@param Qty
Quantity
*/
public void setQty (BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty); | if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Resource Assignment.
@param S_ResourceAssignment_ID
Resource Assignment
*/
public void setS_ResourceAssignment_ID (int S_ResourceAssignment_ID)
{
if (S_ResourceAssignment_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ResourceAssignment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ResourceAssignment_ID, Integer.valueOf(S_ResourceAssignment_ID));
}
/** Get Resource Assignment.
@return Resource Assignment
*/
public int getS_ResourceAssignment_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceAssignment_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_S_Resource getS_Resource() throws RuntimeException
{
return (I_S_Resource)MTable.get(getCtx(), I_S_Resource.Table_Name)
.getPO(getS_Resource_ID(), get_TrxName()); }
/** Set Resource.
@param S_Resource_ID
Resource
*/
public void setS_Resource_ID (int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID));
}
/** Get Resource.
@return Resource
*/
public int getS_Resource_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_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(getS_Resource_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ResourceAssignment.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class CloudPlatformSecurityContextCondition { }
@ConditionalOnProperty({
"spring.data.gemfire.security.username",
"spring.data.gemfire.security.password",
})
static class SpringDataGeodeSecurityContextCondition { }
@ConditionalOnProperty({
"gemfire.security-username",
"gemfire.security-password",
})
static class UsingApacheGeodeSecurityContextCondition { }
}
// This custom PropertySource is required to prevent Pivotal Spring Cloud Services
// (spring-cloud-services-starter-service-registry) from losing the Apache Geode or Cloud Cache Security Context
// credentials stored in the Environment.
static class SpringDataGemFirePropertiesPropertySource extends PropertySource<Properties> {
private static final String SPRING_DATA_GEMFIRE_PROPERTIES_PROPERTY_SOURCE_NAME =
"spring.data.gemfire.properties";
SpringDataGemFirePropertiesPropertySource(Properties springDataGemFireProperties) {
this(SPRING_DATA_GEMFIRE_PROPERTIES_PROPERTY_SOURCE_NAME, springDataGemFireProperties); | }
SpringDataGemFirePropertiesPropertySource(String name, Properties springDataGemFireProperties) {
super(name, springDataGemFireProperties);
}
@Nullable @Override
public Object getProperty(String name) {
return getSource().getProperty(name);
}
@Override
public boolean containsProperty(String name) {
return getSource().containsKey(name);
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\ClientSecurityAutoConfiguration.java | 2 |
请完成以下Java代码 | public void postProcessEngineBuild(ProcessEngine processEngine) {
if(!authorizationEnabled) {
return;
}
final AuthorizationService authorizationService = processEngine.getAuthorizationService();
if(administratorGroupName != null && administratorGroupName.length()>0) {
// create ADMIN authorizations on all built-in resources for configured group
for (Resource resource : Resources.values()) {
if(authorizationService.createAuthorizationQuery().groupIdIn(administratorGroupName).resourceType(resource).resourceId(ANY).count() == 0) {
AuthorizationEntity adminGroupAuth = new AuthorizationEntity(AUTH_TYPE_GRANT);
adminGroupAuth.setGroupId(administratorGroupName);
adminGroupAuth.setResource(resource);
adminGroupAuth.setResourceId(ANY);
adminGroupAuth.addPermission(ALL);
authorizationService.saveAuthorization(adminGroupAuth);
LOG.grantGroupPermissions(administratorGroupName, resource.resourceName());
}
}
}
if(administratorUserName != null && administratorUserName.length()>0) {
// create ADMIN authorizations on all built-in resources for configured user
for (Resource resource : Resources.values()) {
if(authorizationService.createAuthorizationQuery().userIdIn(administratorUserName).resourceType(resource).resourceId(ANY).count() == 0) {
AuthorizationEntity adminUserAuth = new AuthorizationEntity(AUTH_TYPE_GRANT);
adminUserAuth.setUserId(administratorUserName);
adminUserAuth.setResource(resource);
adminUserAuth.setResourceId(ANY);
adminUserAuth.addPermission(ALL);
authorizationService.saveAuthorization(adminUserAuth);
LOG.grantUserPermissions(administratorUserName, resource.resourceName());
}
}
}
} | // getter / setters ////////////////////////////////////
public String getAdministratorGroupName() {
return administratorGroupName;
}
public void setAdministratorGroupName(String administratorGroupName) {
this.administratorGroupName = administratorGroupName;
}
public String getAdministratorUserName() {
return administratorUserName;
}
public void setAdministratorUserName(String administratorUserName) {
this.administratorUserName = administratorUserName;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\plugin\AdministratorAuthorizationPlugin.java | 1 |
请完成以下Java代码 | public String getSaleRefNb() {
return saleRefNb;
}
/**
* Sets the value of the saleRefNb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSaleRefNb(String value) {
this.saleRefNb = value;
}
/**
* Gets the value of the seqNb property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSeqNb() {
return seqNb;
}
/**
* Sets the value of the seqNb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSeqNb(String value) {
this.seqNb = value;
}
/**
* Gets the value of the txId property.
*
* @return
* possible object is
* {@link TransactionIdentifier1 }
*
*/
public TransactionIdentifier1 getTxId() {
return txId;
}
/**
* Sets the value of the txId property.
*
* @param value
* allowed object is
* {@link TransactionIdentifier1 }
*
*/
public void setTxId(TransactionIdentifier1 value) {
this.txId = value;
}
/**
* Gets the value of the pdct property.
*
* @return
* possible object is
* {@link Product2 }
*
*/
public Product2 getPdct() {
return pdct; | }
/**
* Sets the value of the pdct property.
*
* @param value
* allowed object is
* {@link Product2 }
*
*/
public void setPdct(Product2 value) {
this.pdct = value;
}
/**
* Gets the value of the vldtnDt property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getVldtnDt() {
return vldtnDt;
}
/**
* Sets the value of the vldtnDt property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setVldtnDt(XMLGregorianCalendar value) {
this.vldtnDt = value;
}
/**
* Gets the value of the vldtnSeqNb property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getVldtnSeqNb() {
return vldtnSeqNb;
}
/**
* Sets the value of the vldtnSeqNb property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setVldtnSeqNb(String value) {
this.vldtnSeqNb = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\CardIndividualTransaction1.java | 1 |
请完成以下Java代码 | public boolean isSkipIoMappings() {
return skipIoMappings;
}
public void setSkipIoMappings(boolean skipIoMappings) {
this.skipIoMappings = skipIoMappings;
}
public boolean isSkipCustomListeners() {
return skipCustomListeners;
}
public void setSkipCustomListeners(boolean skipCustomListeners) {
this.skipCustomListeners = skipCustomListeners;
}
public void applyTo(ModificationBuilder builder, ProcessEngine processEngine, ObjectMapper objectMapper) {
for (ProcessInstanceModificationInstructionDto instruction : instructions) {
instruction.applyTo(builder, processEngine, objectMapper);
} | }
public String getAnnotation() {
return annotation;
}
public void setAnnotation(String annotation) {
this.annotation = annotation;
}
public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\ModificationDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ConvertListToMapService {
public Map<Integer, Animal> convertListBeforeJava8(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<>();
for (Animal animal : list) {
map.put(animal.getId(), animal);
}
return map;
}
public Map<Integer, Animal> convertListAfterJava8(List<Animal> list) {
Map<Integer, Animal> map = list.stream().collect(Collectors.toMap(Animal::getId, Function.identity()));
return map;
} | public Map<Integer, Animal> convertListWithGuava(List<Animal> list) {
Map<Integer, Animal> map = Maps.uniqueIndex(list, Animal::getId);
return map;
}
public Map<Integer, Animal> convertListWithApacheCommons(List<Animal> list) {
Map<Integer, Animal> map = new HashMap<>();
MapUtils.populateMap(map, list, Animal::getId);
return map;
}
} | repos\tutorials-master\core-java-modules\core-java-collections-conversions\src\main\java\com\baeldung\convertlisttomap\ConvertListToMapService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.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;
}
EventSubscriptionEntityImpl other = (EventSubscriptionEntityImpl) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName().replace("EntityImpl", "")).append("[")
.append("id=").append(id) | .append(", eventType=").append(eventType);
if (activityId != null) {
sb.append(", activityId=").append(activityId);
}
if (executionId != null) {
sb.append(", processInstanceId=").append(processInstanceId)
.append(", executionId=").append(executionId);
} else if (scopeId != null) {
sb.append(", scopeId=").append(scopeId)
.append(", subScopeId=").append(subScopeId)
.append(", scopeType=").append(scopeType)
.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
if (processDefinitionId != null) {
sb.append(", processDefinitionId=").append(processDefinitionId);
} else if (scopeDefinitionId != null) {
if (scopeId == null) {
sb.append(", scopeType=").append(scopeType);
}
sb.append(", scopeDefinitionId=").append(scopeDefinitionId);
}
if (scopeDefinitionKey != null) {
sb.append(", scopeDefinitionKey=").append(scopeDefinitionKey);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\persistence\entity\EventSubscriptionEntityImpl.java | 2 |
请完成以下Java代码 | public String getProofPics() {
return proofPics;
}
public void setProofPics(String proofPics) {
this.proofPics = proofPics;
}
public String getHandleNote() {
return handleNote;
}
public void setHandleNote(String handleNote) {
this.handleNote = handleNote;
}
public String getHandleMan() {
return handleMan;
}
public void setHandleMan(String handleMan) {
this.handleMan = handleMan;
}
public String getReceiveMan() {
return receiveMan;
}
public void setReceiveMan(String receiveMan) {
this.receiveMan = receiveMan;
}
public Date getReceiveTime() {
return receiveTime;
}
public void setReceiveTime(Date receiveTime) {
this.receiveTime = receiveTime;
}
public String getReceiveNote() {
return receiveNote;
}
public void setReceiveNote(String receiveNote) {
this.receiveNote = receiveNote;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", orderId=").append(orderId);
sb.append(", companyAddressId=").append(companyAddressId); | sb.append(", productId=").append(productId);
sb.append(", orderSn=").append(orderSn);
sb.append(", createTime=").append(createTime);
sb.append(", memberUsername=").append(memberUsername);
sb.append(", returnAmount=").append(returnAmount);
sb.append(", returnName=").append(returnName);
sb.append(", returnPhone=").append(returnPhone);
sb.append(", status=").append(status);
sb.append(", handleTime=").append(handleTime);
sb.append(", productPic=").append(productPic);
sb.append(", productName=").append(productName);
sb.append(", productBrand=").append(productBrand);
sb.append(", productAttr=").append(productAttr);
sb.append(", productCount=").append(productCount);
sb.append(", productPrice=").append(productPrice);
sb.append(", productRealPrice=").append(productRealPrice);
sb.append(", reason=").append(reason);
sb.append(", description=").append(description);
sb.append(", proofPics=").append(proofPics);
sb.append(", handleNote=").append(handleNote);
sb.append(", handleMan=").append(handleMan);
sb.append(", receiveMan=").append(receiveMan);
sb.append(", receiveTime=").append(receiveTime);
sb.append(", receiveNote=").append(receiveNote);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\OmsOrderReturnApply.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private TaxCategoryId getTaxCategoryId(
@NonNull final I_C_Invoice invoice,
@NonNull final I_C_InvoiceLine invoiceLine,
@NonNull final CountryId taxCountryId)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID());
final I_C_UOM uom = uomDAO.getById(invoiceLine.getPrice_UOM_ID());
final IEditablePricingContext pricingContext = pricingBL.createInitialContext(OrgId.ofRepoId(invoice.getAD_Org_ID()),
ProductId.ofRepoId(invoiceLine.getM_Product_ID()),
bPartnerId,
Quantity.of(invoiceLine.getQtyInvoicedInPriceUOM(), uom),
SOTrx.ofBoolean(invoice.isSOTrx()))
.setCountryId(taxCountryId);
final IPricingResult priceResult = pricingBL.calculatePrice(pricingContext);
if (!priceResult.isCalculated())
{
throw new AdempiereException("Price could not be calculated for C_InvoiceLine")
.appendParametersToMessage()
.setParameter("C_InvoiceLine_ID", invoiceLine.getC_InvoiceLine_ID());
}
return priceResult.getTaxCategoryId();
}
@NonNull
private CountryId getTaxCountryId(@NonNull final I_C_Invoice invoice, @NonNull final I_C_InvoiceLine invoiceLine)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(invoice.getC_BPartner_ID());
final Supplier<LocationId> getLocationFromBillPartner = () -> {
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(bPartnerId, invoice.getC_BPartner_Location_ID());
return bpartnerDAO.getLocationId(bPartnerLocationId);
};
final LocationId locationId = Stream.of(invoiceLine.getC_Shipping_Location_ID(), invoice.getC_BPartner_Location_Value_ID())
.map(LocationId::ofRepoIdOrNull)
.filter(Objects::nonNull)
.findFirst()
.orElseGet(getLocationFromBillPartner);
return locationDAO.getCountryIdByLocationId(locationId);
}
@Value | private static class InvoiceVerificationRunResult
{
@NonNull
Tax invoiceTax;
@Nullable
Tax resultingTax;
@NonNull
InvoiceVerificationSetLineId setLineId;
@NonNull
OrgId orgId;
@Nullable
String log;
@Builder
public InvoiceVerificationRunResult(final @NonNull Tax invoiceTax,
final @Nullable Tax resultingTax,
final @NonNull InvoiceVerificationSetLineId setLineId,
final @NonNull OrgId orgId,
@Nullable final String log)
{
this.invoiceTax = invoiceTax;
this.resultingTax = resultingTax;
this.setLineId = setLineId;
this.orgId = orgId;
this.log = log;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceVerificationBL.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected void setOwner(TenantId tenantId, Customer customer, IdProvider idProvider) {
customer.setTenantId(tenantId);
}
@Override
protected Customer prepare(EntitiesImportCtx ctx, Customer customer, Customer old, EntityExportData<Customer> exportData, IdProvider idProvider) {
if (customer.isPublic()) {
Customer publicCustomer = customerService.findOrCreatePublicCustomer(ctx.getTenantId());
publicCustomer.setExternalId(customer.getExternalId());
return publicCustomer;
} else {
return customer;
}
}
@Override
protected Customer saveOrUpdate(EntitiesImportCtx ctx, Customer customer, EntityExportData<Customer> exportData, IdProvider idProvider, CompareResult compareResult) {
if (!customer.isPublic()) {
return customerService.saveCustomer(customer);
} else { | return customerDao.save(ctx.getTenantId(), customer);
}
}
@Override
protected Customer deepCopy(Customer customer) {
return new Customer(customer);
}
@Override
public EntityType getEntityType() {
return EntityType.CUSTOMER;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\ie\importing\impl\CustomerImportService.java | 2 |
请完成以下Java代码 | final class RootContextMenuAction extends AbstractContextMenuAction
{
public static final RootContextMenuAction EMPTY = new RootContextMenuAction();
private final List<IContextMenuAction> actions;
/**
* Empty constructor
*/
private RootContextMenuAction()
{
super();
this.actions = Collections.emptyList();
}
/* package */RootContextMenuAction(List<IContextMenuAction> actions)
{
super();
this.actions = actions;
}
@Override
public String getName()
{
return null;
}
@Override
public String getIcon()
{
return null;
}
@Override
public boolean isAvailable()
{
return true;
}
@Override | public boolean isRunnable()
{
return true;
}
@Override
public List<IContextMenuAction> getChildren()
{
return actions;
}
@Override
public void run()
{
// shall not be invoked
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\impl\RootContextMenuAction.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private String name;
private Long salary;
// constructors
public Employee() {
}
public Employee(final Integer id, final String name, final Long salary) {
super();
this.id = id;
this.name = name;
this.salary = salary;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
} | final Employee other = (Employee) obj;
if (id == null) {
if (other.id != null) {
return false;
}
} else if (!id.equals(other.id)) {
return false;
}
return true;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Long getSalary() {
return salary;
}
public void setSalary(Long salary) {
this.salary = salary;
}
} | repos\tutorials-master\persistence-modules\hibernate-queries\src\main\java\com\baeldung\hibernate\criteria\model\Employee.java | 2 |
请完成以下Java代码 | private static SortedSet<LocalDateTime> newSortedSet(final Collection<LocalDateTime> values)
{
if (values == null || values.isEmpty())
{
return new TreeSet<>();
}
else
{
return new TreeSet<>(values);
}
}
private static SortedSet<LocalDateTime> newReverseSortedSet(final Collection<LocalDateTime> values)
{
final TreeSet<LocalDateTime> sortedSet = new TreeSet<>(Comparator.<LocalDateTime> naturalOrder().reversed());
if (values != null && !values.isEmpty())
{
sortedSet.addAll(values);
}
return sortedSet;
}
private static LocalDateTime max(final Collection<LocalDateTime> dates)
{
Check.assumeNotEmpty(dates, "dates is not empty");
return dates.stream().max(Comparator.naturalOrder()).get();
}
//
//
//
//
//
public static class DateSequenceGeneratorBuilder
{
public DateSequenceGeneratorBuilder byDay()
{
return incrementor(CalendarIncrementors.dayByDay());
}
/**
* Iterate each <code>day</code> days.
*
* @param day
* @return this
*/
public DateSequenceGeneratorBuilder byNthDay(final int day)
{
return incrementor(CalendarIncrementors.eachNthDay(day));
}
public DateSequenceGeneratorBuilder byWeeks(final int week, final DayOfWeek dayOfWeek)
{
return incrementor(CalendarIncrementors.eachNthWeek(week, dayOfWeek));
}
public DateSequenceGeneratorBuilder byMonths(final int months, final int dayOfMonth)
{
return incrementor(CalendarIncrementors.eachNthMonth(months, dayOfMonth));
}
public DateSequenceGeneratorBuilder frequency(@NonNull final Frequency frequency)
{
incrementor(createCalendarIncrementor(frequency));
exploder(createDateSequenceExploder(frequency));
return this;
}
private static ICalendarIncrementor createCalendarIncrementor(final Frequency frequency)
{
if (frequency.isWeekly()) | {
return CalendarIncrementors.eachNthWeek(frequency.getEveryNthWeek(), DayOfWeek.MONDAY);
}
else if (frequency.isMonthly())
{
return CalendarIncrementors.eachNthMonth(frequency.getEveryNthMonth(), 1); // every given month, 1st day
}
else
{
throw new IllegalArgumentException("Frequency type not supported for " + frequency);
}
}
private static IDateSequenceExploder createDateSequenceExploder(final Frequency frequency)
{
if (frequency.isWeekly())
{
if (frequency.isOnlySomeDaysOfTheWeek())
{
return DaysOfWeekExploder.of(frequency.getOnlyDaysOfWeek());
}
else
{
return DaysOfWeekExploder.ALL_DAYS_OF_WEEK;
}
}
else if (frequency.isMonthly())
{
return DaysOfMonthExploder.of(frequency.getOnlyDaysOfMonth());
}
else
{
throw new IllegalArgumentException("Frequency type not supported for " + frequency);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\generator\DateSequenceGenerator.java | 1 |
请完成以下Java代码 | public void onAfterQuery(final ICalloutRecord calloutRecord)
{
try
{
tabCallout.onAfterQuery(calloutRecord);
}
catch (final Exception e)
{
handleException("onAfterQuery", calloutRecord, e);
}
}
private static final class StatefulExceptionHandledTabCallout extends ExceptionHandledTabCallout implements IStatefulTabCallout
{
private StatefulExceptionHandledTabCallout(final IStatefulTabCallout tabCallout)
{
super(tabCallout); | }
@Override
public void onInit(final ICalloutRecord calloutRecord)
{
try
{
((IStatefulTabCallout)tabCallout).onInit(calloutRecord);
}
catch (final Exception e)
{
handleException("onInit", calloutRecord, e);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\spi\ExceptionHandledTabCallout.java | 1 |
请完成以下Java代码 | private Optional<Cell> getCommonValue(@NonNull final String columnName)
{
if (rowsList.isEmpty())
{
return Optional.empty();
}
final Cell firstValue = rowsList.get(0).getCell(columnName);
for (int i = 1; i < rowsList.size(); i++)
{
final Cell value = rowsList.get(i).getCell(columnName);
if (!Objects.equals(value, firstValue))
{
return Optional.empty();
}
}
return Optional.of(firstValue); | }
public TablePrinter toPrint()
{
return new TablePrinter(this);
}
public String toTabularString()
{
return toPrint().toString();
}
@Override
@Deprecated
public String toString() {return toTabularString();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\text\tabular\Table.java | 1 |
请完成以下Java代码 | public Builder tokenRevocationEndpoint(String tokenRevocationEndpoint) {
return setting(ConfigurationSettingNames.AuthorizationServer.TOKEN_REVOCATION_ENDPOINT,
tokenRevocationEndpoint);
}
/**
* Sets the OAuth 2.0 Token Introspection endpoint.
* @param tokenIntrospectionEndpoint the Token Introspection endpoint
* @return the {@link Builder} for further configuration
*/
public Builder tokenIntrospectionEndpoint(String tokenIntrospectionEndpoint) {
return setting(ConfigurationSettingNames.AuthorizationServer.TOKEN_INTROSPECTION_ENDPOINT,
tokenIntrospectionEndpoint);
}
/**
* Sets the OAuth 2.0 Dynamic Client Registration endpoint.
* @param clientRegistrationEndpoint the OAuth 2.0 Dynamic Client Registration
* endpoint
* @return the {@link Builder} for further configuration
*/
public Builder clientRegistrationEndpoint(String clientRegistrationEndpoint) {
return setting(ConfigurationSettingNames.AuthorizationServer.CLIENT_REGISTRATION_ENDPOINT,
clientRegistrationEndpoint);
}
/**
* Sets the OpenID Connect 1.0 Client Registration endpoint.
* @param oidcClientRegistrationEndpoint the OpenID Connect 1.0 Client
* Registration endpoint
* @return the {@link Builder} for further configuration
*/
public Builder oidcClientRegistrationEndpoint(String oidcClientRegistrationEndpoint) {
return setting(ConfigurationSettingNames.AuthorizationServer.OIDC_CLIENT_REGISTRATION_ENDPOINT,
oidcClientRegistrationEndpoint);
}
/**
* Sets the OpenID Connect 1.0 UserInfo endpoint.
* @param oidcUserInfoEndpoint the OpenID Connect 1.0 UserInfo endpoint
* @return the {@link Builder} for further configuration
*/
public Builder oidcUserInfoEndpoint(String oidcUserInfoEndpoint) {
return setting(ConfigurationSettingNames.AuthorizationServer.OIDC_USER_INFO_ENDPOINT, oidcUserInfoEndpoint);
} | /**
* Sets the OpenID Connect 1.0 Logout endpoint.
* @param oidcLogoutEndpoint the OpenID Connect 1.0 Logout endpoint
* @return the {@link Builder} for further configuration
*/
public Builder oidcLogoutEndpoint(String oidcLogoutEndpoint) {
return setting(ConfigurationSettingNames.AuthorizationServer.OIDC_LOGOUT_ENDPOINT, oidcLogoutEndpoint);
}
/**
* Builds the {@link AuthorizationServerSettings}.
* @return the {@link AuthorizationServerSettings}
*/
@Override
public AuthorizationServerSettings build() {
AuthorizationServerSettings authorizationServerSettings = new AuthorizationServerSettings(getSettings());
if (authorizationServerSettings.getIssuer() != null
&& authorizationServerSettings.isMultipleIssuersAllowed()) {
throw new IllegalArgumentException("The issuer identifier (" + authorizationServerSettings.getIssuer()
+ ") cannot be set when isMultipleIssuersAllowed() is true.");
}
return authorizationServerSettings;
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\settings\AuthorizationServerSettings.java | 1 |
请完成以下Java代码 | protected Map<String, Object> extractAttributes(HttpSession session) {
return createMigratedAttributeMap(session);
}
@Override
final HttpSession applySessionFixation(HttpServletRequest request) {
HttpSession session = request.getSession();
String originalSessionId = session.getId();
this.logger.debug(LogMessage.of(() -> "Invalidating session with Id '" + originalSessionId + "' "
+ (this.migrateSessionAttributes ? "and" : "without") + " migrating attributes."));
Map<String, Object> attributesToMigrate = extractAttributes(session);
int maxInactiveIntervalToMigrate = session.getMaxInactiveInterval();
session.invalidate();
session = request.getSession(true); // we now have a new session
this.logger.debug(LogMessage.format("Started new session: %s", session.getId()));
transferAttributes(attributesToMigrate, session);
if (this.migrateSessionAttributes) {
session.setMaxInactiveInterval(maxInactiveIntervalToMigrate);
}
return session;
}
/**
* @param attributes the attributes which were extracted from the original session by
* {@code extractAttributes}
* @param newSession the newly created session
*/
void transferAttributes(Map<String, Object> attributes, HttpSession newSession) {
if (attributes != null) {
attributes.forEach(newSession::setAttribute);
}
}
@SuppressWarnings("unchecked")
private HashMap<String, Object> createMigratedAttributeMap(HttpSession session) {
HashMap<String, Object> attributesToMigrate = new HashMap<>();
Enumeration<String> enumeration = session.getAttributeNames();
while (enumeration.hasMoreElements()) {
String key = enumeration.nextElement();
if (!this.migrateSessionAttributes && !key.startsWith("SPRING_SECURITY_")) {
// Only retain Spring Security attributes
continue; | }
attributesToMigrate.put(key, session.getAttribute(key));
}
return attributesToMigrate;
}
/**
* Defines whether attributes should be migrated to a new session or not. Has no
* effect if you override the {@code extractAttributes} method.
* <p>
* Attributes used by Spring Security (to store cached requests, for example) will
* still be retained by default, even if you set this value to {@code false}.
* @param migrateSessionAttributes whether the attributes from the session should be
* transferred to the new, authenticated session.
*/
public void setMigrateSessionAttributes(boolean migrateSessionAttributes) {
this.migrateSessionAttributes = migrateSessionAttributes;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\session\SessionFixationProtectionStrategy.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void write(JsonWriter out, java.sql.Date date) throws IOException
{
if (date == null)
{
out.nullValue();
}
else
{
String value;
if (dateFormat != null)
{
value = dateFormat.format(date);
}
else
{
value = date.toString();
}
out.value(value);
}
}
@Override
public java.sql.Date read(JsonReader in) throws IOException
{
switch (in.peek())
{
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try
{
if (dateFormat != null)
{
return new java.sql.Date(dateFormat.parse(date).getTime());
}
return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime());
}
catch (ParseException e)
{
throw new JsonParseException(e);
}
}
}
}
/**
* Gson TypeAdapter for java.util.Date type
* If the dateFormat is null, ISO8601Utils will be used.
*/
public static class DateTypeAdapter extends TypeAdapter<Date>
{
private DateFormat dateFormat;
public DateTypeAdapter()
{
}
public DateTypeAdapter(DateFormat dateFormat)
{
this.dateFormat = dateFormat;
}
public void setFormat(DateFormat dateFormat)
{
this.dateFormat = dateFormat;
}
@Override
public void write(JsonWriter out, Date date) throws IOException
{
if (date == null)
{
out.nullValue();
}
else
{ | String value;
if (dateFormat != null)
{
value = dateFormat.format(date);
}
else
{
value = ISO8601Utils.format(date, true);
}
out.value(value);
}
}
@Override
public Date read(JsonReader in) throws IOException
{
try
{
switch (in.peek())
{
case NULL:
in.nextNull();
return null;
default:
String date = in.nextString();
try
{
if (dateFormat != null)
{
return dateFormat.parse(date);
}
return ISO8601Utils.parse(date, new ParsePosition(0));
}
catch (ParseException e)
{
throw new JsonParseException(e);
}
}
}
catch (IllegalArgumentException e)
{
throw new JsonParseException(e);
}
}
}
public JSON setDateFormat(DateFormat dateFormat)
{
dateTypeAdapter.setFormat(dateFormat);
return this;
}
public JSON setSqlDateFormat(DateFormat dateFormat)
{
sqlDateTypeAdapter.setFormat(dateFormat);
return this;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\invoker\JSON.java | 2 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
@Override
public String getName() {
return name;
}
@Override
public VariableType getVariableType() {
return variableType;
}
@Override
public void setVariableType(VariableType variableType) {
this.variableType = variableType;
}
@Override
public Long getLongValue() {
return longValue;
}
@Override
public void setLongValue(Long longValue) {
this.longValue = longValue;
}
@Override
public Double getDoubleValue() {
return doubleValue;
}
@Override
public void setDoubleValue(Double doubleValue) {
this.doubleValue = doubleValue;
}
@Override
public String getTextValue() {
return textValue;
}
@Override
public void setTextValue(String textValue) {
this.textValue = textValue;
}
@Override
public String getTextValue2() {
return textValue2;
}
@Override
public void setTextValue2(String textValue2) {
this.textValue2 = textValue2;
}
@Override
public Object getCachedValue() {
return cachedValue;
}
@Override
public void setCachedValue(Object cachedValue) {
this.cachedValue = cachedValue;
}
// common methods ///////////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricDetailVariableInstanceUpdateEntity["); | sb.append("id=").append(id);
sb.append(", name=").append(name);
sb.append(", type=").append(variableType != null ? variableType.getTypeName() : "null");
if (longValue != null) {
sb.append(", longValue=").append(longValue);
}
if (doubleValue != null) {
sb.append(", doubleValue=").append(doubleValue);
}
if (textValue != null) {
sb.append(", textValue=").append(StringUtils.abbreviate(textValue, 40));
}
if (textValue2 != null) {
sb.append(", textValue2=").append(StringUtils.abbreviate(textValue2, 40));
}
if (byteArrayRef != null && byteArrayRef.getId() != null) {
sb.append(", byteArrayValueId=").append(byteArrayRef.getId());
}
sb.append("]");
return sb.toString();
}
@Override
public String getScopeId() {
return null;
}
@Override
public String getSubScopeId() {
return null;
}
@Override
public String getScopeType() {
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricDetailVariableInstanceUpdateEntityImpl.java | 1 |
请完成以下Java代码 | private IDunnableSource createSource(Class<? extends IDunnableSource> sourceClass)
{
final IDunnableSource source;
try
{
source = sourceClass.newInstance();
return source;
}
catch (Exception e)
{
throw new DunningException("Cannot create dunning source for " + sourceClass, e);
}
}
@Override
public void registerSource(Class<? extends IDunnableSource> clazz) | {
if (dunnableSources.containsKey(clazz))
{
return;
}
final IDunnableSource source = createSource(clazz);
dunnableSources.put(clazz, source);
}
@Override
public String toString()
{
return "DefaultDunnableSourceFactory [dunnableSources=" + dunnableSources + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DefaultDunnableSourceFactory.java | 1 |
请完成以下Java代码 | public abstract class ValuedDataObject extends DataObject {
protected Object value;
public Object getValue() {
return value;
}
public abstract void setValue(Object value);
public abstract ValuedDataObject clone();
public void setValues(ValuedDataObject otherElement) {
super.setValues(otherElement);
if (otherElement.getValue() != null) {
setValue(otherElement.getValue());
}
}
public String getType() {
String structureRef = itemSubjectRef.getStructureRef();
return structureRef.substring(structureRef.indexOf(':') + 1);
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
} | ValuedDataObject otherObject = (ValuedDataObject) o;
if (!otherObject.getItemSubjectRef().getStructureRef().equals(this.itemSubjectRef.getStructureRef())) {
return false;
}
if (!otherObject.getId().equals(this.id)) {
return false;
}
if (!otherObject.getName().equals(this.name)) {
return false;
}
if (!otherObject.getValue().equals(this.value.toString())) {
return false;
}
return true;
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ValuedDataObject.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ConfigPropertiesController {
@Value("${baeldung.archaius.properties.one:not found!}")
private String propertyOneWithValue;
@Value("${baeldung.archaius.properties.two:not found!}")
private String propertyTwoWithValue;
@Value("${baeldung.archaius.properties.three:not found!}")
private String propertyThreeWithValue;
@Value("${baeldung.archaius.properties.four:not found!}")
private String propertyFourWithValue;
private DynamicStringProperty propertyOneWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.one", "not found!");
private DynamicStringProperty propertyTwoWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.two", "not found!");
private DynamicStringProperty propertyThreeWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.three", "not found!");
private DynamicStringProperty propertyFourWithDynamic = DynamicPropertyFactory.getInstance()
.getStringProperty("baeldung.archaius.properties.four", "not found!"); | @GetMapping("/properties-from-value")
public Map<String, String> getPropertiesFromValue() {
Map<String, String> properties = new HashMap<>();
properties.put("baeldung.archaius.properties.one", propertyOneWithValue);
properties.put("baeldung.archaius.properties.two", propertyTwoWithValue);
properties.put("baeldung.archaius.properties.three", propertyThreeWithValue);
properties.put("baeldung.archaius.properties.four", propertyFourWithValue);
return properties;
}
@GetMapping("/properties-from-dynamic")
public Map<String, String> getPropertiesFromDynamic() {
Map<String, String> properties = new HashMap<>();
properties.put("baeldung.archaius.properties.one", propertyOneWithDynamic.get());
properties.put("baeldung.archaius.properties.two", propertyTwoWithDynamic.get());
properties.put("baeldung.archaius.properties.three", propertyThreeWithDynamic.get());
properties.put("baeldung.archaius.properties.four", propertyFourWithDynamic.get());
return properties;
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-archaius\spring-cloud-archaius-extra-configs\src\main\java\com\baeldung\spring\cloud\archaius\extraconfigs\controllers\ConfigPropertiesController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ProactiveNotification {
protected int channel;
@XmlElement(required = true)
protected String value;
protected int rule;
@XmlElement(required = true)
protected String language;
/**
* Gets the value of the channel property.
*
*/
public int getChannel() {
return channel;
}
/**
* Sets the value of the channel property.
*
*/
public void setChannel(int value) {
this.channel = value;
}
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value; | }
/**
* Gets the value of the rule property.
*
*/
public int getRule() {
return rule;
}
/**
* Sets the value of the rule property.
*
*/
public void setRule(int value) {
this.rule = value;
}
/**
* Gets the value of the language property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLanguage() {
return language;
}
/**
* Sets the value of the language property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLanguage(String value) {
this.language = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ProactiveNotification.java | 2 |
请完成以下Java代码 | private void extractCandidateUsersAndGroups(org.activiti.engine.task.Task source, TaskImpl destination) {
List<IdentityLink> candidates = taskService.getIdentityLinksForTask(source.getId());
destination.setCandidateGroups(extractCandidatesBy(candidates, IdentityLink::getGroupId));
destination.setCandidateUsers(extractCandidatesBy(candidates, IdentityLink::getUserId));
}
private List<String> extractCandidatesBy(List<IdentityLink> candidates, Function<IdentityLink, String> extractor) {
List<String> result = emptyList();
if (candidates != null) {
result = candidates
.stream()
.filter(candidate -> IdentityLinkType.CANDIDATE.equals(candidate.getType()))
.map(extractor::apply)
.filter(Objects::nonNull)
.collect(Collectors.toList()); | }
return result;
}
private Task.TaskStatus calculateStatus(org.activiti.engine.task.Task source) {
if (source instanceof TaskEntity && (((TaskEntity) source).isDeleted() || ((TaskEntity) source).isCanceled())) {
return Task.TaskStatus.CANCELLED;
} else if (source.isSuspended()) {
return Task.TaskStatus.SUSPENDED;
} else if (source.getAssignee() != null && !source.getAssignee().isEmpty()) {
return Task.TaskStatus.ASSIGNED;
}
return Task.TaskStatus.CREATED;
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\model\impl\APITaskConverter.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(rules)
.toString();
}
public static List<IValidationRule> unbox(@Nullable final IValidationRule rule)
{
if (rule == null || NullValidationRule.isNull(rule))
{
return ImmutableList.of();
}
final ArrayList<IValidationRule> result = new ArrayList<>();
unboxAndAppendToList(rule, result);
return result;
}
public static List<IValidationRule> unbox(@Nullable final Collection<IValidationRule> rules)
{
if (rules == null || rules.isEmpty())
{
return ImmutableList.of();
}
final ArrayList<IValidationRule> result = new ArrayList<>();
for (final IValidationRule rule : rules)
{
unboxAndAppendToList(rule, result);
}
return result;
}
private static void unboxAndAppendToList(@Nullable final IValidationRule rule, @NonNull final ArrayList<IValidationRule> list)
{
if (rule instanceof CompositeValidationRule)
{
final CompositeValidationRule compositeRule = (CompositeValidationRule)rule;
for (final IValidationRule childRule : compositeRule.rules)
{
unboxAndAppendToList(childRule, list);
}
}
else if (rule != null && !NullValidationRule.isNull(rule))
{
list.add(rule);
}
}
@SuppressWarnings("UnusedReturnValue")
public static final class Builder
{
private final List<IValidationRule> rules = new ArrayList<>();
private Builder() {}
public IValidationRule build()
{
if (rules.isEmpty())
{
return NullValidationRule.instance;
}
else if (rules.size() == 1)
{
return rules.get(0);
}
else
{
return new CompositeValidationRule(this);
}
}
public Builder add(final IValidationRule rule)
{
add(rule, false); | return this;
}
public Builder addExploded(final IValidationRule rule)
{
add(rule, true);
return this;
}
private Builder add(final IValidationRule rule, final boolean explodeComposite)
{
// Don't add null rules
if (NullValidationRule.isNull(rule))
{
return this;
}
// Don't add if already exists
if (rules.contains(rule))
{
return this;
}
if (explodeComposite && rule instanceof CompositeValidationRule)
{
final CompositeValidationRule compositeRule = (CompositeValidationRule)rule;
addAll(compositeRule.getValidationRules(), true);
}
else
{
rules.add(rule);
}
return this;
}
private Builder addAll(final Collection<IValidationRule> rules)
{
return addAll(rules, false);
}
private Builder addAll(final Collection<IValidationRule> rules, final boolean explodeComposite)
{
rules.forEach(includedRule -> add(includedRule, explodeComposite));
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\validationRule\impl\CompositeValidationRule.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonProduct
{
@NonNull ProductId id;
@NonNull String name;
@NonNull BigDecimal price;
@NonNull String currencySymbol;
@NonNull UomId uomId;
@NonNull String uomSymbol;
@Nullable UomId catchWeightUomId;
@Nullable String catchWeightUomSymbol;
@Nullable BigDecimal catchWeight;
@NonNull TaxCategoryId taxCategoryId;
public static JsonProduct from(@NonNull final POSProduct product, @NonNull final String adLanguage)
{
return JsonProduct.builder()
.id(product.getId())
.name(product.getName(adLanguage))
.price(product.getPrice().toBigDecimal())
.currencySymbol(product.getCurrencySymbol(adLanguage))
.uomId(product.getUom().getUomId())
.uomSymbol(product.getUom().getUomSymbol()) | .catchWeightUomId(product.getCatchWeightUom() != null ? product.getCatchWeightUom().getUomId() : null)
.catchWeightUomSymbol(product.getCatchWeightUom() != null ? product.getCatchWeightUom().getUomSymbol() : null)
.catchWeight(product.getCatchWeight())
.taxCategoryId(product.getTaxCategoryId())
.build();
}
public static List<JsonProduct> fromList(@NonNull final List<POSProduct> list, @NonNull final String adLanguage)
{
return list.stream()
.map(product -> from(product, adLanguage))
.sorted(Comparator.comparing(JsonProduct::getName))
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.rest-api\src\main\java\de\metas\pos\rest_api\json\JsonProduct.java | 2 |
请完成以下Java代码 | public ResponseEntity<Object> createServerDeploy(@Validated @RequestBody ServerDeploy resources){
serverDeployService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改服务器")
@ApiOperation(value = "修改服务器")
@PutMapping
@PreAuthorize("@el.check('serverDeploy:edit')")
public ResponseEntity<Object> updateServerDeploy(@Validated @RequestBody ServerDeploy resources){
serverDeployService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除服务器") | @ApiOperation(value = "删除Server")
@DeleteMapping
@PreAuthorize("@el.check('serverDeploy:del')")
public ResponseEntity<Object> deleteServerDeploy(@RequestBody Set<Long> ids){
serverDeployService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("测试连接服务器")
@ApiOperation(value = "测试连接服务器")
@PostMapping("/testConnect")
@PreAuthorize("@el.check('serverDeploy:add')")
public ResponseEntity<Object> testConnectServerDeploy(@Validated @RequestBody ServerDeploy resources){
return new ResponseEntity<>(serverDeployService.testConnect(resources),HttpStatus.CREATED);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\rest\ServerDeployController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isEnrichWithDynatraceMetadata() {
return this.enrichWithDynatraceMetadata;
}
public void setEnrichWithDynatraceMetadata(Boolean enrichWithDynatraceMetadata) {
this.enrichWithDynatraceMetadata = enrichWithDynatraceMetadata;
}
public @Nullable String getMetricKeyPrefix() {
return this.metricKeyPrefix;
}
public void setMetricKeyPrefix(@Nullable String metricKeyPrefix) {
this.metricKeyPrefix = metricKeyPrefix;
}
public boolean isUseDynatraceSummaryInstruments() {
return this.useDynatraceSummaryInstruments;
} | public void setUseDynatraceSummaryInstruments(boolean useDynatraceSummaryInstruments) {
this.useDynatraceSummaryInstruments = useDynatraceSummaryInstruments;
}
public boolean isExportMeterMetadata() {
return this.exportMeterMetadata;
}
public void setExportMeterMetadata(boolean exportMeterMetadata) {
this.exportMeterMetadata = exportMeterMetadata;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\dynatrace\DynatraceProperties.java | 2 |
请完成以下Java代码 | public Collection<I_M_ShippingPackage> getBy(final @NonNull ShippingPackageQuery query)
{
return toShippingPackageQueryBuilder(query)
.create()
.list();
}
private IQuery<I_M_Package> toPackageSqlQuery(final @NonNull ShippingPackageQuery query)
{
final IQueryBuilder<I_M_ShippingPackage> builder = toShippingPackageQueryBuilder(query);
return builder.andCollect(I_M_ShippingPackage.COLUMN_M_Package_ID)
.create();
}
private IQueryBuilder<I_M_ShippingPackage> toShippingPackageQueryBuilder(final @NonNull ShippingPackageQuery query)
{
if(query.getOrderIds().isEmpty() && query.getOrderLineIds().isEmpty())
{
return queryBL.createQueryBuilder(I_M_ShippingPackage.class)
.filter(ConstantQueryFilter.of(false));
} | final IQueryBuilder<I_M_ShippingPackage> builder = queryBL.createQueryBuilder(I_M_ShippingPackage.class)
.addOnlyActiveRecordsFilter();
final Collection<OrderId> orderIds = query.getOrderIds();
if (!orderIds.isEmpty())
{
builder.addInArrayFilter(I_M_ShippingPackage.COLUMNNAME_C_Order_ID, orderIds);
}
final Collection<OrderLineId> orderLineIds = query.getOrderLineIds();
if (!orderLineIds.isEmpty())
{
builder.addInArrayFilter(I_M_ShippingPackage.COLUMNNAME_C_OrderLine_ID, orderLineIds);
}
return builder;
}
public void deleteBy(@NonNull final ShippingPackageQuery query)
{
deleteFromShipperTransportation(toPackageSqlQuery(query).listIds(PackageId::ofRepoId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\PurchaseOrderToShipperTransportationRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MD5 {
/**
* 签名字符串
* @param text 需要签名的字符串
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static String sign(String text, String key, String input_charset) {
text = text + key;
return DigestUtils.md5Hex(getContentBytes(text, input_charset));
}
/**
* 签名字符串
* @param text 需要签名的字符串
* @param sign 签名结果
* @param key 密钥
* @param input_charset 编码格式
* @return 签名结果
*/
public static boolean verify(String text, String sign, String key, String input_charset) {
text = text + key;
String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
if(mysign.equals(sign)) {
return true;
}
else { | return false;
}
}
/**
* @param content
* @param charset
* @return
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
private static byte[] getContentBytes(String content, String charset) {
if (charset == null || "".equals(charset)) {
return content.getBytes();
}
try {
return content.getBytes(charset);
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
}
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\alipay\MD5.java | 2 |
请完成以下Java代码 | public static HalCaseDefinition fromCaseDefinition(CaseDefinition caseDefinition, ProcessEngine processEngine) {
HalCaseDefinition halCaseDefinition = new HalCaseDefinition();
halCaseDefinition.id = caseDefinition.getId();
halCaseDefinition.key = caseDefinition.getKey();
halCaseDefinition.category = caseDefinition.getCategory();
halCaseDefinition.name = caseDefinition.getName();
halCaseDefinition.version = caseDefinition.getVersion();
halCaseDefinition.resource = caseDefinition.getResourceName();
halCaseDefinition.deploymentId = caseDefinition.getDeploymentId();
halCaseDefinition.contextPath = ApplicationContextPathUtil.getApplicationPathForDeployment(processEngine, caseDefinition.getDeploymentId());
halCaseDefinition.linker.createLink(REL_SELF, caseDefinition.getId());
halCaseDefinition.linker.createLink(REL_DEPLOYMENT, caseDefinition.getDeploymentId());
halCaseDefinition.linker.createLink(REL_DEPLOYMENT_RESOURCE, caseDefinition.getDeploymentId(), caseDefinition.getResourceName());
return halCaseDefinition;
}
public String getId() {
return id;
}
public String getKey() {
return key;
}
public String getCategory() {
return category;
} | public String getName() {
return name;
}
public int getVersion() {
return version;
}
public String getResource() {
return resource;
}
public String getDeploymentId() {
return deploymentId;
}
public String getContextPath() {
return contextPath;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\caseDefinition\HalCaseDefinition.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private HuId getHuIdToPick(@NonNull final DistributionJobLine line)
{
if (_huIdToPick == null)
{
_huIdToPick = resolveHuIdToPick(line);
}
return _huIdToPick;
}
@NonNull
private HuId resolveHuIdToPick(@NonNull final DistributionJobLine line)
{
final JsonDistributionEvent.PickFrom pickFrom = Check.assumeNotNull(this.pickFrom, "pickFrom must be set");
final ScannedCode pickFromScannedCode = ScannedCode.ofString(Check.assumeNotNull(pickFrom.getQrCode(), "pickFrom.qrCode must be set"));
final HuId sourceHuId = huService.resolveHUId(pickFromScannedCode);
final Quantity sourceHUQty = huService.getProductQuantity(sourceHuId, line.getProductId());
final Quantity qtyToPick = pickFrom.getQtyPicked(line.getUOM()).orElse(null);
if (qtyToPick == null)
{
// no qty to pick specified by user => pick the whole HU
return sourceHuId;
}
else if (qtyToPick.compareTo(sourceHUQty) > 0)
{
throw new AdempiereException(NOT_ENOUGH_QTY, sourceHUQty);
}
else if (qtyToPick.compareTo(sourceHUQty) == 0)
{
// scanned HU has exactly the required qty
return sourceHuId;
}
else
{
return splitQty(line, sourceHuId, qtyToPick); | }
}
@NonNull
private HuId splitQty(
@NonNull final DistributionJobLine line,
@NonNull final HuId pickFromVHUId,
@NonNull final Quantity qty)
{
final PackToHUsProducer.PackToInfo packToInfo = packToHUsProducer.extractPackToInfo(PackToSpec.VIRTUAL, line.getPickFromLocatorId())
.withPackForShipping(false);
final I_M_HU splitHU = packToHUsProducer.packToHU(
PackToHUsProducer.PackToHURequest.builder()
.huContext(HUContextHolder.getCurrent())
.pickFromHUId(pickFromVHUId)
.packToInfo(packToInfo)
.productId(line.getProductId())
.qtyPicked(qty)
.documentRef(line.getDDOrderLineId().toTableRecordReference())
.checkIfAlreadyPacked(true)
.build()).getSingleTopLevelTURecord();
return HuId.ofRepoId(splitHU.getM_HU_ID());
}
private Optional<LocatorId> getInTransitLocatorId()
{
return warehouseService.getTrolleyByUserId(userId).map(LocatorQRCode::getLocatorId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\commands\pick_from\DistributionJobPickFromCommand.java | 2 |
请完成以下Java代码 | public void setGetter(Method getter) {
this.getter = getter;
}
public Method getSetter() {
return setter;
}
public void setSetter(Method setter) {
this.setter = setter;
}
@Override
public String toString() {
return "ManagedAttributeInfo: [" + key + " + getter: " + getter + ", setter: " + setter + "]";
}
}
private static final class ManagedOperationInfo {
private final String description;
private final Method operation;
private ManagedOperationInfo(String description, Method operation) {
this.description = description; | this.operation = operation;
}
public String getDescription() {
return description;
}
public Method getOperation() {
return operation;
}
@Override
public String toString() {
return "ManagedOperationInfo: [" + operation + "]";
}
}
private static final class MBeanAttributesAndOperations {
private Map<String, ManagedAttributeInfo> attributes;
private Set<ManagedOperationInfo> operations;
}
} | repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\MBeanInfoAssembler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ChainRequestGatewayFilterFactory extends AbstractGatewayFilterFactory<ChainRequestGatewayFilterFactory.Config> {
final Logger logger = LoggerFactory.getLogger(ChainRequestGatewayFilterFactory.class);
private final WebClient client;
public ChainRequestGatewayFilterFactory(WebClient client) {
super(Config.class);
this.client = client;
}
@Override
public List<String> shortcutFieldOrder() {
return Arrays.asList("languageServiceEndpoint", "defaultLanguage");
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
return client.get()
.uri(config.getLanguageServiceEndpoint())
.exchange()
.flatMap(response -> {
return (response.statusCode()
.is2xxSuccessful()) ? response.bodyToMono(String.class) : Mono.just(config.getDefaultLanguage());
})
.map(LanguageRange::parse)
.map(range -> {
exchange.getRequest()
.mutate()
.headers(h -> h.setAcceptLanguage(range));
String allOutgoingRequestLanguages = exchange.getRequest()
.getHeaders()
.getAcceptLanguage()
.stream()
.map(r -> r.getRange())
.collect(Collectors.joining(","));
logger.info("Chain Request output - Request contains Accept-Language header: " + allOutgoingRequestLanguages);
return exchange;
}) | .flatMap(chain::filter);
};
}
public static class Config {
private String languageServiceEndpoint;
private String defaultLanguage;
public Config() {
}
public String getLanguageServiceEndpoint() {
return languageServiceEndpoint;
}
public void setLanguageServiceEndpoint(String languageServiceEndpoint) {
this.languageServiceEndpoint = languageServiceEndpoint;
}
public String getDefaultLanguage() {
return defaultLanguage;
}
public void setDefaultLanguage(String defaultLanguage) {
this.defaultLanguage = defaultLanguage;
}
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\java\com\baeldung\springcloudgateway\customfilters\gatewayapp\filters\factories\ChainRequestGatewayFilterFactory.java | 2 |
请完成以下Java代码 | public void updateProcessBusinessKeyInHistory(ExecutionEntity processInstance) {
for (HistoryManager historyManager : historyManagers) {
historyManager.updateProcessBusinessKeyInHistory(processInstance);
}
}
@Override
public void updateProcessBusinessStatusInHistory(ExecutionEntity processInstance) {
for (HistoryManager historyManager : historyManagers) {
historyManager.updateProcessBusinessStatusInHistory(processInstance);
}
}
@Override
public void updateProcessDefinitionIdInHistory(ProcessDefinitionEntity processDefinitionEntity, ExecutionEntity processInstance) {
for (HistoryManager historyManager : historyManagers) {
historyManager.updateProcessDefinitionIdInHistory(processDefinitionEntity, processInstance);
}
}
@Override
public void updateActivity(ExecutionEntity executionEntity, String oldActivityId, FlowElement newFlowElement, TaskEntity task, Date updateTime) {
for (HistoryManager historyManager : historyManagers) {
historyManager.updateActivity(executionEntity, oldActivityId, newFlowElement, task, updateTime);
}
}
@Override
public void updateHistoricActivityInstance(ActivityInstance activityInstance) {
for (HistoryManager historyManager : historyManagers) {
historyManager.updateHistoricActivityInstance(activityInstance);
} | }
@Override
public void createHistoricActivityInstance(ActivityInstance activityInstance) {
for (HistoryManager historyManager : historyManagers) {
historyManager.createHistoricActivityInstance(activityInstance);
}
}
@Override
public void recordHistoricUserTaskLogEntry(HistoricTaskLogEntryBuilder taskLogEntryBuilder) {
for (HistoryManager historyManager : historyManagers) {
historyManager.recordHistoricUserTaskLogEntry(taskLogEntryBuilder);
}
}
@Override
public void deleteHistoryUserTaskLog(long logNumber) {
for (HistoryManager historyManager : historyManagers) {
historyManager.deleteHistoryUserTaskLog(logNumber);
}
}
public void addHistoryManager(HistoryManager historyManager) {
historyManagers.add(historyManager);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\history\CompositeHistoryManager.java | 1 |
请完成以下Java代码 | public void setUomCode(final @NonNull String uomCode)
{
this.uomCode = uomCode;
this.uomCodeSet = true;
}
public void setEan(final String ean)
{
this.ean = ean;
this.eanSet = true;
}
public void setGtin(final String gtin)
{
this.gtin = gtin;
this.gtinSet = true;
}
public void setDescription(final String description)
{
this.description = description;
this.descriptionSet = true;
}
public void setDiscontinued(final Boolean discontinued)
{
this.discontinued = discontinued;
this.discontinuedSet = true;
}
public void setDiscontinuedFrom(final LocalDate discontinuedFrom)
{
this.discontinuedFrom = discontinuedFrom;
this.discontinuedFromSet = true;
}
public void setActive(final Boolean active)
{
this.active = active;
this.activeSet = true;
}
public void setStocked(final Boolean stocked)
{
this.stocked = stocked;
this.stockedSet = true; | }
public void setProductCategoryIdentifier(final String productCategoryIdentifier)
{
this.productCategoryIdentifier = productCategoryIdentifier;
this.productCategoryIdentifierSet = true;
}
public void setSyncAdvise(final SyncAdvise syncAdvise)
{
this.syncAdvise = syncAdvise;
}
public void setBpartnerProductItems(final List<JsonRequestBPartnerProductUpsert> bpartnerProductItems)
{
this.bpartnerProductItems = bpartnerProductItems;
}
public void setProductTaxCategories(final List<JsonRequestProductTaxCategoryUpsert> productTaxCategories)
{
this.productTaxCategories = productTaxCategories;
}
public void setUomConversions(final List<JsonRequestUOMConversionUpsert> uomConversions)
{
this.uomConversions = uomConversions;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-product\src\main\java\de\metas\common\product\v2\request\JsonRequestProduct.java | 1 |
请完成以下Java代码 | public final class ALoginRes_pt extends ListResourceBundle
{
/** Translation Content */
//Characters encoded to UTF8 Hex, so no more problems with svn commits
//Fernando Lucktemberg - CenturuyOn Consultoria
static final Object[][] contents = new String[][]
{
{ "Connection", "Conex\u00e3o" },
{ "Defaults", "Padr\u00f5es" },
{ "Login", "ADempiere Login" },
{ "File", "Arquivo" },
{ "Exit", "Sair" },
{ "Help", "Ajuda" },
{ "About", "Sobre" },
{ "Host", "Servidor" },
{ "Database", "Banco de Dados" },
{ "User", "Usu\u00e1rio" },
{ "EnterUser", "Entre com o Usu\u00e1rio da Aplica\u00e7\u00e3o" },
{ "Password", "Senha" },
{ "EnterPassword", "Entre com a senha da Aplica\u00e7\u00e3o" },
{ "Language", "Idioma" },
{ "SelectLanguage", "Selecione o idioma" },
{ "Role", "Regra" },
{ "Client", "Cliente" },
{ "Organization", "Organiza\u00e7\u00e3o" },
{ "Date", "Data" },
{ "Warehouse", "Dep\u00f3sito" },
{ "Printer", "Impressora" },
{ "Connected", "Conectado" },
{ "NotConnected", "N\u00e3o conectado" },
{ "DatabaseNotFound", "Banco de Dados n\u00e3o encontrado" },
{ "UserPwdError", "Usu\u00e1rio/Senha inv\u00e1lidos" },
{ "RoleNotFound", "Regra n\u00e3o encontrada/incorreta" },
{ "Authorized", "Autorizado" }, | { "Ok", "Ok" },
{ "Cancel", "Cancelar" },
{ "VersionConflict", "Conflito de Vers\u00f5es:" },
{ "VersionInfo", "Servidor <> Cliente" },
{ "PleaseUpgrade", "Favor executar o programa de atualiza��o" }
};
/**
* Get Contents
* @return context
*/
public Object[][] getContents()
{
return contents;
} // getContents
} // ALoginRes_pt | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\apps\ALoginRes_pt.java | 1 |
请完成以下Java代码 | public class ResourceRef implements Serializable {
private static final long serialVersionUID = 1L;
private String id;
private String name;
private EventResourceEntity entity;
protected boolean deleted;
public ResourceRef() {
}
// Only intended to be used by ByteArrayRefTypeHandler
public ResourceRef(String id) {
this.id = id;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public byte[] getBytes() {
ensureInitialized();
return (entity != null ? entity.getBytes() : null);
}
public void setValue(String name, byte[] bytes) {
this.name = name;
setBytes(bytes);
}
private void setBytes(byte[] bytes) {
EventResourceEntityManager resourceEntityManager = CommandContextUtil.getResourceEntityManager();
if (id == null) {
if (bytes != null) {
entity = resourceEntityManager.create();
entity.setName(name);
entity.setBytes(bytes);
resourceEntityManager.insert(entity);
id = entity.getId();
}
} else {
ensureInitialized();
entity.setBytes(bytes);
resourceEntityManager.update(entity);
}
} | public EventResourceEntity getEntity() {
ensureInitialized();
return entity;
}
public void delete() {
if (!deleted && id != null) {
if (entity != null) {
// if the entity has been loaded already,
// we might as well use the safer optimistic locking delete.
CommandContextUtil.getResourceEntityManager().delete(entity);
} else {
CommandContextUtil.getResourceEntityManager().delete(id);
}
entity = null;
id = null;
deleted = true;
}
}
private void ensureInitialized() {
if (id != null && entity == null) {
entity = CommandContextUtil.getResourceEntityManager().findById(id);
name = entity.getName();
}
}
public boolean isDeleted() {
return deleted;
}
@Override
public String toString() {
return "ResourceRef[id=" + id + ", name=" + name + ", entity=" + entity + (deleted ? ", deleted]" : "]");
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\ResourceRef.java | 1 |
请完成以下Java代码 | public int getC_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID);
}
@Override
public void setCostAmount (final BigDecimal CostAmount)
{
set_Value (COLUMNNAME_CostAmount, CostAmount);
}
@Override
public BigDecimal getCostAmount()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CostAmount);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setCostAmountReceived (final BigDecimal CostAmountReceived)
{
set_Value (COLUMNNAME_CostAmountReceived, CostAmountReceived);
}
@Override
public BigDecimal getCostAmountReceived()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CostAmountReceived);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setC_UOM_ID (final int C_UOM_ID)
{
if (C_UOM_ID < 1)
set_Value (COLUMNNAME_C_UOM_ID, null);
else
set_Value (COLUMNNAME_C_UOM_ID, C_UOM_ID);
}
@Override
public int getC_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_C_UOM_ID);
}
@Override
public void setLineNetAmt (final BigDecimal LineNetAmt)
{
set_Value (COLUMNNAME_LineNetAmt, LineNetAmt);
}
@Override
public BigDecimal getLineNetAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_LineNetAmt);
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 setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyReceived (final BigDecimal QtyReceived)
{
set_Value (COLUMNNAME_QtyReceived, QtyReceived);
}
@Override
public BigDecimal getQtyReceived()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyReceived);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost_Detail.java | 1 |
请完成以下Java代码 | private DocTypeId getInventoryDocTypeId(@NonNull final I_M_Warehouse warehouse)
{
if (request.getInternalUseInventoryDocTypeId() != null)
{
return request.getInternalUseInventoryDocTypeId();
}
return docTypeDAO.getDocTypeId(
DocTypeQuery.builder()
.docBaseType(DocBaseType.MaterialPhysicalInventory)
.docSubType(DocSubType.InternalUseInventory)
.adClientId(warehouse.getAD_Client_ID())
.adOrgId(warehouse.getAD_Org_ID())
.build());
} | private List<I_M_HU> getTopLevelHUs()
{
final List<I_M_HU> hus = request.getHus();
if (hus.isEmpty())
{
throw new AdempiereException("No HUs for internal use inventory");
}
return handlingUnitsBL.getTopLevelHUs(TopLevelHusQuery.builder()
.hus(hus)
.includeAll(false)
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\internaluse\HUInternalUseInventoryProducer.java | 1 |
请完成以下Java代码 | public String getTraceId()
{
final DemandDetail demandDetail = getDemandDetail();
return demandDetail != null ? demandDetail.getTraceId() : null;
}
/**
* This is enabled by the current usage of {@link #parentId}
*/
public boolean isStockCandidateOfThisCandidate(@NonNull final Candidate potentialStockCandidate)
{
if (potentialStockCandidate.type != CandidateType.STOCK)
{
return false;
}
switch (type)
{
case DEMAND:
return potentialStockCandidate.getParentId().equals(id);
case SUPPLY:
return potentialStockCandidate.getId().equals(parentId);
default:
return false;
} | }
/**
* The qty is always stored as an absolute value on the candidate, but we're interested if the candidate is adding or subtracting qty to the stock.
*/
public BigDecimal getStockImpactPlannedQuantity()
{
switch (getType())
{
case DEMAND:
case UNEXPECTED_DECREASE:
case INVENTORY_DOWN:
return getQuantity().negate();
default:
return getQuantity();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\Candidate.java | 1 |
请完成以下Java代码 | public PageData<Job> findJobsByFilter(TenantId tenantId, JobFilter filter, PageLink pageLink) {
PageData<Job> jobs = jobDao.findByTenantIdAndFilter(tenantId, filter, pageLink);
Set<EntityId> entityIds = jobs.getData().stream()
.map(Job::getEntityId)
.collect(Collectors.toSet());
Map<EntityId, EntityInfo> entityInfos = entityService.fetchEntityInfos(tenantId, null, entityIds);
jobs.getData().forEach(job -> {
EntityInfo entityInfo = entityInfos.get(job.getEntityId());
if (entityInfo != null) {
job.setEntityName(entityInfo.getName());
}
});
return jobs;
}
@Override
public Job findLatestJobByKey(TenantId tenantId, String key) {
return jobDao.findLatestByTenantIdAndKey(tenantId, key);
}
@Override
public void deleteJob(TenantId tenantId, JobId jobId) {
Job job = findJobById(tenantId, jobId);
if (!job.getStatus().isOneOf(CANCELLED, COMPLETED, FAILED)) {
throw new IllegalArgumentException("Job must be cancelled, completed or failed");
}
jobDao.removeById(tenantId, jobId.getId());
}
@Override
public int deleteJobsByEntityId(TenantId tenantId, EntityId entityId) { // TODO: cancel all jobs for this entity
return jobDao.removeByEntityId(tenantId, entityId);
}
private Job findForUpdate(TenantId tenantId, JobId jobId) {
return jobDao.findByIdForUpdate(tenantId, jobId);
} | @Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findJobById(tenantId, (JobId) entityId));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(jobDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
jobDao.removeById(tenantId, id.getId());
}
@Override
public void deleteByTenantId(TenantId tenantId) {
jobDao.removeByTenantId(tenantId);
}
@Override
public EntityType getEntityType() {
return EntityType.JOB;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\job\DefaultJobService.java | 1 |
请完成以下Java代码 | public boolean isMatchAfter() {
return this.matchAfter;
}
@Override
protected String getDescription() {
Filter filter = getFilter();
Assert.notNull(filter, "'filter' must not be null");
return "filter " + getOrDeduceName(filter);
}
@Override
protected Dynamic addRegistration(String description, ServletContext servletContext) {
Filter filter = getFilter();
return servletContext.addFilter(getOrDeduceName(filter), filter);
}
/**
* Configure registration settings. Subclasses can override this method to perform
* additional configuration if required.
* @param registration the registration
*/
@Override
protected void configure(FilterRegistration.Dynamic registration) {
super.configure(registration);
EnumSet<DispatcherType> dispatcherTypes = determineDispatcherTypes();
Set<String> servletNames = new LinkedHashSet<>();
for (ServletRegistrationBean<?> servletRegistrationBean : this.servletRegistrationBeans) {
servletNames.add(servletRegistrationBean.getServletName());
}
servletNames.addAll(this.servletNames);
if (servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter, DEFAULT_URL_MAPPINGS);
}
else {
if (!servletNames.isEmpty()) {
registration.addMappingForServletNames(dispatcherTypes, this.matchAfter,
StringUtils.toStringArray(servletNames));
}
if (!this.urlPatterns.isEmpty()) {
registration.addMappingForUrlPatterns(dispatcherTypes, this.matchAfter,
StringUtils.toStringArray(this.urlPatterns));
}
}
}
/**
* Return the {@link Filter} to be registered.
* @return the filter
*/
public abstract @Nullable T getFilter();
/**
* Returns the filter name that will be registered. | * @return the filter name
* @since 3.2.0
*/
public String getFilterName() {
return getOrDeduceName(getFilter());
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(getOrDeduceName(this));
if (this.servletNames.isEmpty() && this.urlPatterns.isEmpty()) {
builder.append(" urls=").append(Arrays.toString(DEFAULT_URL_MAPPINGS));
}
else {
if (!this.servletNames.isEmpty()) {
builder.append(" servlets=").append(this.servletNames);
}
if (!this.urlPatterns.isEmpty()) {
builder.append(" urls=").append(this.urlPatterns);
}
}
builder.append(" order=").append(getOrder());
return builder.toString();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\AbstractFilterRegistrationBean.java | 1 |
请完成以下Java代码 | void failed(@Nullable ConfigurableApplicationContext context, Throwable exception) {
doWithListeners("spring.boot.application.failed",
(listener) -> callFailedListener(listener, context, exception), (step) -> {
step.tag("exception", exception.getClass().toString());
String message = exception.getMessage();
if (message != null) {
step.tag("message", message);
}
});
}
private void callFailedListener(SpringApplicationRunListener listener,
@Nullable ConfigurableApplicationContext context, Throwable exception) {
try {
listener.failed(context, exception);
}
catch (Throwable ex) {
if (exception == null) {
ReflectionUtils.rethrowRuntimeException(ex);
}
if (this.log.isDebugEnabled()) {
this.log.error("Error handling failed", ex);
}
else {
String message = ex.getMessage(); | message = (message != null) ? message : "no error message";
this.log.warn("Error handling failed (" + message + ")");
}
}
}
private void doWithListeners(String stepName, Consumer<SpringApplicationRunListener> listenerAction) {
doWithListeners(stepName, listenerAction, null);
}
private void doWithListeners(String stepName, Consumer<SpringApplicationRunListener> listenerAction,
@Nullable Consumer<StartupStep> stepAction) {
StartupStep step = this.applicationStartup.start(stepName);
this.listeners.forEach(listenerAction);
if (stepAction != null) {
stepAction.accept(step);
}
step.end();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\SpringApplicationRunListeners.java | 1 |
请完成以下Java代码 | protected VariableMap collectLastVariables(CommandContext commandContext,
HistoricProcessInstance processInstance) {
HistoryService historyService = commandContext.getProcessEngineConfiguration()
.getHistoryService();
List<HistoricVariableInstance> historicVariables =
historyService.createHistoricVariableInstanceQuery()
.executionIdIn(processInstance.getId())
.list();
VariableMap variables = new VariableMapImpl();
for (HistoricVariableInstance variable : historicVariables) {
variables.putValueTyped(variable.getName(), variable.getTypedValue());
}
return variables;
}
protected HistoricActivityInstance resolveStartActivityInstance(
HistoricProcessInstance processInstance) {
HistoryService historyService = Context.getProcessEngineConfiguration().getHistoryService();
String processInstanceId = processInstance.getId();
String startActivityId = processInstance.getStartActivityId(); | ensureNotNull("startActivityId", startActivityId);
List<HistoricActivityInstance> historicActivityInstances = historyService
.createHistoricActivityInstanceQuery()
.processInstanceId(processInstanceId)
.activityId(startActivityId)
.orderPartiallyByOccurrence()
.asc()
.list();
ensureNotEmpty("historicActivityInstances", historicActivityInstances);
HistoricActivityInstance startActivityInstance = historicActivityInstances.get(0);
return startActivityInstance;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\RestartProcessInstancesCmd.java | 1 |
请完成以下Java代码 | public static class OpenSingleDocument implements ResultAction
{
@NonNull
DocumentPath documentPath;
@Builder.Default
ProcessExecutionResult.RecordsToOpen.TargetTab targetTab = ProcessExecutionResult.RecordsToOpen.TargetTab.NEW_TAB;
}
@lombok.Value
@lombok.Builder
public static class SelectViewRowsAction implements ResultAction
{
@NonNull ViewId viewId;
@NonNull DocumentIdsSelection rowIds;
} | @lombok.Value
@lombok.Builder
public static class DisplayQRCodeAction implements ResultAction
{
@NonNull String code;
}
@lombok.Value
@lombok.Builder
public static class NewRecordAction implements ResultAction
{
@NonNull String windowId;
@NonNull @Singular Map<String, String> fieldValues;
@NonNull @Builder.Default ProcessExecutionResult.WebuiNewRecord.TargetTab targetTab = ProcessExecutionResult.WebuiNewRecord.TargetTab.SAME_TAB;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\ProcessInstanceResult.java | 1 |
请完成以下Java代码 | public class TbMsgCountNode implements TbNode {
private AtomicLong messagesProcessed = new AtomicLong(0);
private final Gson gson = new Gson();
private UUID nextTickId;
private long delay;
private String telemetryPrefix;
private long lastScheduledTs;
@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
TbMsgCountNodeConfiguration config = TbNodeUtils.convert(configuration, TbMsgCountNodeConfiguration.class);
this.delay = TimeUnit.SECONDS.toMillis(config.getInterval());
this.telemetryPrefix = config.getTelemetryPrefix();
scheduleTickMsg(ctx, null);
}
@Override
public void onMsg(TbContext ctx, TbMsg msg) {
if (msg.isTypeOf(TbMsgType.MSG_COUNT_SELF_MSG) && msg.getId().equals(nextTickId)) {
JsonObject telemetryJson = new JsonObject();
telemetryJson.addProperty(this.telemetryPrefix + "_" + ctx.getServiceId(), messagesProcessed.longValue());
messagesProcessed = new AtomicLong(0);
TbMsgMetaData metaData = new TbMsgMetaData();
metaData.putValue("delta", Long.toString(System.currentTimeMillis() - lastScheduledTs + delay));
TbMsg tbMsg = TbMsg.newMsg()
.queueName(msg.getQueueName())
.type(TbMsgType.POST_TELEMETRY_REQUEST)
.originator(ctx.getTenantId())
.customerId(msg.getCustomerId())
.copyMetaData(metaData)
.data(gson.toJson(telemetryJson))
.build();
ctx.enqueueForTellNext(tbMsg, TbNodeConnectionType.SUCCESS);
scheduleTickMsg(ctx, tbMsg); | } else {
messagesProcessed.incrementAndGet();
ctx.ack(msg);
}
}
private void scheduleTickMsg(TbContext ctx, TbMsg msg) {
long curTs = System.currentTimeMillis();
if (lastScheduledTs == 0L) {
lastScheduledTs = curTs;
}
lastScheduledTs = lastScheduledTs + delay;
long curDelay = Math.max(0L, (lastScheduledTs - curTs));
TbMsg tickMsg = ctx.newMsg(null, TbMsgType.MSG_COUNT_SELF_MSG, ctx.getSelfId(), msg != null ? msg.getCustomerId() : null, TbMsgMetaData.EMPTY, TbMsg.EMPTY_STRING);
nextTickId = tickMsg.getId();
ctx.tellSelf(tickMsg, curDelay);
}
} | repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\action\TbMsgCountNode.java | 1 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=password
spring.jpa.database-p | latform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update | repos\tutorials-master\persistence-modules\spring-data-jpa-query-5\src\main\resources\application-h2.properties | 2 |
请完成以下Java代码 | private boolean isDeleteEmptyAndJustCreatedAggregatedTUs()
{
if (deleteEmptyAndJustCreatedAggregatedTUs != null)
{
return deleteEmptyAndJustCreatedAggregatedTUs;
}
else if (baseAllocationRequest != null)
{
return baseAllocationRequest.isDeleteEmptyAndJustCreatedAggregatedTUs();
}
return false;
}
@Override
public IAllocationRequest create()
{
final IHUContext huContext = getHUContextToUse(); | final ProductId productId = getProductIdToUse();
final Quantity quantity = getQuantityToUse();
final ZonedDateTime date = getDateToUse();
final TableRecordReference fromTableRecord = getFromReferencedTableRecordToUse();
final boolean forceQtyAllocation = isForceQtyAllocationToUse();
final ClearanceStatusInfo clearanceStatusInfo = getClearanceStatusInfo();
return new AllocationRequest(
huContext,
productId,
quantity,
date,
fromTableRecord,
forceQtyAllocation,
clearanceStatusInfo,
isDeleteEmptyAndJustCreatedAggregatedTUs());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationRequestBuilder.java | 1 |
请完成以下Java代码 | default CompletableFuture<Output> execute(DelegateExecution execution, AsyncTaskInvoker taskInvoker) {
Input inputData = prepareExecutionData(execution);
return taskInvoker.submit(() -> execute(inputData));
}
/**
* Method invoked before doing the execution to extract needed that from the execution
* on the main thread.
* This should be used to prepare and extract data from the execution before doing the execution in a different thread.
*
* @param execution the execution from which to extract data
* @return the data for the delegate
*/
Input prepareExecutionData(DelegateExecution execution);
/**
* Perform the actual execution of the delegate in another thread.
* This uses {@link #prepareExecutionData(DelegateExecution)} to get the needed data
* from the {@link DelegateExecution} and returns the output data that can is passed to {@link #afterExecution(DelegateExecution, Object)}.
*
* <b>IMPORTANT:</b> This is a completely new thread which does not participate in the transaction of the process.
*
* @param inputData the input data for the execution created via {@link #prepareExecutionData(DelegateExecution)}
* @return the output data of the execution
* @see #execute(DelegateExecution, AsyncTaskInvoker) | */
Output execute(Input inputData);
/**
* Method invoked with the result from {@link #execute(Object)}.
* This should be used to set data on the {@link DelegateExecution}.
* This is on the same thread as {@link #prepareExecutionData(DelegateExecution)} and participates in the process transaction.
*
* @param execution the execution to which data can be set
* @param executionData the execution data
*/
@Override
void afterExecution(DelegateExecution execution, Output executionData);
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\delegate\FlowableFutureJavaDelegate.java | 1 |
请完成以下Java代码 | public class KotlinJpaMavenBuildCustomizer implements BuildCustomizer<MavenBuild> {
private final BuildMetadataResolver buildMetadataResolver;
public KotlinJpaMavenBuildCustomizer(InitializrMetadata metadata, ProjectDescription projectDescription) {
this.buildMetadataResolver = new BuildMetadataResolver(metadata, projectDescription.getPlatformVersion());
}
@Override
public void customize(MavenBuild build) {
if (this.buildMetadataResolver.hasFacet(build, "jpa")) {
build.plugins().add("org.jetbrains.kotlin", "kotlin-maven-plugin", (kotlinPlugin) -> {
kotlinPlugin.configuration((configuration) -> {
configuration.configure("compilerPlugins", (compilerPlugins) -> {
compilerPlugins.add("plugin", "jpa"); | compilerPlugins.add("plugin", "all-open");
});
configuration.configure("pluginOptions", (option) -> {
option.add("option", "all-open:annotation=jakarta.persistence.Entity");
option.add("option", "all-open:annotation=jakarta.persistence.MappedSuperclass");
option.add("option", "all-open:annotation=jakarta.persistence.Embeddable");
});
});
kotlinPlugin.dependency("org.jetbrains.kotlin", "kotlin-maven-noarg",
VersionReference.ofProperty(KotlinMavenBuildCustomizer.KOTLIN_VERSION_PROPERTY));
});
}
}
} | repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\code\kotlin\KotlinJpaMavenBuildCustomizer.java | 1 |
请完成以下Java代码 | public final class JavaFieldDeclaration implements Annotatable {
private final AnnotationContainer annotations = new AnnotationContainer();
private final int modifiers;
private final String name;
private final String returnType;
private final Object value;
private final boolean initialized;
private JavaFieldDeclaration(Builder builder) {
this.modifiers = builder.modifiers;
this.name = builder.name;
this.returnType = builder.returnType;
this.value = builder.value;
this.initialized = builder.initialized;
}
/**
* Creates a new builder for the field with the given name.
* @param name the field name
* @return the builder
*/
public static Builder field(String name) {
return new Builder(name);
}
@Override
public AnnotationContainer annotations() {
return this.annotations;
}
/**
* Return the modifiers.
* @return the modifiers
*/
public int getModifiers() {
return this.modifiers;
}
/**
* Return the name.
* @return the name
*/
public String getName() {
return this.name;
}
/**
* Return the return type.
* @return the return type
*/
public String getReturnType() {
return this.returnType;
}
/**
* Return the value.
* @return the value
*/
public Object getValue() {
return this.value;
}
/**
* Return whether this field is initialized.
* @return whether the field is initialized.
*/
public boolean isInitialized() {
return this.initialized;
}
/** | * Builder for creating a {@link JavaFieldDeclaration}.
*/
public static final class Builder {
private final String name;
private String returnType;
private int modifiers;
private Object value;
private boolean initialized;
private Builder(String name) {
this.name = name;
}
/**
* Sets the modifiers.
* @param modifiers the modifiers
* @return this for method chaining
*/
public Builder modifiers(int modifiers) {
this.modifiers = modifiers;
return this;
}
/**
* Sets the value.
* @param value the value
* @return this for method chaining
*/
public Builder value(Object value) {
this.value = value;
this.initialized = true;
return this;
}
/**
* Sets the return type.
* @param returnType the return type
* @return this for method chaining
*/
public JavaFieldDeclaration returning(String returnType) {
this.returnType = returnType;
return new JavaFieldDeclaration(this);
}
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\java\JavaFieldDeclaration.java | 1 |
请完成以下Java代码 | public BigDecimal getQty()
{
// TODO: why not using getQtyEnteredTU?
// yes, why not indeed?
final BigDecimal qtyItemCapacity = orderLine.getQtyItemCapacity();
if (qtyItemCapacity.signum() == 0)
{
return BigDecimal.ZERO;
}
final BigDecimal qtyOrdered = orderLine.getQtyOrdered();
return qtyOrdered.divide(qtyItemCapacity, 0, RoundingMode.UP);
}
@Override
public @Nullable ProductId getLUProductId()
{
final HuPackingInstructionsId luPIId = HuPackingInstructionsId.ofRepoIdOrNull(orderLine.getM_LU_HU_PI_ID());
if (luPIId == null)
{ | return null;
}
return packingMaterialDAO.getLUPIItemForHUPI(BPartnerId.ofRepoId(orderLine.getC_BPartner_ID()), luPIId)
.map(HuPackingMaterial::getProductId)
.orElse(null);
}
@Override
public BigDecimal getQtyLU()
{
return orderLine.getQtyLU();
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\order\api\impl\OrderLinePackingMaterialDocumentLineSource.java | 1 |
请完成以下Java代码 | public ChangeActivityStateBuilder localVariables(String startActivityId, Map<String, Object> localVariables) {
if (this.localVariables == null) {
this.localVariables = new HashMap<>();
}
this.localVariables.put(startActivityId, localVariables);
return this;
}
@Override
public void changeState() {
if (runtimeService == null) {
throw new FlowableException("RuntimeService cannot be null, Obtain your builder instance from the RuntimeService to access this feature");
}
runtimeService.changeActivityState(this);
}
public String getProcessInstanceId() {
return processInstanceId;
}
public List<MoveExecutionIdContainer> getMoveExecutionIdList() {
return moveExecutionIdList;
} | public List<MoveActivityIdContainer> getMoveActivityIdList() {
return moveActivityIdList;
}
public List<EnableActivityIdContainer> getEnableActivityIdList() {
return enableActivityIdList;
}
public Map<String, Object> getProcessInstanceVariables() {
return processVariables;
}
public Map<String, Map<String, Object>> getLocalVariables() {
return localVariables;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\runtime\ChangeActivityStateBuilderImpl.java | 1 |
请完成以下Java代码 | private List<String> getRoleNames(Resource webXml, NodeList securityRoles) {
ArrayList<String> roleNames = new ArrayList<>();
for (int i = 0; i < securityRoles.getLength(); i++) {
Element securityRoleElement = (Element) securityRoles.item(i);
NodeList roles = securityRoleElement.getElementsByTagName("role-name");
if (roles.getLength() > 0) {
String roleName = roles.item(0).getTextContent().trim();
roleNames.add(roleName);
this.logger.info("Retrieved role-name '" + roleName + "' from web.xml");
}
else {
this.logger.info("No security-role elements found in " + webXml);
}
}
return roleNames;
}
/**
* @return Document for the specified InputStream
*/
private Document getDocument(InputStream aStream) {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setValidating(false);
DocumentBuilder builder = factory.newDocumentBuilder();
builder.setEntityResolver(new MyEntityResolver());
return builder.parse(aStream);
}
catch (FactoryConfigurationError | IOException | SAXException | ParserConfigurationException ex) {
throw new RuntimeException("Unable to parse document object", ex);
}
finally {
try { | aStream.close();
}
catch (IOException ex) {
this.logger.warn("Failed to close input stream for web.xml", ex);
}
}
}
/**
* We do not need to resolve external entities, so just return an empty String.
*/
private static final class MyEntityResolver implements EntityResolver {
@Override
public InputSource resolveEntity(String publicId, String systemId) {
return new InputSource(new StringReader(""));
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\j2ee\WebXmlMappableAttributesRetriever.java | 1 |
请完成以下Java代码 | private void setQtyConv(final BigDecimal qtyConv)
{
fieldQtyConv.setValue(qtyConv, true);
}
private void setDescription(final String description)
{
fieldDescription.setValue(description, true);
}
private <T> T toModel(final Class<T> modelClass, final Object idObj)
{
final int id = toID(idObj);
if (id <= 0)
{
return null;
}
return InterfaceWrapperHelper.create(getCtx(), id, modelClass, ITrx.TRXNAME_None);
}
private static final int toID(final Object idObj)
{
if (idObj == null)
{
return -1;
}
else if (idObj instanceof Number)
{
return ((Number)idObj).intValue();
}
else
{
return -1;
}
}
private void doConvert(final String reason)
{
// Reset
setDescription(null);
setQtyConv(null); | final I_C_UOM uomFrom = getC_UOM();
final I_C_UOM uomTo = getC_UOM_To();
if (uomFrom == null || uomTo == null)
{
return;
}
final I_M_Product product = getM_Product();
final BigDecimal qty = getQty();
try
{
final BigDecimal qtyConv;
if (product != null)
{
final UOMConversionContext conversionCtx = UOMConversionContext.of(product);
qtyConv = uomConversionBL.convertQty(conversionCtx, qty, uomFrom, uomTo);
}
else
{
qtyConv = uomConversionBL.convert(uomFrom, uomTo, qty).orElse(null);
}
setQtyConv(qtyConv);
setDescription("Converted "
+ NumberUtils.stripTrailingDecimalZeros(qty) + " " + uomFrom.getUOMSymbol()
+ " to "
+ NumberUtils.stripTrailingDecimalZeros(qtyConv) + " " + uomTo.getUOMSymbol()
+ "<br>Product: " + (product == null ? "-" : product.getName())
+ "<br>Reason: " + reason);
}
catch (final Exception e)
{
setDescription(e.getLocalizedMessage());
// because this is a test form, printing the exception directly to console it's totally fine.
// More, if we would log it as WARNING/SEVERE, an AD_Issue would be created, but we don't want that.
e.printStackTrace();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\uom\form\UOMConversionCheckFormPanel.java | 1 |
请完成以下Java代码 | public boolean isObligation() {
if (obligation == null) {
return true;
} else {
return obligation;
}
}
/**
* Sets the value of the obligation property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setObligation(Boolean value) {
this.obligation = value;
}
/**
* Gets the value of the sectionCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSectionCode() {
return sectionCode;
}
/**
* Sets the value of the sectionCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSectionCode(String value) {
this.sectionCode = value;
}
/**
* Gets the value of the remark property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRemark() {
return remark;
}
/**
* Sets the value of the remark property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRemark(String value) {
this.remark = value;
} | /**
* Gets the value of the serviceAttributes property.
*
* @return
* possible object is
* {@link Long }
*
*/
public long getServiceAttributes() {
if (serviceAttributes == null) {
return 0L;
} else {
return serviceAttributes;
}
}
/**
* Sets the value of the serviceAttributes property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setServiceAttributes(Long value) {
this.serviceAttributes = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RecordServiceType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigInteger getTimeForPayment() {
return timeForPayment;
}
/**
* Sets the value of the timeForPayment property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setTimeForPayment(BigInteger value) {
this.timeForPayment = value;
}
/**
* Consignment reference.
*
* @return
* possible object is
* {@link String }
*
*/ | public String getConsignmentReference() {
return consignmentReference;
}
/**
* Sets the value of the consignmentReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setConsignmentReference(String value) {
this.consignmentReference = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\RECADVExtensionType.java | 2 |
请完成以下Java代码 | public String getEmployeeId() {
return employeeId;
}
public void setEmployeeId(String employeeId) {
this.employeeId = employeeId;
}
public String getCompanyId() {
return companyId;
}
public void setCompanyId(String companyId) {
this.companyId = companyId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((companyId == null) ? 0 : companyId.hashCode());
result = prime * result + ((employeeId == null) ? 0 : employeeId.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;
EmployeeIdentity other = (EmployeeIdentity) obj;
if (companyId == null) {
if (other.companyId != null)
return false;
} else if (!companyId.equals(other.companyId))
return false;
if (employeeId == null) {
if (other.employeeId != null)
return false;
} else if (!employeeId.equals(other.employeeId))
return false;
return true;
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-hibernate-composite-key-demo\src\main\java\net\alanbinu\springboot\entity\EmployeeIdentity.java | 1 |
请完成以下Java代码 | public VariableInstanceResource getVariableInstance(String id) {
return new VariableInstanceResourceImpl(id, getProcessEngine());
}
@Override
public List<VariableInstanceDto> getVariableInstances(UriInfo uriInfo, Integer firstResult, Integer maxResults, boolean deserializeObjectValues) {
VariableInstanceQueryDto queryDto = new VariableInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryVariableInstances(queryDto, firstResult, maxResults, deserializeObjectValues);
}
@Override
public List<VariableInstanceDto> queryVariableInstances(VariableInstanceQueryDto queryDto, Integer firstResult, Integer maxResults, boolean deserializeObjectValues) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
VariableInstanceQuery query = queryDto.toQuery(engine);
// disable binary fetching by default.
query.disableBinaryFetching();
// disable custom object fetching by default. Cannot be done to not break existing API
if (!deserializeObjectValues) {
query.disableCustomObjectDeserialization();
}
List<VariableInstance> matchingInstances = QueryUtil.list(query, firstResult, maxResults);
List<VariableInstanceDto> instanceResults = new ArrayList<>();
for (VariableInstance instance : matchingInstances) { | VariableInstanceDto resultInstance = VariableInstanceDto.fromVariableInstance(instance);
instanceResults.add(resultInstance);
}
return instanceResults;
}
@Override
public CountResultDto getVariableInstancesCount(UriInfo uriInfo) {
VariableInstanceQueryDto queryDto = new VariableInstanceQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryVariableInstancesCount(queryDto);
}
@Override
public CountResultDto queryVariableInstancesCount(VariableInstanceQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
VariableInstanceQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\VariableInstanceRestServiceImpl.java | 1 |
请完成以下Java代码 | public void actionPerformed (final ActionEvent e)
{
if(m_editor == null)
{
return;
}
if (e.getSource() != m_editor)
{
return;
}
if(log.isTraceEnabled())
log.trace(m_mField.getColumnName() + ": Value=" + m_editor.getValue());
//
// When user presses enter, automatically stop editing (for some basic text fields)
final int displayType = m_mField.getDisplayType();
if (DisplayType.isText(displayType) || DisplayType.isNumeric(displayType) || DisplayType.isDate(displayType))
{
stopCellEditing();
}
//
// Fire delegated action listener
if (actionListener != null)
{
actionListener.actionPerformed(e);
}
} // actionPerformed
/**
* Dispose
*/
public void dispose()
{
if (m_editor != null)
{
m_editor.dispose();
m_editor = null;
}
actionListener = null;
// m_mField = null;
// m_table = null;
} // dispose
/**
* @return true if we can stop current editor
*/
private boolean canStopEditing()
{
// nothing atm
return true;
}
@Override
public boolean stopCellEditing()
{
if (!canStopEditing())
{ | return false;
}
if (!super.stopCellEditing())
{
return false;
}
clearCurrentEditing();
return true;
}
@Override
public void cancelCellEditing()
{
if (!canStopEditing())
{
return ;
}
clearCurrentEditing();
super.cancelCellEditing();
}
private void clearCurrentEditing()
{
// metas: reset editing coordinates
editingRowIndexModel = -1;
editingColumnIndexModel = -1;
editingKeyId = -100;
if (m_editor instanceof VLookup)
{
((VLookup)m_editor).setStopEditing(true);
}
}
public void setActionListener(final ActionListener listener)
{
actionListener = listener;
}
} // VCellEditor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VCellEditor.java | 1 |
请完成以下Java代码 | public ErrorInfo handleIllegalState(FlowableIllegalStateException e, HttpServletRequest request) {
if (logger.isDebugEnabled()) {
logger.debug("Illegal state. Message: {}, Request: {} {}", e.getMessage(), request.getMethod(), request.getRequestURI());
}
return new ErrorInfo("Bad request", e);
}
@ResponseStatus(HttpStatus.BAD_REQUEST) // 400
@ExceptionHandler(HttpMessageConversionException.class)
@ResponseBody
public ErrorInfo handleBadMessageConversion(HttpMessageConversionException e, HttpServletRequest request) {
if (sendFullErrorException) {
if (logger.isDebugEnabled()) {
logger.debug("Invalid message conversion. Message: {}, Request: {} {}", e.getMessage(), request.getMethod(), request.getRequestURI());
}
return new ErrorInfo("Bad request", e);
} else {
String errorIdentifier = UUID.randomUUID().toString();
logger.warn("Invalid Message conversion exception. Error ID: {}. Message: {}, Request: {} {}", errorIdentifier, e.getMessage(), request.getMethod(), request.getRequestURI());
ErrorInfo errorInfo = new ErrorInfo("Bad request", null);
errorInfo.setException("Invalid HTTP message. Error ID: " + errorIdentifier);
return errorInfo;
}
}
@ResponseStatus(HttpStatus.CONFLICT) // 409
@ExceptionHandler(FlowableTaskAlreadyClaimedException.class)
@ResponseBody
public ErrorInfo handleTaskAlreadyClaimed(FlowableTaskAlreadyClaimedException e, HttpServletRequest request) {
if (logger.isDebugEnabled()) {
logger.debug("Task was already claimed. Message: {}, Request: {} {}", e.getMessage(), request.getMethod(), request.getRequestURI()); | }
return new ErrorInfo("Task was already claimed", e);
}
// Fall back
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 500
@ExceptionHandler(Exception.class)
@ResponseBody
public ErrorInfo handleOtherException(Exception e, HttpServletRequest request) {
if (sendFullErrorException) {
logger.error("Unhandled exception. Request: {} {}", request.getMethod(), request.getRequestURI(), e);
return new ErrorInfo("Internal server error", e);
} else {
String errorIdentifier = UUID.randomUUID().toString();
logger.error("Unhandled exception. Error ID: {}. Request: {} {}", errorIdentifier, request.getMethod(), request.getRequestURI(), e);
ErrorInfo errorInfo = new ErrorInfo("Internal server error", e);
errorInfo.setException("Error with ID: " + errorIdentifier);
return errorInfo;
}
}
public boolean isSendFullErrorException() {
return sendFullErrorException;
}
public void setSendFullErrorException(boolean sendFullErrorException) {
this.sendFullErrorException = sendFullErrorException;
}
} | repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\exception\BaseExceptionHandlerAdvice.java | 1 |
请完成以下Java代码 | private void createTable(XSLFSlide slide) {
XSLFTable tbl = slide.createTable();
tbl.setAnchor(new Rectangle(50, 50, 450, 300));
int numColumns = 3;
int numRows = 5;
// header
XSLFTableRow headerRow = tbl.addRow();
headerRow.setHeight(50);
for (int i = 0; i < numColumns; i++) {
XSLFTableCell th = headerRow.addCell();
XSLFTextParagraph p = th.addNewTextParagraph();
p.setTextAlign(TextParagraph.TextAlign.CENTER);
XSLFTextRun r = p.addNewTextRun();
r.setText("Header " + (i + 1));
r.setBold(true);
r.setFontColor(Color.white);
th.setFillColor(new Color(79, 129, 189));
th.setBorderWidth(TableCell.BorderEdge.bottom, 2.0);
th.setBorderColor(TableCell.BorderEdge.bottom, Color.white);
// all columns are equally sized
tbl.setColumnWidth(i, 150);
} | // data
for (int rownum = 0; rownum < numRows; rownum++) {
XSLFTableRow tr = tbl.addRow();
tr.setHeight(50);
for (int i = 0; i < numColumns; i++) {
XSLFTableCell cell = tr.addCell();
XSLFTextParagraph p = cell.addNewTextParagraph();
XSLFTextRun r = p.addNewTextRun();
r.setText("Cell " + (i * rownum + 1));
if (rownum % 2 == 0) {
cell.setFillColor(new Color(208, 216, 232));
} else {
cell.setFillColor(new Color(233, 247, 244));
}
}
}
}
} | repos\tutorials-master\apache-poi-2\src\main\java\com\baeldung\poi\powerpoint\PowerPointHelper.java | 1 |
请完成以下Java代码 | private void addTextMsg(@Nullable final Throwable ex)
{
if (ex == null)
{
return;
}
addTextMsg(AdempiereException.extractMessage(ex));
final AdempiereException metasfreshException = AdempiereException.wrapIfNeeded(ex);
final AdIssueId adIssueId = context.createIssue(metasfreshException);
setIssueId(adIssueId);
}
void setProcessingResultMessage(@Nullable final String msg)
{
this.processingResultMessage = msg;
this.processingResultException = null;
addTextMsg(msg); | }
void setProcessingResultMessage(@NonNull final Throwable ex)
{
this.processingResultMessage = AdempiereException.extractMessage(ex);
this.processingResultException = ex;
addTextMsg(ex);
}
@Nullable
public String getProcessingResultMessage() { return processingResultMessage; }
@Nullable
public Throwable getProcessingResultException() { return processingResultException; }
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\WFProcess.java | 1 |
请完成以下Java代码 | private boolean isApplyUserGroupRecordAccess(
@NonNull final RoleId roleId,
@NonNull final String tableName)
{
return configs
.getByRoleId(roleId)
.isTableHandled(tableName);
}
public boolean hasRecordPermission(
@NonNull final UserId userId,
@NonNull final RoleId roleId,
@NonNull final TableRecordReference recordRef,
@NonNull final Access permission)
{
if (!isApplyUserGroupRecordAccess(roleId, recordRef.getTableName()))
{
return true;
}
final RecordAccessQuery query = RecordAccessQuery.builder()
.recordRef(recordRef)
.permission(permission)
.principals(getPrincipals(userId)) | .build();
return recordAccessRepository.query(query)
.addOnlyActiveRecordsFilter()
.create()
.anyMatch();
}
private Set<Principal> getPrincipals(@NonNull final UserId userId)
{
final ImmutableSet.Builder<Principal> principals = ImmutableSet.builder();
principals.add(Principal.userId(userId));
for (final UserGroupId userGroupId : userGroupsRepo.getAssignedGroupIdsByUserId(userId))
{
principals.add(Principal.userGroupId(userGroupId));
}
return principals.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\record_access\RecordAccessService.java | 1 |
请完成以下Java代码 | public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public int getAge() { | return age;
}
public void setAge(int age) {
this.age = age;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", age=" + age +
'}';
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-1 课: Spring Boot 使用 JDBC 操作数据库\spring-boot-jdbc\src\main\java\com\neo\model\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Job xmlFileItemWriterJob() throws Exception {
return jobBuilderFactory.get("xmlFileItemWriterJob")
.start(step())
.build();
}
private Step step() throws Exception {
return stepBuilderFactory.get("step")
.<TestData, TestData>chunk(2)
.reader(simpleReader)
.writer(xmlFileItemWriter())
.build();
}
private StaxEventItemWriter<TestData> xmlFileItemWriter() throws IOException {
StaxEventItemWriter<TestData> writer = new StaxEventItemWriter<>();
// 通过XStreamMarshaller将TestData转换为xml
XStreamMarshaller marshaller = new XStreamMarshaller(); | Map<String,Class<TestData>> map = new HashMap<>(1);
map.put("test", TestData.class);
marshaller.setAliases(map); // 设置xml标签
writer.setRootTagName("tests"); // 设置根标签
writer.setMarshaller(marshaller);
FileSystemResource file = new FileSystemResource("/Users/mrbird/Desktop/file.xml");
Path path = Paths.get(file.getPath());
if (!Files.exists(path)) {
Files.createFile(path);
}
writer.setResource(file); // 设置目标文件路径
return writer;
}
} | repos\SpringAll-master\69.spring-batch-itemwriter\src\main\java\cc\mrbird\batch\job\XmlFileItemWriterDemo.java | 2 |
请完成以下Java代码 | public I_C_Activity getC_Activity() throws RuntimeException
{
return (I_C_Activity)MTable.get(getCtx(), I_C_Activity.Table_Name)
.getPO(getC_Activity_ID(), get_TrxName()); }
/** Set Activity.
@param C_Activity_ID
Business Activity
*/
public void setC_Activity_ID (int C_Activity_ID)
{
if (C_Activity_ID < 1)
set_Value (COLUMNNAME_C_Activity_ID, null);
else
set_Value (COLUMNNAME_C_Activity_ID, Integer.valueOf(C_Activity_ID));
}
/** Get Activity.
@return Business Activity
*/
public int getC_Activity_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Activity_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Payroll Department.
@param HR_Department_ID Payroll Department */
public void setHR_Department_ID (int HR_Department_ID)
{
if (HR_Department_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_Department_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_Department_ID, Integer.valueOf(HR_Department_ID));
}
/** Get Payroll Department.
@return Payroll Department */
public int getHR_Department_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Department_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 Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Department.java | 1 |
请完成以下Java代码 | public CostPrice withComponentsCostPrice(final CostAmount componentsCostPrice)
{
return toBuilder().componentsCostPrice(componentsCostPrice).build();
}
public CostPrice add(final CostPrice costPrice)
{
if (!UomId.equals(this.getUomId(), costPrice.getUomId()))
{
throw new AdempiereException("UOM does not match: " + this + ", " + costPrice);
}
return builder()
.ownCostPrice(getOwnCostPrice().add(costPrice.getOwnCostPrice()))
.componentsCostPrice(getComponentsCostPrice().add(costPrice.getComponentsCostPrice()))
.uomId(getUomId())
.build();
}
public CostAmount multiply(@NonNull final Quantity quantity)
{
if (!UomId.equals(uomId, quantity.getUomId()))
{
throw new AdempiereException("UOM does not match: " + this + ", " + quantity);
}
return toCostAmount().multiply(quantity);
}
public CostAmount multiply(
@NonNull final Duration duration, | @NonNull final TemporalUnit durationUnit)
{
final BigDecimal durationBD = DurationUtils.toBigDecimal(duration, durationUnit);
return toCostAmount().multiply(durationBD);
}
public CostPrice convertAmounts(
@NonNull final UomId toUomId,
@NonNull final UnaryOperator<CostAmount> converter)
{
if (UomId.equals(this.uomId, toUomId))
{
return this;
}
return toBuilder()
.uomId(toUomId)
.ownCostPrice(converter.apply(getOwnCostPrice()))
.componentsCostPrice(converter.apply(getComponentsCostPrice()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\costing\CostPrice.java | 1 |
请完成以下Java代码 | public boolean isCreateMovementOnComplete()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_IsCreateMovementOnComplete, false);
}
public Quantity getQtyToShip(final I_DD_OrderLine_Or_Alternative ddOrderLineOrAlt)
{
return ddOrderLowLevelService.getQtyToShip(ddOrderLineOrAlt);
}
public void assignToResponsible(@NonNull final I_DD_Order ddOrder, @NonNull final UserId responsibleId)
{
final UserId currentResponsibleId = extractCurrentResponsibleId(ddOrder);
if (currentResponsibleId == null)
{
ddOrder.setAD_User_Responsible_ID(responsibleId.getRepoId());
save(ddOrder);
}
else if (!UserId.equals(currentResponsibleId, responsibleId))
{
throw new AdempiereException("DD Order already assigned to a different responsible");
}
else
{
// already assigned to that responsible,
// shall not happen but we can safely ignore the case
logger.warn("Order {} already assigned to {}", ddOrder.getDD_Order_ID(), responsibleId);
}
}
@Nullable
private static UserId extractCurrentResponsibleId(final I_DD_Order ddOrder)
{
return UserId.ofRepoIdOrNullIfSystem(ddOrder.getAD_User_Responsible_ID());
}
public void unassignFromResponsible(final DDOrderId ddOrderId)
{
final I_DD_Order ddOrder = getById(ddOrderId); | unassignFromResponsibleAndSave(ddOrder);
}
public void removeAllNotStartedSchedules(final DDOrderId ddOrderId)
{
ddOrderMoveScheduleService.removeNotStarted(ddOrderId);
}
private void unassignFromResponsibleAndSave(final I_DD_Order ddOrder)
{
ddOrder.setAD_User_Responsible_ID(-1);
save(ddOrder);
}
public Set<ProductId> getProductIdsByDDOrderIds(final Collection<DDOrderId> ddOrderIds)
{
return ddOrderLowLevelDAO.getProductIdsByDDOrderIds(ddOrderIds);
}
public Stream<I_DD_OrderLine> streamLinesByDDOrderIds(@NonNull final Collection<DDOrderId> ddOrderIds)
{
return ddOrderLowLevelDAO.streamLinesByDDOrderIds(ddOrderIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\DDOrderService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class StringLookupValueDocumentFieldValueLoader implements DocumentFieldValueLoader
{
@NonNull String sqlColumnName;
@NonNull String sqlDisplayColumnName;
@Override
@Nullable
public StringLookupValue retrieveFieldValue(
@NonNull final ResultSet rs,
final boolean isDisplayColumnAvailable,
final String adLanguage,
final LookupDescriptor lookupDescriptor_NOTUSED) throws SQLException
{
final String key = rs.getString(sqlColumnName);
if (rs.wasNull())
{
return null;
}
if (isDisplayColumnAvailable)
{
final StringLookupValue lookupValue = SqlForFetchingLookupById.retrieveStringLookupValue(rs, sqlDisplayColumnName, adLanguage);
if (lookupValue != null)
{
return lookupValue;
}
}
return StringLookupValue.unknown(key);
}
}
@Value
private static class LoadLabelsValues implements DocumentFieldValueLoader
{
@NonNull String sqlValuesColumn;
@Override
public LookupValuesList retrieveFieldValue(
@NonNull final ResultSet rs,
final boolean isDisplayColumnAvailable_NOTUSED,
final String adLanguage_NOTUSED,
@Nullable final LookupDescriptor lookupDescriptor) throws SQLException
{
// FIXME: atm we are avoiding NPE by returning EMPTY.
if (lookupDescriptor == null)
{
return LookupValuesList.EMPTY;
}
final LabelsLookup lookup = LabelsLookup.cast(lookupDescriptor);
final List<Object> ids = retrieveIds(rs);
return lookup.retrieveExistingValuesByIds(ids);
}
private List<Object> retrieveIds(final ResultSet rs) throws SQLException
{
final Array sqlArray = rs.getArray(sqlValuesColumn);
if (sqlArray != null)
{
return Stream.of((Object[])sqlArray.getArray())
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList()); | }
else
{
return ImmutableList.of();
}
}
}
@Builder
@Value
private static class ColorDocumentFieldValueLoader implements DocumentFieldValueLoader
{
@NonNull String sqlColumnName;
@Override
@Nullable
public Object retrieveFieldValue(
@NonNull final ResultSet rs,
final boolean isDisplayColumnAvailable_NOTUSED,
final String adLanguage_NOTUSED,
final LookupDescriptor lookupDescriptor_NOTUSED) throws SQLException
{
final ColorId adColorId = ColorId.ofRepoIdOrNull(rs.getInt(sqlColumnName));
if (adColorId == null)
{
return null;
}
final IColorRepository colorRepository = Services.get(IColorRepository.class);
final MFColor color = colorRepository.getColorById(adColorId);
if (color == null)
{
return null;
}
final Color awtColor = color.toFlatColor().getFlatColor();
return ColorValue.ofRGB(awtColor.getRed(), awtColor.getGreen(), awtColor.getBlue());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\DocumentFieldValueLoaders.java | 2 |
请完成以下Java代码 | public void logSqlMigrationContextInfo(final I_AD_Menu record)
{
if (MigrationScriptFileLoggerHolder.isDisabled())
{
return;
}
MigrationScriptFileLoggerHolder.logComment("Name: " + record.getName());
final String action = record.getAction();
MigrationScriptFileLoggerHolder.logComment("Action Type: " + action);
if (X_AD_Menu.ACTION_Window.equals(action))
{
final AdWindowId adWindowId = AdWindowId.ofRepoIdOrNull(record.getAD_Window_ID());
if (adWindowId != null)
{
final ADWindowName windowName = Names.ADWindowName_Loader.retrieve(adWindowId);
MigrationScriptFileLoggerHolder.logComment("Window: " + windowName.toShortString());
}
}
else if (X_AD_Menu.ACTION_Process.equals(action))
{
final AdProcessId adProcessId = AdProcessId.ofRepoIdOrNull(record.getAD_Process_ID());
if (adProcessId != null)
{ | final ADProcessName processName = Names.ADProcessName_Loader.retrieve(adProcessId);
MigrationScriptFileLoggerHolder.logComment("Process: " + processName.toShortString());
}
}
else if (X_AD_Menu.ACTION_Report.equals(action))
{
final AdProcessId adProcessId = AdProcessId.ofRepoIdOrNull(record.getAD_Process_ID());
if (adProcessId != null)
{
final ADProcessName processName = Names.ADProcessName_Loader.retrieve(adProcessId);
MigrationScriptFileLoggerHolder.logComment("Report: " + processName.toShortString());
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\validator\sql_migration_context_info\interceptor\AD_Menu.java | 1 |
请完成以下Java代码 | public boolean isNoDeliveryPossible()
{
return this.equals(KEINE_LIEFERUNG_ABER_DISPO_MOEGLICH)
|| this.equals(KEINE_LIEFERUNG_ABER_NACHLIEFERUNG_MOEGLICH)
|| this.equals(KEINE_LIEFERUNG_ABER_NORMAL_MOEGLICH)
|| this.equals(KEINE_LIEFERUNG_ABER_VERBUND_MOEGLICH)
|| this.equals(NICHT_LIEFERBAR);
}
private static final Map<String, Type> MAP = ImmutableMap
.<String, Type> builder()
.put("Normal", NORMAL)
.put("Verbund", VERBUND)
.put("Dispo", DISPO)
.put("KeineLieferungAberNormalMoeglich", KEINE_LIEFERUNG_ABER_NORMAL_MOEGLICH)
.put("KeineLieferungAberVerbundMoeglich", KEINE_LIEFERUNG_ABER_VERBUND_MOEGLICH)
.put("KeineLieferungAberNachlieferungMoeglich", KEINE_LIEFERUNG_ABER_NACHLIEFERUNG_MOEGLICH)
.put("KeineLieferungAberDispoMoeglich", KEINE_LIEFERUNG_ABER_DISPO_MOEGLICH)
.put("NichtLieferbar", NICHT_LIEFERBAR)
.build();
public static Type ofStringValueOrNull(@Nullable final String value)
{
if (value == null)
{
return null;
}
final Type result = MAP.get(value);
return result;
}
public static String getValueOrNull(@Nullable final Type type)
{
if (type == null)
{
return null;
}
return type.value;
}
}
@JsonProperty("id")
@NonNull
OrderResponsePackageItemPartId id;
@JsonProperty("qty")
@NonNull | Quantity qty;
@JsonProperty("type")
Type type;
@JsonProperty("deliveryDate")
ZonedDateTime deliveryDate;
@JsonProperty("defectReason")
OrderDefectReason defectReason;
@JsonProperty("tour")
String tour;
@JsonProperty("tourId")
String tourId;
@JsonProperty("tourDeviation")
boolean tourDeviation;
@Builder
@JsonCreator
private OrderResponsePackageItemPart(
@JsonProperty("id") final OrderResponsePackageItemPartId id,
@JsonProperty("qty") @NonNull final Quantity qty,
@JsonProperty("type") final Type type,
@JsonProperty("deliveryDate") final ZonedDateTime deliveryDate,
@JsonProperty("defectReason") final OrderDefectReason defectReason,
@JsonProperty("tour") final String tour,
@JsonProperty("tourId") final String tourId,
@JsonProperty("tourDeviation") final boolean tourDeviation)
{
this.id = id != null ? id : OrderResponsePackageItemPartId.random();
this.qty = qty;
this.type = type;
this.deliveryDate = deliveryDate;
this.defectReason = defectReason;
this.tour = tour;
this.tourId = tourId;
this.tourDeviation = tourDeviation;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\OrderResponsePackageItemPart.java | 1 |
请完成以下Java代码 | public Builder issuedAt(Instant issuedAt) {
return claim(OAuth2TokenClaimNames.IAT, issuedAt);
}
/**
* Sets the ID {@code (jti)} claim, which provides a unique identifier for the
* OAuth 2.0 Token.
* @param jti the unique identifier for the OAuth 2.0 Token
* @return the {@link Builder}
*/
public Builder id(String jti) {
return claim(OAuth2TokenClaimNames.JTI, jti);
}
/**
* Sets the claim.
* @param name the claim name
* @param value the claim value
* @return the {@link Builder}
*/
public Builder claim(String name, Object value) {
Assert.hasText(name, "name cannot be empty");
Assert.notNull(value, "value cannot be null");
this.claims.put(name, value);
return this;
}
/**
* A {@code Consumer} to be provided access to the claims allowing the ability to
* add, replace, or remove.
* @param claimsConsumer a {@code Consumer} of the claims
* @return the {@link Builder} | */
public Builder claims(Consumer<Map<String, Object>> claimsConsumer) {
claimsConsumer.accept(this.claims);
return this;
}
/**
* Builds a new {@link OAuth2TokenClaimsSet}.
* @return a {@link OAuth2TokenClaimsSet}
*/
public OAuth2TokenClaimsSet build() {
Assert.notEmpty(this.claims, "claims cannot be empty");
// The value of the 'iss' claim is a String or URL (StringOrURI).
// Attempt to convert to URL.
Object issuer = this.claims.get(OAuth2TokenClaimNames.ISS);
if (issuer != null) {
URL convertedValue = ClaimConversionService.getSharedInstance().convert(issuer, URL.class);
if (convertedValue != null) {
this.claims.put(OAuth2TokenClaimNames.ISS, convertedValue);
}
}
return new OAuth2TokenClaimsSet(this.claims);
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\token\OAuth2TokenClaimsSet.java | 1 |
请完成以下Java代码 | public void setVolume (final @Nullable BigDecimal Volume)
{
set_Value (COLUMNNAME_Volume, Volume);
}
@Override
public BigDecimal getVolume()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setWarehouse_temperature (final @Nullable java.lang.String Warehouse_temperature)
{
set_Value (COLUMNNAME_Warehouse_temperature, Warehouse_temperature);
}
@Override
public java.lang.String getWarehouse_temperature()
{
return get_ValueAsString(COLUMNNAME_Warehouse_temperature);
}
@Override
public void setWeight (final @Nullable BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
} | @Override
public void setWeight_UOM_ID (final int Weight_UOM_ID)
{
if (Weight_UOM_ID < 1)
set_Value (COLUMNNAME_Weight_UOM_ID, null);
else
set_Value (COLUMNNAME_Weight_UOM_ID, Weight_UOM_ID);
}
@Override
public int getWeight_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_Weight_UOM_ID);
}
@Override
public void setWidthInCm (final int WidthInCm)
{
set_Value (COLUMNNAME_WidthInCm, WidthInCm);
}
@Override
public int getWidthInCm()
{
return get_ValueAsInt(COLUMNNAME_WidthInCm);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserDetail {
@Id
@GeneratedValue
private Long id;
@Column(nullable = false, unique = true)
private Long userId;
private Integer age;
private String realName;
private String status;
private String hobby;
private String introduction;
private String lastLoginIp;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public String getRealName() {
return realName;
}
public void setRealName(String realName) {
this.realName = realName;
}
public String getStatus() {
return status;
}
public void setStatus(String status) { | this.status = status;
}
public String getHobby() {
return hobby;
}
public void setHobby(String hobby) {
this.hobby = hobby;
}
public String getIntroduction() {
return introduction;
}
public void setIntroduction(String introduction) {
this.introduction = introduction;
}
public String getLastLoginIp() {
return lastLoginIp;
}
public void setLastLoginIp(String lastLoginIp) {
this.lastLoginIp = lastLoginIp;
}
@Override
public String toString() {
return "UserDetail{" +
"id=" + id +
", userId=" + userId +
", age=" + age +
", realName='" + realName + '\'' +
", status='" + status + '\'' +
", hobby='" + hobby + '\'' +
", introduction='" + introduction + '\'' +
", lastLoginIp='" + lastLoginIp + '\'' +
'}';
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-4 课: Spring Data JPA 的基本使用\spring-boot-jpa\src\main\java\com\neo\model\UserDetail.java | 2 |
请完成以下Java代码 | public class MWithholding extends X_C_Withholding
{
/**
*
*/
private static final long serialVersionUID = 7734620609620104180L;
/**
* Standard Constructor
* @param ctx context
* @param C_Withholding_ID id
* @param trxName transaction
*/
public MWithholding (Properties ctx, int C_Withholding_ID, String trxName)
{
super (ctx, C_Withholding_ID, trxName);
} // MWithholding
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MWithholding (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MWithholding | /**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (newRecord && success)
insert_Accounting("C_Withholding_Acct", "C_AcctSchema_Default", null);
return success;
} // afterSave
/**
* Before Delete
* @return true
*/
protected boolean beforeDelete ()
{
return delete_Accounting("C_Withholding_Acct");
} // beforeDelete
} // MWithholding | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MWithholding.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void saveByELEvaluation() {
firstName = (String) evaluateEL("#{firstName.value}", String.class);
FacesContext ctx = FacesContext.getCurrentInstance();
FacesMessage theMessage = new FacesMessage("Name component Evaluated: " + firstName);
theMessage.setSeverity(FacesMessage.SEVERITY_INFO);
ctx.addMessage(null, theMessage);
}
private Object evaluateEL(String elExpression, Class<?> clazz) {
Object toReturn = null;
FacesContext ctx = FacesContext.getCurrentInstance();
Application app = ctx.getApplication();
toReturn = app.evaluateExpressionGet(ctx, elExpression, clazz);
return toReturn;
}
/**
* @return the firstName
*/
public String getFirstName() {
return firstName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName; | }
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
/**
* @return the pageDescription
*/
public String getPageDescription() {
return pageDescription;
}
/**
* @param pageDescription the pageDescription to set
*/
public void setPageDescription(String pageDescription) {
this.pageDescription = pageDescription;
}
/**
* @return the pageCounter
*/
public int getPageCounter() {
return pageCounter;
}
/**
* @param pageCounter the pageCounter to set
*/
public void setPageCounter(int pageCounter) {
this.pageCounter = pageCounter;
}
} | repos\tutorials-master\web-modules\jsf\src\main\java\com\baeldung\springintegration\controllers\ELSampleBean.java | 2 |
请完成以下Java代码 | public int hashCode()
{
long bits = Double.doubleToLongBits(width);
bits ^= Double.doubleToLongBits(height) * 31;
return (((int) bits) ^ ((int) (bits >> 32)));
} // hashCode
/**
* Equals
* @param obj object
* @return true if w/h is same
*/
public boolean equals (Object obj)
{
if (obj != null && obj instanceof Dimension2D)
{
Dimension2D d = (Dimension2D)obj;
if (d.getWidth() == width && d.getHeight() == height)
return true; | }
return false;
} // equals
/**
* String Representation
* @return info
*/
public String toString()
{
StringBuffer sb = new StringBuffer();
sb.append("Dimension2D[w=").append(width).append(",h=").append(height).append("]");
return sb.toString();
} // toString
} // Dimension2DImpl | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\Dimension2DImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class JitterConfig {
private double randomFactor = 0.5;
public void validate() {
Assert.isTrue(randomFactor >= 0 && randomFactor <= 1,
"random factor must be between 0 and 1 (default 0.5)");
}
public JitterConfig() {
}
public JitterConfig(double randomFactor) {
this.randomFactor = randomFactor;
}
public double getRandomFactor() {
return randomFactor; | }
public void setRandomFactor(double randomFactor) {
this.randomFactor = randomFactor;
}
@Override
public String toString() {
return new ToStringCreator(this).append("randomFactor", randomFactor).toString();
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RetryGatewayFilterFactory.java | 2 |
请完成以下Java代码 | public class GL_JournalBatch
{
private final IGLJournalDAO glJournalDAO = Services.get(IGLJournalDAO.class);
@Init
public void init()
{
CopyRecordFactory.enableForTableName(I_GL_JournalBatch.Table_Name);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = { I_GL_JournalBatch.COLUMNNAME_DateAcct, I_GL_JournalBatch.COLUMNNAME_DateDoc })
public void updateDateAcct(final I_GL_JournalBatch journalBatch)
{
final List<I_GL_Journal> journals = glJournalDAO.retrieveJournalsForBatch(journalBatch);
if (journals.isEmpty())
{
// do nothing
return;
}
final Timestamp dateAcct = journalBatch.getDateAcct(); | final Timestamp dateDoc = journalBatch.getDateDoc();
for (final I_GL_Journal journal : journals)
{
// Don't change processed journals
if (journal.isProcessed())
{
continue;
}
journal.setDateAcct(dateAcct);
journal.setDateDoc(dateDoc);
InterfaceWrapperHelper.save(journal);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\GL_JournalBatch.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setMail(String mail) {
this.mail = mail;
}
public String getLicencePic() {
return licencePic;
}
public void setLicencePic(String licencePic) {
this.licencePic = licencePic;
}
public Integer getUserType() {
return userType;
} | public void setUserType(Integer userType) {
this.userType = userType;
}
@Override
public String toString() {
return "RegisterReq{" +
"username='" + username + '\'' +
", password='" + password + '\'' +
", phone='" + phone + '\'' +
", mail='" + mail + '\'' +
", licencePic='" + licencePic + '\'' +
", userType=" + userType +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\req\user\RegisterReq.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getAcceptingPartyGLN() {
return acceptingPartyGLN;
}
/**
* Sets the value of the acceptingPartyGLN property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAcceptingPartyGLN(String value) {
this.acceptingPartyGLN = value;
}
/**
* Gets the value of the contractNumber property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getContractNumber() {
return contractNumber;
}
/**
* Sets the value of the contractNumber property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setContractNumber(String value) {
this.contractNumber = value;
}
/**
* Gets the value of the thm property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isTHM() {
return thm;
}
/**
* Sets the value of the thm property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setTHM(Boolean value) { | this.thm = value;
}
/**
* Gets the value of the nonReturnableContainer property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isNonReturnableContainer() {
return nonReturnableContainer;
}
/**
* Sets the value of the nonReturnableContainer property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setNonReturnableContainer(Boolean value) {
this.nonReturnableContainer = value;
}
/**
* Gets the value of the specialConditionCode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSpecialConditionCode() {
return specialConditionCode;
}
/**
* Sets the value of the specialConditionCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSpecialConditionCode(String value) {
this.specialConditionCode = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVOICListLineItemExtensionType.java | 2 |
请完成以下Java代码 | private ScriptEngine getEngine()
{
return _engine;
}
public ScriptExecutor putContext(final Properties ctx, final int windowNo)
{
Check.assumeNotNull(ctx, "Parameter ctx is not null");
final ScriptEngine engine = getEngine();
for (final Enumeration<?> en = ctx.propertyNames(); en.hasMoreElements();)
{
final String key = en.nextElement().toString();
// filter
if (key == null || key.length() == 0
|| key.startsWith("P") // Preferences
|| key.indexOf('|') != -1 && !key.startsWith(String.valueOf(windowNo)) // other Window Settings
|| key.indexOf('|') != -1 && key.indexOf('|') != key.lastIndexOf('|') // other tab
)
{
continue;
}
final String value = ctx.getProperty(key);
if (value != null)
{
final String engineKey = convertToEngineKey(key, windowNo);
engine.put(engineKey, value);
}
}
//
// Also put the context and windowNo as argument
putArgument("Ctx", ctx);
putArgument("WindowNo", windowNo);
return this;
}
public ScriptExecutor putArgument(final String name, final Object value)
{
Check.assumeNotEmpty(name, "name is not empty");
getEngine().put(ARGUMENTS_PREFIX + name, value);
return this;
}
public ScriptExecutor putProcessParameter(final String name, final Object value)
{ | Check.assumeNotEmpty(name, "name is not empty");
getEngine().put(PARAMETERS_PREFIX + name, value);
return this;
}
public static String convertToEngineKey(final String key, final int windowNo)
{
final String keyPrefix = windowNo + "|";
if (key.startsWith(keyPrefix))
{
String retValue = WINDOW_CONTEXT_PREFIX + key.substring(keyPrefix.length());
retValue = StringUtils.replace(retValue, "|", "_");
return retValue;
}
else
{
String retValue = null;
if (key.startsWith("#"))
{
retValue = GLOBAL_CONTEXT_PREFIX + key.substring(1);
}
else
{
retValue = key;
}
retValue = StringUtils.replace(retValue, "#", "_");
return retValue;
}
}
public ScriptExecutor putAll(final Map<String, ? extends Object> context)
{
final ScriptEngine engine = getEngine();
context.entrySet()
.stream()
.forEach(entry -> engine.put(entry.getKey(), entry.getValue()));
return this;
}
public ScriptExecutor setThrowExceptionIfResultNotEmpty()
{
throwExceptionIfResultNotEmpty = true;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\script\ScriptExecutor.java | 1 |
请完成以下Java代码 | public List<HistoricDetailEntity> findHistoricDetailsByProcessInstanceId(String processInstanceId) {
return getDbSqlSession().selectList("selectHistoricDetailByProcessInstanceId", processInstanceId);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricDetailEntity> findHistoricDetailsByTaskId(String taskId) {
return getDbSqlSession().selectList("selectHistoricDetailByTaskId", taskId);
}
@Override
public long findHistoricDetailCountByQueryCriteria(HistoricDetailQueryImpl historicVariableUpdateQuery) {
return (Long) getDbSqlSession().selectOne(
"selectHistoricDetailCountByQueryCriteria",
historicVariableUpdateQuery
);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricDetail> findHistoricDetailsByQueryCriteria(
HistoricDetailQueryImpl historicVariableUpdateQuery,
Page page
) {
return getDbSqlSession().selectList("selectHistoricDetailsByQueryCriteria", historicVariableUpdateQuery, page);
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricDetail> findHistoricDetailsByNativeQuery(
Map<String, Object> parameterMap,
int firstResult, | int maxResults
) {
return getDbSqlSession().selectListWithRawParameter(
"selectHistoricDetailByNativeQuery",
parameterMap,
firstResult,
maxResults
);
}
@Override
public long findHistoricDetailCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectHistoricDetailCountByNativeQuery", parameterMap);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisHistoricDetailDataManager.java | 1 |
请完成以下Java代码 | private void notifyCandidateStarterUserAddedListeners(
ProcessCandidateStarterUserAddedEvent processCandidateStarterUserAddedEvent
) {
for (ProcessRuntimeEventListener<
ProcessCandidateStarterUserAddedEvent
> listener : candidateStarterUserListeners) {
listener.onEvent(processCandidateStarterUserAddedEvent);
}
}
private void notifyCandidateStarterGroupAddedListeners(
ProcessCandidateStarterGroupAddedEvent processCandidateStarterGroupAddedEvent
) {
for (ProcessRuntimeEventListener<
ProcessCandidateStarterGroupAddedEvent
> listener : candidateStarterGroupListeners) {
listener.onEvent(processCandidateStarterGroupAddedEvent);
}
}
private ProcessCandidateStarterUserAddedEvent createCandidateStarterUserEvent(IdentityLink identityLink) {
return new ProcessCandidateStarterUserAddedEventImpl(
new ProcessCandidateStarterUserImpl(identityLink.getProcessDefinitionId(), identityLink.getUserId())
);
}
private ProcessCandidateStarterGroupAddedEvent createCandidateStarterGroupEvent(IdentityLink identityLink) {
return new ProcessCandidateStarterGroupAddedEventImpl( | new ProcessCandidateStarterGroupImpl(identityLink.getProcessDefinitionId(), identityLink.getGroupId())
);
}
private void publishCandidateStarterEvents(
List<ProcessCandidateStarterUserAddedEvent> candidateStarterUserAddedEvents,
List<ProcessCandidateStarterGroupAddedEvent> candidateStarterGroupAddedEvents
) {
if (!candidateStarterUserAddedEvents.isEmpty()) {
eventPublisher.publishEvent(new ProcessCandidateStarterUserAddedEvents(candidateStarterUserAddedEvents));
}
if (!candidateStarterGroupAddedEvents.isEmpty()) {
eventPublisher.publishEvent(new ProcessCandidateStarterGroupAddedEvents(candidateStarterGroupAddedEvents));
}
}
@Override
public void doStop() {
// nothing
}
} | repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\ProcessCandidateStartersEventProducer.java | 1 |
请完成以下Java代码 | public class MergeMaps {
private static Map<String, Employee> map1 = new HashMap<>();
private static Map<String, Employee> map2 = new HashMap<>();
public static void main(String[] args) {
initialize();
mergeFunction();
streamConcat();
streamOf();
streamEx();
streamMerge();
}
private static void streamMerge() {
Map<String, Employee> map3 = map2.entrySet()
.stream()
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> new Employee(v1.getId(), v2.getName()),
() -> new HashMap<>(map1)
)
);
System.out.println(map3);
}
private static void streamEx() {
Map<String, Employee> map3 = EntryStream.of(map1)
.append(EntryStream.of(map2))
.toMap((e1, e2) -> e1);
System.out.println(map3);
}
private static void streamOf() {
Map<String, Employee> map3 = Stream.of(map1, map2)
.flatMap(map -> map.entrySet().stream())
.collect(
Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(v1, v2) -> new Employee(v1.getId(), v2.getName())
)
);
map3.entrySet().forEach(System.out::println);
}
private static void streamConcat() {
Map<String, Employee> result = Stream.concat(map1.entrySet().stream(), map2.entrySet().stream()).collect(Collectors.toMap(
Map.Entry::getKey,
Map.Entry::getValue,
(value1, value2) -> new Employee(value2.getId(), value1.getName())
)); | result.entrySet().forEach(System.out::println);
}
private static void mergeFunction() {
Map<String, Employee> map3 = new HashMap<>(map1);
map2.forEach(
(key, value) -> map3.merge(key, value, (v1, v2) ->
new Employee(v1.getId(), v2.getName()))
);
map3.entrySet().forEach(System.out::println);
}
private static void initialize() {
Employee employee1 = new Employee(1L, "Henry");
map1.put(employee1.getName(), employee1);
Employee employee2 = new Employee(22L, "Annie");
map1.put(employee2.getName(), employee2);
Employee employee3 = new Employee(8L, "John");
map1.put(employee3.getName(), employee3);
Employee employee4 = new Employee(2L, "George");
map2.put(employee4.getName(), employee4);
Employee employee5 = new Employee(3L, "Henry");
map2.put(employee5.getName(), employee5);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-2\src\main\java\com\baeldung\map\mergemaps\MergeMaps.java | 1 |
请完成以下Java代码 | protected boolean isBpmnResource(String resourceName) {
for (String suffix : BPMN_RESOURCE_SUFFIXES) {
if (resourceName.endsWith(suffix)) {
return true;
}
}
return false;
}
public ExpressionManager getExpressionManager() {
return expressionManager;
}
public void setExpressionManager(ExpressionManager expressionManager) {
this.expressionManager = expressionManager;
}
public BpmnParser getBpmnParser() {
return bpmnParser; | }
public void setBpmnParser(BpmnParser bpmnParser) {
this.bpmnParser = bpmnParser;
}
public IdGenerator getIdGenerator() {
return idGenerator;
}
public void setIdGenerator(IdGenerator idGenerator) {
this.idGenerator = idGenerator;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\BpmnDeployer.java | 1 |
请完成以下Java代码 | void setGreaterThan(Date date) {
query.createdAfter(date);
}
@Override
void setLowerThan(Date date) {
query.createdBefore(date);
}
@Override
String fieldName() {
return "create time";
}
}.run(createTimes);
}
if (!CollectionUtil.isEmpty(tenantIds)) {
query.tenantIdIn(tenantIds.toArray(new String[0]));
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (TRUE.equals(includeJobsWithoutTenantId)) {
query.includeJobsWithoutTenantId();
}
if (TRUE.equals(acquired)) {
query.acquired();
}
}
@Override
protected void applySortBy(JobQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_JOB_ID_VALUE)) {
query.orderByJobId();
} else if (sortBy.equals(SORT_BY_EXECUTION_ID_VALUE)) { | query.orderByExecutionId();
} else if (sortBy.equals(SORT_BY_PROCESS_INSTANCE_ID_VALUE)) {
query.orderByProcessInstanceId();
} else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_ID_VALUE)) {
query.orderByProcessDefinitionId();
} else if (sortBy.equals(SORT_BY_PROCESS_DEFINITION_KEY_VALUE)) {
query.orderByProcessDefinitionKey();
} else if (sortBy.equals(SORT_BY_JOB_RETRIES_VALUE)) {
query.orderByJobRetries();
} else if (sortBy.equals(SORT_BY_JOB_DUEDATE_VALUE)) {
query.orderByJobDuedate();
} else if (sortBy.equals(SORT_BY_JOB_PRIORITY_VALUE)) {
query.orderByJobPriority();
} else if (sortBy.equals(SORT_BY_TENANT_ID)) {
query.orderByTenantId();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\JobQueryDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getHandleStatus() {
return handleStatus;
}
public void setHandleStatus(String handleStatus) {
this.handleStatus = handleStatus == null ? null : handleStatus.trim();
}
public String getHandleValue() {
return handleValue;
}
public void setHandleValue(String handleValue) {
this.handleValue = handleValue == null ? null : handleValue.trim();
}
public String getHandleRemark() {
return handleRemark;
}
public void setHandleRemark(String handleRemark) {
this.handleRemark = handleRemark == null ? null : handleRemark.trim();
} | public String getOperatorName() {
return operatorName;
}
public void setOperatorName(String operatorName) {
this.operatorName = operatorName == null ? null : operatorName.trim();
}
public String getOperatorAccountNo() {
return operatorAccountNo;
}
public void setOperatorAccountNo(String operatorAccountNo) {
this.operatorAccountNo = operatorAccountNo == null ? null : operatorAccountNo.trim();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistake.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class AccountId implements RepoIdAware
{
@JsonCreator
@NonNull
public static AccountId ofRepoId(final int repoId)
{
return new AccountId(repoId);
}
@Nullable
public static AccountId ofRepoIdOrNull(final int repoId)
{
if (repoId <= 0)
{
return null;
}
else
{
return ofRepoId(repoId);
}
}
@NonNull
public static Optional<AccountId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final AccountId id)
{
return id != null ? id.getRepoId() : -1; | }
int repoId;
private AccountId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_ValidCombination_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(
@Nullable final AccountId id1,
@Nullable final AccountId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AccountId.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class OrderCreateResponse
{
public static OrderCreateResponse ok(final OrderResponse order)
{
return _builder().order(order).build();
}
public static OrderCreateResponse error(Id orderId, BPartnerId bpartnerId, String errorMsg)
{
return _builder()
.error(OrderCreateError.builder().orderId(orderId).bpartnerId(bpartnerId).errorMsg(errorMsg).build())
.build();
}
@JsonProperty("error")
OrderCreateError error;
@JsonProperty("order")
OrderResponse order;
@Builder(builderMethodName = "_builder")
@JsonCreator
private OrderCreateResponse(
@JsonProperty("error") final OrderCreateError error,
@JsonProperty("order") final OrderResponse order)
{
if (error == null && order == null)
{
throw new IllegalArgumentException("order or error shall be set");
}
if (error != null && order != null) | {
throw new IllegalArgumentException("either order or error shall be set");
}
this.error = error;
this.order = order;
}
public boolean isError()
{
return error != null;
}
public OrderCreateError getError()
{
if (error == null)
{
throw new RuntimeException("Not an error response: " + this);
}
return error;
}
public OrderResponse getOrder()
{
if (order == null)
{
throw new RuntimeException("Not an order response: " + this);
}
return order;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\OrderCreateResponse.java | 2 |
请完成以下Java代码 | public Map<String, String> initParams() {
initParams.put(VALUE_PARAM, null);
initParams.put(DISABLED_PARAM, null);
return initParams;
}
@Override
public void parseParams() {
String disabled = initParams.get(DISABLED_PARAM);
if (ServletFilterUtil.isEmpty(disabled)) {
setDisabled(false);
} else {
setDisabled(Boolean.parseBoolean(disabled));
}
String value = initParams.get(VALUE_PARAM);
if (!ServletFilterUtil.isEmpty(value)) {
value = normalizeString(value);
setValue(value);
} else {
setValue(HEADER_DEFAULT_VALUE);
}
}
protected String normalizeString(String value) { | return value
.trim()
.replaceAll("\\s+", " "); // replaces [\t\n\x0B\f\r]
}
@Override
public String getHeaderName() {
return HEADER_NAME;
}
@Override
public String getHeaderValue(final ServletContext servletContext) {
final String nonce = generateNonce();
servletContext.setAttribute(ATTR_CSP_FILTER_NONCE, nonce);
return value.replaceAll("\\" + HEADER_NONCE_PLACEHOLDER, String.format("'nonce-%s'", nonce));
}
protected String generateNonce() {
final byte[] bytes = new byte[20];
ThreadLocalRandom.current().nextBytes(bytes);
return ENCODER.encodeToString(bytes);
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\filter\headersec\provider\impl\ContentSecurityPolicyProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void addStockChangeDetailToFilter(
@NonNull final CandidatesQuery query,
@NonNull final IQueryBuilder<I_MD_Candidate> builder)
{
final StockChangeDetailQuery stockChangeDetail = query.getStockChangeDetailQuery();
if (stockChangeDetail != null)
{
stockChangeDetail.augmentQueryBuilder(builder);
}
}
private static void addSimulatedConstraints(@NonNull final CandidatesQuery query, @NonNull final IQueryBuilder<I_MD_Candidate> builder)
{
switch (query.getSimulatedQueryQualifier())
{ | case ONLY_SIMULATED:
builder.addEqualsFilter(I_MD_Candidate.COLUMNNAME_MD_Candidate_Status, X_MD_Candidate.MD_CANDIDATE_STATUS_Simulated);
break;
case EXCLUDE_SIMULATED:
builder.addNotEqualsFilter(I_MD_Candidate.COLUMNNAME_MD_Candidate_Status, X_MD_Candidate.MD_CANDIDATE_STATUS_Simulated);
break;
case INCLUDE_SIMULATED:
break;
default:
throw new AdempiereException("Unknown SimulatedQueryQualifier!")
.appendParametersToMessage()
.setParameter("SimulatedQueryQualifier", query.getSimulatedQueryQualifier());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\repohelpers\RepositoryCommons.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected JmsProperties getJmsProperties() {
Assert.state(this.jmsProperties != null, "'jmsProperties' must not be null");
return this.jmsProperties;
}
/**
* Configure the specified jms listener container factory. The factory can be further
* tuned and default settings can be overridden.
* @param factory the {@link AbstractJmsListenerContainerFactory} instance to
* configure
* @param connectionFactory the {@link ConnectionFactory} to use
*/
public void configure(T factory, ConnectionFactory connectionFactory) {
Assert.notNull(factory, "'factory' must not be null");
Assert.notNull(connectionFactory, "'connectionFactory' must not be null");
JmsProperties properties = getJmsProperties(); | JmsProperties.Listener listenerProperties = properties.getListener();
Session sessionProperties = listenerProperties.getSession();
factory.setConnectionFactory(connectionFactory);
PropertyMapper map = PropertyMapper.get();
map.from(properties::isPubSubDomain).to(factory::setPubSubDomain);
map.from(properties::isSubscriptionDurable).to(factory::setSubscriptionDurable);
map.from(properties::getClientId).to(factory::setClientId);
map.from(this.destinationResolver).to(factory::setDestinationResolver);
map.from(this.messageConverter).to(factory::setMessageConverter);
map.from(this.exceptionListener).to(factory::setExceptionListener);
map.from(sessionProperties.getAcknowledgeMode()::getMode).to(factory::setSessionAcknowledgeMode);
map.from(this.observationRegistry).to(factory::setObservationRegistry);
map.from(sessionProperties::getTransacted).to(factory::setSessionTransacted);
map.from(listenerProperties::isAutoStartup).to(factory::setAutoStartup);
}
} | repos\spring-boot-main\module\spring-boot-jms\src\main\java\org\springframework\boot\jms\autoconfigure\AbstractJmsListenerContainerFactoryConfigurer.java | 2 |
请完成以下Java代码 | public static DDOrderMoveScheduleId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new DDOrderMoveScheduleId(repoId) : null;
}
public static DDOrderMoveScheduleId ofJson(@NonNull final String string)
{
try
{
return ofRepoId(Integer.parseInt(string));
}
catch (Exception ex)
{
throw new AdempiereException("Invalid id: " + string);
} | }
private DDOrderMoveScheduleId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "DD_Order_MoveSchedule_ID");
}
@JsonValue
public int toJson() {return getRepoId();}
public static boolean equals(@Nullable final DDOrderMoveScheduleId id1, @Nullable final DDOrderMoveScheduleId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\DDOrderMoveScheduleId.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.