instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码 | public class WorkStation {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "id")
private Long id;
@Column(name = "workstation_number")
private Integer workstationNumber;
@Column(name = "floor")
private String floor;
@OneToOne(mappedBy = "workStation")
private Employee employee;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
} | public Integer getWorkstationNumber() {
return workstationNumber;
}
public void setWorkstationNumber(Integer workstationNumber) {
this.workstationNumber = workstationNumber;
}
public String getFloor() {
return floor;
}
public void setFloor(String floor) {
this.floor = floor;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
} | repos\tutorials-master\persistence-modules\hibernate-jpa\src\main\java\com\baeldung\hibernate\onetoone\jointablebased\WorkStation.java | 2 |
请完成以下Java代码 | public Builder region(String region) {
this.region = region;
return this;
}
/**
* Sets the zip code or postal code.
* @param postalCode the zip code or postal code
* @return the {@link Builder}
*/
public Builder postalCode(String postalCode) {
this.postalCode = postalCode;
return this;
}
/**
* Sets the country.
* @param country the country
* @return the {@link Builder}
*/
public Builder country(String country) {
this.country = country;
return this;
} | /**
* Builds a new {@link DefaultAddressStandardClaim}.
* @return a {@link AddressStandardClaim}
*/
public AddressStandardClaim build() {
DefaultAddressStandardClaim address = new DefaultAddressStandardClaim();
address.formatted = this.formatted;
address.streetAddress = this.streetAddress;
address.locality = this.locality;
address.region = this.region;
address.postalCode = this.postalCode;
address.country = this.country;
return address;
}
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\DefaultAddressStandardClaim.java | 1 |
请完成以下Java代码 | public class CredentialPropertiesOutput
implements AuthenticationExtensionsClientOutput<CredentialPropertiesOutput.ExtensionOutput> {
@Serial
private static final long serialVersionUID = -3201699313968303331L;
/**
* The extension id.
*/
public static final String EXTENSION_ID = "credProps";
private final ExtensionOutput output;
/**
* Creates a new instance.
* @param rk is the resident key is discoverable
*/
public CredentialPropertiesOutput(boolean rk) {
this.output = new ExtensionOutput(rk);
}
@Override
public String getExtensionId() {
return EXTENSION_ID;
}
@Override
public ExtensionOutput getOutput() {
return this.output;
} | /**
* The output for {@link CredentialPropertiesOutput}
*
* @author Rob Winch
* @since 6.4
* @see #getOutput()
*/
public static final class ExtensionOutput implements Serializable {
@Serial
private static final long serialVersionUID = 4557406414847424019L;
private final boolean rk;
private ExtensionOutput(boolean rk) {
this.rk = rk;
}
/**
* This OPTIONAL property, known abstractly as the resident key credential
* property (i.e., client-side discoverable credential property), is a Boolean
* value indicating whether the PublicKeyCredential returned as a result of a
* registration ceremony is a client-side discoverable credential.
* @return is resident key credential property
*/
public boolean isRk() {
return this.rk;
}
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\api\CredentialPropertiesOutput.java | 1 |
请完成以下Java代码 | public class BalanceType5Choice {
@XmlElement(name = "Cd")
@XmlSchemaType(name = "string")
protected BalanceType12Code cd;
@XmlElement(name = "Prtry")
protected String prtry;
/**
* Gets the value of the cd property.
*
* @return
* possible object is
* {@link BalanceType12Code }
*
*/
public BalanceType12Code getCd() {
return cd;
}
/**
* Sets the value of the cd property.
*
* @param value
* allowed object is
* {@link BalanceType12Code }
*
*/
public void setCd(BalanceType12Code value) {
this.cd = value;
} | /**
* Gets the value of the prtry property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPrtry() {
return prtry;
}
/**
* Sets the value of the prtry property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPrtry(String value) {
this.prtry = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BalanceType5Choice.java | 1 |
请在Spring Boot框架中完成以下Java代码 | void addDefaultEmptyGroupIfPossible()
{
if (product.isAny())
{
return;
}
final AttributesKey defaultAttributesKey = this.storageAttributesKeyMatcher.toAttributeKeys().orElse(null);
if (defaultAttributesKey == null)
{
return;
}
final AvailableToPromiseResultGroupBuilder group = AvailableToPromiseResultGroupBuilder.builder()
.bpartner(bpartner)
.warehouse(warehouse)
.productId(ProductId.ofRepoId(product.getProductId()))
.storageAttributesKey(defaultAttributesKey)
.build();
groups.add(group); | }
@VisibleForTesting
boolean isZeroQty()
{
if (groups.isEmpty())
{
return true;
}
for (AvailableToPromiseResultGroupBuilder group : groups)
{
if (!group.isZeroQty())
{
return false;
}
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseResultBucket.java | 2 |
请完成以下Java代码 | public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
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;
} | public Date getRegTime() {
return regTime;
}
public void setRegTime(Date regTime) {
this.regTime = regTime;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
", age=" + age +
", regTime=" + regTime +
'}';
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 3-8 课:Spring Data Jpa 和 Thymeleaf 综合实践\spring-boot-Jpa-thymeleaf\src\main\java\com\neo\model\User.java | 1 |
请完成以下Java代码 | public class Ant {
protected int trailSize;
protected int trail[];
protected boolean visited[];
public Ant(int tourSize) {
this.trailSize = tourSize;
this.trail = new int[tourSize];
this.visited = new boolean[tourSize];
}
protected void visitCity(int currentIndex, int city) {
trail[currentIndex + 1] = city;
visited[city] = true;
} | protected boolean visited(int i) {
return visited[i];
}
protected double trailLength(double graph[][]) {
double length = graph[trail[trailSize - 1]][trail[0]];
for (int i = 0; i < trailSize - 1; i++) {
length += graph[trail[i]][trail[i + 1]];
}
return length;
}
protected void clear() {
for (int i = 0; i < trailSize; i++)
visited[i] = false;
}
} | repos\tutorials-master\algorithms-modules\algorithms-genetic\src\main\java\com\baeldung\algorithms\ga\ant_colony\Ant.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Sentinel getSentinel() {
DataRedisProperties.Sentinel sentinel = this.properties.getSentinel();
return (sentinel != null) ? new PropertiesSentinel(getStandalone().getDatabase(), sentinel) : null;
}
@Override
public @Nullable Cluster getCluster() {
DataRedisProperties.Cluster cluster = this.properties.getCluster();
return (cluster != null) ? new PropertiesCluster(cluster) : null;
}
@Override
public @Nullable MasterReplica getMasterReplica() {
DataRedisProperties.Masterreplica masterreplica = this.properties.getMasterreplica();
return (masterreplica != null) ? new PropertiesMasterReplica(masterreplica) : null;
}
private @Nullable DataRedisUrl getRedisUrl() {
return DataRedisUrl.of(this.properties.getUrl());
}
private List<Node> asNodes(@Nullable List<String> nodes) {
if (nodes == null) {
return Collections.emptyList();
}
return nodes.stream().map(this::asNode).toList();
}
private Node asNode(String node) {
int portSeparatorIndex = node.lastIndexOf(':');
String host = node.substring(0, portSeparatorIndex);
int port = Integer.parseInt(node.substring(portSeparatorIndex + 1));
return new Node(host, port);
}
/**
* {@link Cluster} implementation backed by properties.
*/
private class PropertiesCluster implements Cluster {
private final List<Node> nodes;
PropertiesCluster(DataRedisProperties.Cluster properties) {
this.nodes = asNodes(properties.getNodes());
}
@Override
public List<Node> getNodes() {
return this.nodes;
}
}
/**
* {@link MasterReplica} implementation backed by properties.
*/
private class PropertiesMasterReplica implements MasterReplica {
private final List<Node> nodes;
PropertiesMasterReplica(DataRedisProperties.Masterreplica properties) {
this.nodes = asNodes(properties.getNodes());
}
@Override
public List<Node> getNodes() {
return this.nodes;
}
}
/**
* {@link Sentinel} implementation backed by properties.
*/ | private class PropertiesSentinel implements Sentinel {
private final int database;
private final DataRedisProperties.Sentinel properties;
PropertiesSentinel(int database, DataRedisProperties.Sentinel properties) {
this.database = database;
this.properties = properties;
}
@Override
public int getDatabase() {
return this.database;
}
@Override
public String getMaster() {
String master = this.properties.getMaster();
Assert.state(master != null, "'master' must not be null");
return master;
}
@Override
public List<Node> getNodes() {
return asNodes(this.properties.getNodes());
}
@Override
public @Nullable String getUsername() {
return this.properties.getUsername();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\PropertiesDataRedisConnectionDetails.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private void processJsonAttachmentRequest(@NonNull final Exchange exchange)
{
final ExportPPOrderRouteContext context = ProcessorHelper.getPropertyOrThrowError(exchange, ROUTE_PROPERTY_EXPORT_PP_ORDER_CONTEXT, ExportPPOrderRouteContext.class);
final JsonExternalSystemRequest request = context.getJsonExternalSystemRequest();
final JsonMetasfreshId adPInstanceId = request.getAdPInstanceId();
Check.assumeNotNull(adPInstanceId, "adPInstanceId cannot be null at this stage!");
final String fileContent = context.getUpdatedPLUFileContent();
final byte[] fileData = fileContent.getBytes();
final String base64FileData = Base64.getEncoder().encodeToString(fileData);
final JsonAttachment attachment = JsonAttachment.builder()
.fileName(context.getPLUTemplateFilename())
.data(base64FileData)
.type(JsonAttachmentSourceType.Data)
.build(); | final JsonTableRecordReference jsonTableRecordReference = JsonTableRecordReference.builder()
.tableName(LeichMehlConstants.AD_PINSTANCE_TABLE_NAME)
.recordId(adPInstanceId)
.build();
final JsonAttachmentRequest jsonAttachmentRequest = JsonAttachmentRequest.builder()
.attachment(attachment)
.orgCode(request.getOrgCode())
.reference(jsonTableRecordReference)
.build();
exchange.getIn().setBody(jsonAttachmentRequest);
}
private void addXMLDeclarationIfNeeded(@NonNull final Exchange exchange) {
final DispatchMessageRequest request = exchange.getIn().getBody(DispatchMessageRequest.class);
final DispatchMessageRequest modifiedRequest = request.withPayload(XMLUtil.addXMLDeclarationIfNeeded(request.getPayload()));
exchange.getIn().setBody(modifiedRequest);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-leichundmehl\src\main\java\de\metas\camel\externalsystems\leichundmehl\to_leichundmehl\pporder\LeichUndMehlExportPPOrderRouteBuilder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class OrderCreateRequestPackageItem
{
@JsonProperty("id")
OrderCreateRequestPackageItemId id;
@JsonProperty("pzn")
PZN pzn;
@JsonProperty("qty")
Quantity qty;
@JsonProperty("deliverySpecifications")
DeliverySpecifications deliverySpecifications;
@JsonProperty("purchaseCandidateId")
@JsonInclude(JsonInclude.Include.NON_NULL)
MSV3PurchaseCandidateId purchaseCandidateId; | @Builder
@JsonCreator
private OrderCreateRequestPackageItem(
@JsonProperty("id") final OrderCreateRequestPackageItemId id,
@JsonProperty("pzn") @NonNull final PZN pzn,
@JsonProperty("qty") @NonNull final Quantity qty,
@JsonProperty("deliverySpecifications") @NonNull final DeliverySpecifications deliverySpecifications,
@JsonProperty("purchaseCandidateId") MSV3PurchaseCandidateId purchaseCandidateId)
{
this.id = id != null ? id : OrderCreateRequestPackageItemId.random();
this.pzn = pzn;
this.qty = qty;
this.deliverySpecifications = deliverySpecifications;
this.purchaseCandidateId = purchaseCandidateId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\order\OrderCreateRequestPackageItem.java | 2 |
请完成以下Java代码 | public class ResourceStreamSource implements StreamSource {
String resource;
ClassLoader classLoader;
public ResourceStreamSource(String resource) {
this.resource = resource;
}
public ResourceStreamSource(String resource, ClassLoader classLoader) {
this.resource = resource;
this.classLoader = classLoader;
}
public InputStream getInputStream() {
InputStream inputStream = null; | if (classLoader == null) {
inputStream = ReflectUtil.getResourceAsStream(resource);
} else {
inputStream = classLoader.getResourceAsStream(resource);
}
if (inputStream == null) {
throw new ActivitiIllegalArgumentException("resource '" + resource + "' doesn't exist");
}
return new BufferedInputStream(inputStream);
}
public String toString() {
return "Resource[" + resource + "]";
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\io\ResourceStreamSource.java | 1 |
请完成以下Java代码 | public class Book {
Long id;
String name;
Long authorId;
public Book() {
}
public Book(Long id, String name, Long authorId) {
this.id = id;
this.name = name;
this.authorId = authorId;
}
public Long getId() { | return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
} | repos\spring-graphql-main\spring-graphql-docs\src\main\java\org\springframework\graphql\docs\graalvm\server\Book.java | 1 |
请完成以下Java代码 | public List<HistoricIdentityLinkEntity> findHistoricIdentityLinks() {
return getDbSqlSession().selectList("selectHistoricIdentityLinks");
}
@SuppressWarnings("unchecked")
public List<HistoricIdentityLinkEntity> findHistoricIdentityLinkByTaskUserGroupAndType(String taskId, String userId, String groupId, String type) {
Map<String, String> parameters = new HashMap<>();
parameters.put("taskId", taskId);
parameters.put("userId", userId);
parameters.put("groupId", groupId);
parameters.put("type", type);
return getDbSqlSession().selectList("selectHistoricIdentityLinkByTaskUserGroupAndType", parameters);
}
@SuppressWarnings("unchecked")
public List<HistoricIdentityLinkEntity> findHistoricIdentityLinkByProcessDefinitionUserAndGroup(String processDefinitionId, String userId, String groupId) {
Map<String, String> parameters = new HashMap<>();
parameters.put("processDefinitionId", processDefinitionId);
parameters.put("userId", userId);
parameters.put("groupId", groupId);
return getDbSqlSession().selectList("selectHistoricIdentityLinkByProcessDefinitionUserAndGroup", parameters);
}
public void deleteHistoricIdentityLinksByTaskId(String taskId) {
List<HistoricIdentityLinkEntity> identityLinks = findHistoricIdentityLinksByTaskId(taskId);
for (HistoricIdentityLinkEntity identityLink : identityLinks) {
deleteHistoricIdentityLink(identityLink);
}
}
public void deleteHistoricIdentityLinksByProcInstance(String processInstanceId) {
// Identity links from db
List<HistoricIdentityLinkEntity> identityLinks = findHistoricIdentityLinksByProcessInstanceId(processInstanceId);
// Delete | for (HistoricIdentityLinkEntity identityLink : identityLinks) {
deleteHistoricIdentityLink(identityLink);
}
// Identity links from cache
List<HistoricIdentityLinkEntity> identityLinksFromCache = Context.getCommandContext().getDbSqlSession().findInCache(HistoricIdentityLinkEntity.class);
for (HistoricIdentityLinkEntity identityLinkEntity : identityLinksFromCache) {
if (processInstanceId.equals(identityLinkEntity.getProcessInstanceId())) {
deleteHistoricIdentityLink(identityLinkEntity);
}
}
}
public void deleteHistoricIdentityLinksByProcDef(String processDefId) {
getDbSqlSession().delete("deleteHistoricIdentityLinkByProcDef", processDefId);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricIdentityLinkEntityManager.java | 1 |
请完成以下Java代码 | public Integer getDisabled() {
return disabled;
}
/**
* Set the disabled.
*
* @param disabled the disabled
*/
public void setDisabled(Integer disabled) {
this.disabled = disabled;
}
/**
* Get the theme.
*
* @return the theme
*/
public String getTheme() {
return theme;
}
/**
* Set the theme.
*
* @param theme theme
*/ | public void setTheme(String theme) {
this.theme = theme;
}
/**
* Get the checks if is ldap.
*
* @return the checks if is ldap
*/
public Integer getIsLdap()
{
return isLdap;
}
/**
* Set the checks if is ldap.
*
* @param isLdap the checks if is ldap
*/
public void setIsLdap(Integer isLdap)
{
this.isLdap = isLdap;
}
} | repos\springBoot-master\springboot-mybatis\src\main\java\com\us\example\bean\User.java | 1 |
请完成以下Java代码 | public OAuth2Authorization getAuthorization() {
return get(OAuth2Authorization.class);
}
/**
* Returns the {@link OAuth2AuthorizationConsent authorization consent}.
* @return the {@link OAuth2AuthorizationConsent}, or {@code null} if not available
*/
@Nullable
public OAuth2AuthorizationConsent getAuthorizationConsent() {
return get(OAuth2AuthorizationConsent.class);
}
/**
* Returns the requested scopes.
* @return the requested scopes
*/
public Set<String> getRequestedScopes() {
Set<String> requestedScopes = getAuthorization().getAttribute(OAuth2ParameterNames.SCOPE);
return (requestedScopes != null) ? requestedScopes : Collections.emptySet();
}
/**
* Constructs a new {@link Builder} with the provided
* {@link OAuth2DeviceVerificationAuthenticationToken}.
* @param authentication the {@link OAuth2DeviceVerificationAuthenticationToken}
* @return the {@link Builder}
*/
public static Builder with(OAuth2DeviceVerificationAuthenticationToken authentication) {
return new Builder(authentication);
}
/**
* A builder for {@link OAuth2DeviceVerificationAuthenticationContext}.
*/
public static final class Builder extends AbstractBuilder<OAuth2DeviceVerificationAuthenticationContext, Builder> {
private Builder(OAuth2DeviceVerificationAuthenticationToken authentication) {
super(authentication);
}
/**
* Sets the {@link RegisteredClient registered client}.
* @param registeredClient the {@link RegisteredClient}
* @return the {@link Builder} for further configuration
*/
public Builder registeredClient(RegisteredClient registeredClient) {
return put(RegisteredClient.class, registeredClient); | }
/**
* Sets the {@link OAuth2Authorization authorization}.
* @param authorization the {@link OAuth2Authorization}
* @return the {@link Builder} for further configuration
*/
public Builder authorization(OAuth2Authorization authorization) {
return put(OAuth2Authorization.class, authorization);
}
/**
* Sets the {@link OAuth2AuthorizationConsent authorization consent}.
* @param authorizationConsent the {@link OAuth2AuthorizationConsent}
* @return the {@link Builder} for further configuration
*/
public Builder authorizationConsent(OAuth2AuthorizationConsent authorizationConsent) {
return put(OAuth2AuthorizationConsent.class, authorizationConsent);
}
/**
* Builds a new {@link OAuth2DeviceVerificationAuthenticationContext}.
* @return the {@link OAuth2DeviceVerificationAuthenticationContext}
*/
@Override
public OAuth2DeviceVerificationAuthenticationContext build() {
Assert.notNull(get(RegisteredClient.class), "registeredClient cannot be null");
Assert.notNull(get(OAuth2Authorization.class), "authorization cannot be null");
return new OAuth2DeviceVerificationAuthenticationContext(getContext());
}
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceVerificationAuthenticationContext.java | 1 |
请完成以下Java代码 | private boolean productMatches(final ProductId productId)
{
if (this.productId == null)
{
return true;
}
return Objects.equals(this.productId, productId);
}
private boolean productCategoryMatches(final ProductCategoryId productCategoryId)
{
if (this.productCategoryId == null)
{
return true;
}
return Objects.equals(this.productCategoryId, productCategoryId);
}
private boolean productManufacturerMatches(final BPartnerId productManufacturerId)
{
if (this.productManufacturerId == null)
{
return true;
}
if (productManufacturerId == null) | {
return false;
}
return Objects.equals(this.productManufacturerId, productManufacturerId);
}
public boolean attributeMatches(@NonNull final ImmutableAttributeSet attributes)
{
final AttributeValueId breakAttributeValueId = this.attributeValueId;
if (breakAttributeValueId == null)
{
return true;
}
return attributes.hasAttributeValueId(breakAttributeValueId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\PricingConditionsBreakMatchCriteria.java | 1 |
请完成以下Java代码 | public String getCategoryType ()
{
return (String)get_Value(COLUMNNAME_CategoryType);
}
/** 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 GL Category.
@param GL_Category_ID
General Ledger Category
*/
public void setGL_Category_ID (int GL_Category_ID)
{
if (GL_Category_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_Category_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_Category_ID, Integer.valueOf(GL_Category_ID));
}
/** Get GL Category.
@return General Ledger Category
*/
public int getGL_Category_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Category_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Default.
@param IsDefault
Default value
*/
public void setIsDefault (boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault)); | }
/** Get Default.
@return Default value
*/
public boolean isDefault ()
{
Object oo = get_Value(COLUMNNAME_IsDefault);
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);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_Category.java | 1 |
请完成以下Java代码 | public void setTp(BalanceType12 value) {
this.tp = value;
}
/**
* Gets the value of the cdtLine property.
*
* @return
* possible object is
* {@link CreditLine2 }
*
*/
public CreditLine2 getCdtLine() {
return cdtLine;
}
/**
* Sets the value of the cdtLine property.
*
* @param value
* allowed object is
* {@link CreditLine2 }
*
*/
public void setCdtLine(CreditLine2 value) {
this.cdtLine = value;
}
/**
* Gets the value of the amt property.
*
* @return
* possible object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public ActiveOrHistoricCurrencyAndAmount getAmt() {
return amt;
}
/**
* Sets the value of the amt property.
*
* @param value
* allowed object is
* {@link ActiveOrHistoricCurrencyAndAmount }
*
*/
public void setAmt(ActiveOrHistoricCurrencyAndAmount value) {
this.amt = value;
}
/**
* Gets the value of the cdtDbtInd property.
*
* @return
* possible object is
* {@link CreditDebitCode }
*
*/
public CreditDebitCode getCdtDbtInd() {
return cdtDbtInd;
}
/**
* Sets the value of the cdtDbtInd property.
*
* @param value
* allowed object is
* {@link CreditDebitCode }
*
*/
public void setCdtDbtInd(CreditDebitCode value) {
this.cdtDbtInd = value;
}
/**
* Gets the value of the dt property.
*
* @return
* possible object is
* {@link DateAndDateTimeChoice }
*
*/
public DateAndDateTimeChoice getDt() {
return dt;
}
/** | * Sets the value of the dt property.
*
* @param value
* allowed object is
* {@link DateAndDateTimeChoice }
*
*/
public void setDt(DateAndDateTimeChoice value) {
this.dt = value;
}
/**
* Gets the value of the avlbty property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the avlbty property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAvlbty().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link CashBalanceAvailability2 }
*
*
*/
public List<CashBalanceAvailability2> getAvlbty() {
if (avlbty == null) {
avlbty = new ArrayList<CashBalanceAvailability2>();
}
return this.avlbty;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\CashBalance3.java | 1 |
请完成以下Java代码 | public List<String> getSQLModify(final boolean setNullOption)
{
final String sqlDefaultValue = getSQLDefaultValue();
final StringBuilder sqlBase_ModifyColumn = new StringBuilder("ALTER TABLE ")
.append(tableName)
.append(" MODIFY ").append(columnName);
final List<String> sqlStatements = new ArrayList<>();
//
// Modify data type and DEFAULT value
{
final StringBuilder sqlDefault = new StringBuilder(sqlBase_ModifyColumn);
// Datatype
sqlDefault.append(" ").append(getSQLDataType());
// Default
if (sqlDefaultValue != null)
{
sqlDefault.append(" DEFAULT ").append(sqlDefaultValue);
}
else
{
// avoid the explicit DEFAULT NULL, because apparently it causes an extra cost
// if (!mandatory)
// sqlDefault.append(" DEFAULT NULL ");
}
sqlStatements.add(DB.convertSqlToNative(sqlDefault.toString()));
}
//
// Update NULL values
if (mandatory && sqlDefaultValue != null && !sqlDefaultValue.isEmpty())
{
final String sqlSet = "UPDATE " + tableName + " SET " + columnName + "=" + sqlDefaultValue + " WHERE " + columnName + " IS NULL";
sqlStatements.add(sqlSet);
}
//
// Set NULL/NOT NULL constraint
if (setNullOption)
{
final StringBuilder sqlNull = new StringBuilder(sqlBase_ModifyColumn);
if (mandatory)
sqlNull.append(" NOT NULL");
else
sqlNull.append(" NULL");
sqlStatements.add(DB.convertSqlToNative(sqlNull.toString()));
}
//
return sqlStatements;
}
/** | * Get SQL Data Type
*
* @return e.g. NVARCHAR2(60)
*/
private String getSQLDataType()
{
final String columnName = getColumnName();
final ReferenceId displayType = getReferenceId();
final int fieldLength = getFieldLength();
return DB.getSQLDataType(displayType.getRepoId(), columnName, fieldLength);
}
private String getSQLDefaultValue()
{
final int displayType = referenceId.getRepoId();
if (defaultValue != null
&& !defaultValue.isEmpty()
&& defaultValue.indexOf('@') == -1 // no variables
&& (!(DisplayType.isID(displayType) && defaultValue.equals("-1")))) // not for ID's with default -1
{
if (DisplayType.isText(displayType)
|| displayType == DisplayType.List
|| displayType == DisplayType.YesNo
// Two special columns: Defined as Table but DB Type is String
|| columnName.equals("EntityType") || columnName.equals("AD_Language")
|| (displayType == DisplayType.Button && !(columnName.endsWith("_ID"))))
{
if (!defaultValue.startsWith(DB.QUOTE_STRING) && !defaultValue.endsWith(DB.QUOTE_STRING))
{
return DB.TO_STRING(defaultValue);
}
else
{
return defaultValue;
}
}
else
{
return defaultValue;
}
}
else
{
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\ddl\ColumnDDL.java | 1 |
请完成以下Java代码 | void doPutIfAbsent(K key, V value) {
cache.putIfAbsent(key, value);
}
void doEvict(K key) {
cache.evict(key);
}
TbCacheTransaction<K, V> newTransaction(List<K> keys) {
lock.lock();
try {
var transaction = new CaffeineTbCacheTransaction<>(this, keys);
var transactionId = transaction.getId();
for (K key : keys) {
objectTransactions.computeIfAbsent(key, k -> new HashSet<>()).add(transactionId);
}
transactions.put(transactionId, transaction);
return transaction;
} finally {
lock.unlock();
}
}
public boolean commit(UUID trId, Map<K, V> pendingPuts) {
lock.lock();
try {
var tr = transactions.get(trId);
var success = !tr.isFailed();
if (success) {
for (K key : tr.getKeys()) {
Set<UUID> otherTransactions = objectTransactions.get(key);
if (otherTransactions != null) {
for (UUID otherTrId : otherTransactions) {
if (trId == null || !trId.equals(otherTrId)) {
transactions.get(otherTrId).setFailed(true);
}
}
}
}
pendingPuts.forEach(this::doPutIfAbsent);
}
removeTransaction(trId);
return success;
} finally {
lock.unlock();
}
}
void rollback(UUID id) {
lock.lock();
try {
removeTransaction(id);
} finally {
lock.unlock();
}
} | private void removeTransaction(UUID id) {
CaffeineTbCacheTransaction<K, V> transaction = transactions.remove(id);
if (transaction != null) {
for (var key : transaction.getKeys()) {
Set<UUID> transactions = objectTransactions.get(key);
if (transactions != null) {
transactions.remove(id);
if (transactions.isEmpty()) {
objectTransactions.remove(key);
}
}
}
}
}
protected void failAllTransactionsByKey(K key) {
Set<UUID> transactionsIds = objectTransactions.get(key);
if (transactionsIds != null) {
for (UUID otherTrId : transactionsIds) {
transactions.get(otherTrId).setFailed(true);
}
}
}
} | repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\CaffeineTbTransactionalCache.java | 1 |
请完成以下Java代码 | public void flush() {
releaseBatches();
}
private void releaseBatches() {
this.lock.lock();
try {
for (MessageBatch batch : this.batchingStrategy.releaseBatches()) {
super.send(batch.exchange(), batch.routingKey(), batch.message(), null);
}
}
finally {
this.lock.unlock();
}
} | @Override
public void doStart() {
}
@Override
public void doStop() {
flush();
}
@Override
public boolean isRunning() {
return true;
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\core\BatchingRabbitTemplate.java | 1 |
请完成以下Java代码 | public boolean isStatus_Print_Job_Instructions()
{
return get_ValueAsBoolean(COLUMNNAME_Status_Print_Job_Instructions);
}
@Override
public void setTrayNumber (int TrayNumber)
{
set_ValueNoCheck (COLUMNNAME_TrayNumber, Integer.valueOf(TrayNumber));
}
@Override
public int getTrayNumber()
{
return get_ValueAsInt(COLUMNNAME_TrayNumber);
}
@Override
public void setUpdatedby_Print_Job_Instructions (int Updatedby_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Updatedby_Print_Job_Instructions, Integer.valueOf(Updatedby_Print_Job_Instructions));
} | @Override
public int getUpdatedby_Print_Job_Instructions()
{
return get_ValueAsInt(COLUMNNAME_Updatedby_Print_Job_Instructions);
}
@Override
public void setUpdated_Print_Job_Instructions (java.sql.Timestamp Updated_Print_Job_Instructions)
{
set_ValueNoCheck (COLUMNNAME_Updated_Print_Job_Instructions, Updated_Print_Job_Instructions);
}
@Override
public java.sql.Timestamp getUpdated_Print_Job_Instructions()
{
return get_ValueAsTimestamp(COLUMNNAME_Updated_Print_Job_Instructions);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_C_Printing_Queue_PrintInfo_v.java | 1 |
请完成以下Java代码 | private static final class ProcessParametersCallout
{
private static void forwardValueToCurrentProcessInstance(final ICalloutField calloutField)
{
final JavaProcess processInstance = JavaProcess.currentInstance();
final String parameterName = calloutField.getColumnName();
final IRangeAwareParams source = createSource(calloutField);
// Ask the instance to load the parameter
processInstance.loadParameterValueNoFail(parameterName, source);
}
private static IRangeAwareParams createSource(final ICalloutField calloutField)
{
final String parameterName = calloutField.getColumnName();
final Object fieldValue = calloutField.getValue();
if (fieldValue instanceof LookupValue)
{
final Object idObj = ((LookupValue)fieldValue).getId();
return ProcessParams.ofValueObject(parameterName, idObj);
}
else if (fieldValue instanceof DateRangeValue)
{
final DateRangeValue dateRange = (DateRangeValue)fieldValue;
return ProcessParams.of(
parameterName,
TimeUtil.asDate(dateRange.getFrom()), | TimeUtil.asDate(dateRange.getTo()));
}
else
{
return ProcessParams.ofValueObject(parameterName, fieldValue);
}
}
}
private static final class ProcessParametersDataBindingDescriptorBuilder implements DocumentEntityDataBindingDescriptorBuilder
{
public static final ProcessParametersDataBindingDescriptorBuilder instance = new ProcessParametersDataBindingDescriptorBuilder();
private static final DocumentEntityDataBindingDescriptor dataBinding = () -> ADProcessParametersRepository.instance;
@Override
public DocumentEntityDataBindingDescriptor getOrBuild()
{
return dataBinding;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\adprocess\ADProcessDescriptorsFactory.java | 1 |
请完成以下Java代码 | public boolean supports(Class<?> type) {
return this.validatedType.equals(type) && this.delegate.supports(type);
}
@Override
public void validate(Object target, Errors errors) {
this.delegate.validate(target, errors);
}
static boolean isJsr303Present(ApplicationContext applicationContext) {
ClassLoader classLoader = applicationContext.getClassLoader();
for (String validatorClass : VALIDATOR_CLASSES) {
if (!ClassUtils.isPresent(validatorClass, classLoader)) {
return false;
} | }
return true;
}
private static class Delegate extends LocalValidatorFactoryBean {
Delegate(ApplicationContext applicationContext) {
setApplicationContext(applicationContext);
setMessageInterpolator(new MessageInterpolatorFactory(applicationContext).getObject());
afterPropertiesSet();
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\ConfigurationPropertiesJsr303Validator.java | 1 |
请完成以下Java代码 | public Collection<String> getUrlMappings() {
return this.urlMappings;
}
/**
* Add URL mappings, as defined in the Servlet specification, for the servlet.
* @param urlMappings the mappings to add
* @see #setUrlMappings(Collection)
*/
public void addUrlMappings(String... urlMappings) {
Assert.notNull(urlMappings, "'urlMappings' must not be null");
this.urlMappings.addAll(Arrays.asList(urlMappings));
}
/**
* Sets the {@code loadOnStartup} priority. See
* {@link ServletRegistration.Dynamic#setLoadOnStartup} for details.
* @param loadOnStartup if load on startup is enabled
*/
public void setLoadOnStartup(int loadOnStartup) {
this.loadOnStartup = loadOnStartup;
}
/**
* Set the {@link MultipartConfigElement multi-part configuration}.
* @param multipartConfig the multipart configuration to set or {@code null}
*/
public void setMultipartConfig(@Nullable MultipartConfigElement multipartConfig) {
this.multipartConfig = multipartConfig;
}
/**
* Returns the {@link MultipartConfigElement multi-part configuration} to be applied
* or {@code null}.
* @return the multipart config
*/
public @Nullable MultipartConfigElement getMultipartConfig() {
return this.multipartConfig;
}
@Override
protected String getDescription() {
Assert.state(this.servlet != null, "Unable to return description for null servlet");
return "servlet " + getServletName();
}
@Override
protected ServletRegistration.Dynamic addRegistration(String description, ServletContext servletContext) {
String name = getServletName();
return servletContext.addServlet(name, this.servlet);
}
/** | * Configure registration settings. Subclasses can override this method to perform
* additional configuration if required.
* @param registration the registration
*/
@Override
protected void configure(ServletRegistration.Dynamic registration) {
super.configure(registration);
String[] urlMapping = StringUtils.toStringArray(this.urlMappings);
if (urlMapping.length == 0 && this.alwaysMapUrl) {
urlMapping = DEFAULT_MAPPINGS;
}
if (!ObjectUtils.isEmpty(urlMapping)) {
registration.addMapping(urlMapping);
}
registration.setLoadOnStartup(this.loadOnStartup);
if (this.multipartConfig != null) {
registration.setMultipartConfig(this.multipartConfig);
}
}
/**
* Returns the servlet name that will be registered.
* @return the servlet name
*/
public String getServletName() {
return getOrDeduceName(this.servlet);
}
@Override
public String toString() {
return getServletName() + " urls=" + getUrlMappings();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\ServletRegistrationBean.java | 1 |
请完成以下Java代码 | public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set EMail Address.
@param EMail
Electronic Mail Address
*/
public void setEMail (String EMail)
{
set_Value (COLUMNNAME_EMail, EMail);
}
/** Get EMail Address.
@return Electronic Mail Address
*/
public String getEMail ()
{
return (String)get_Value(COLUMNNAME_EMail);
}
public I_M_PriceList getM_PriceList() throws RuntimeException
{
return (I_M_PriceList)MTable.get(getCtx(), I_M_PriceList.Table_Name)
.getPO(getM_PriceList_ID(), get_TrxName()); }
/** Set Price List.
@param M_PriceList_ID
Unique identifier of a Price List
*/
public void setM_PriceList_ID (int M_PriceList_ID)
{
if (M_PriceList_ID < 1)
set_Value (COLUMNNAME_M_PriceList_ID, null);
else
set_Value (COLUMNNAME_M_PriceList_ID, Integer.valueOf(M_PriceList_ID));
}
/** Get Price List.
@return Unique identifier of a Price List
*/
public int getM_PriceList_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_PriceList_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Session ID.
@param Session_ID Session ID */
public void setSession_ID (int Session_ID)
{
if (Session_ID < 1)
set_Value (COLUMNNAME_Session_ID, null);
else
set_Value (COLUMNNAME_Session_ID, Integer.valueOf(Session_ID));
}
/** Get Session ID.
@return Session ID */
public int getSession_ID () | {
Integer ii = (Integer)get_Value(COLUMNNAME_Session_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(getSession_ID()));
}
/** Set W_Basket_ID.
@param W_Basket_ID
Web Basket
*/
public void setW_Basket_ID (int W_Basket_ID)
{
if (W_Basket_ID < 1)
set_ValueNoCheck (COLUMNNAME_W_Basket_ID, null);
else
set_ValueNoCheck (COLUMNNAME_W_Basket_ID, Integer.valueOf(W_Basket_ID));
}
/** Get W_Basket_ID.
@return Web Basket
*/
public int getW_Basket_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Basket_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Basket.java | 1 |
请完成以下Java代码 | protected BatchQuery createNewQuery(ProcessEngine engine) {
return engine.getManagementService().createBatchQuery();
}
protected void applyFilters(BatchQuery query) {
if (batchId != null) {
query.batchId(batchId);
}
if (type != null) {
query.type(type);
}
if (TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (tenantIds != null && !tenantIds.isEmpty()) {
query.tenantIdIn(tenantIds.toArray(new String[tenantIds.size()]));
}
if (TRUE.equals(suspended)) {
query.suspended();
} | if (FALSE.equals(suspended)) {
query.active();
}
}
protected void applySortBy(BatchQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_BATCH_ID_VALUE)) {
query.orderById();
}
else if (sortBy.equals(SORT_BY_TENANT_ID_VALUE)) {
query.orderByTenantId();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\batch\BatchQueryDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class X_S_IssueLabel extends org.compiere.model.PO implements I_S_IssueLabel, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 1351114609L;
/** Standard Constructor */
public X_S_IssueLabel (final Properties ctx, final int S_IssueLabel_ID, @Nullable final String trxName)
{
super (ctx, S_IssueLabel_ID, trxName);
}
/** Load Constructor */
public X_S_IssueLabel (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
/**
* Label AD_Reference_ID=541140
* Reference name: S_IssueLabel
*/
public static final int LABEL_AD_Reference_ID=541140;
/** TestLabel = TestLabel */
public static final String LABEL_TestLabel = "TestLabel";
@Override
public void setLabel (final java.lang.String Label)
{
set_ValueNoCheck (COLUMNNAME_Label, Label);
}
@Override
public java.lang.String getLabel()
{
return get_ValueAsString(COLUMNNAME_Label);
}
@Override
public de.metas.serviceprovider.model.I_S_Issue getS_Issue()
{
return get_ValueAsPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class);
}
@Override
public void setS_Issue(final de.metas.serviceprovider.model.I_S_Issue S_Issue)
{
set_ValueFromPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Issue);
}
@Override | public void setS_Issue_ID (final int S_Issue_ID)
{
if (S_Issue_ID < 1)
set_Value (COLUMNNAME_S_Issue_ID, null);
else
set_Value (COLUMNNAME_S_Issue_ID, S_Issue_ID);
}
@Override
public int getS_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Issue_ID);
}
@Override
public void setS_IssueLabel_ID (final int S_IssueLabel_ID)
{
if (S_IssueLabel_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_IssueLabel_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_IssueLabel_ID, S_IssueLabel_ID);
}
@Override
public int getS_IssueLabel_ID()
{
return get_ValueAsInt(COLUMNNAME_S_IssueLabel_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_IssueLabel.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class WFEventAuditRepository
{
public void save(@NonNull final WFEventAuditList auditList)
{
auditList.toList().forEach(this::save);
}
public void save(@NonNull final WFEventAudit audit)
{
I_AD_WF_EventAudit record = audit.getId() > 0
? InterfaceWrapperHelper.loadOutOfTrx(audit.getId(), I_AD_WF_EventAudit.class)
: null;
if (record == null)
{
record = InterfaceWrapperHelper.newInstanceOutOfTrx(I_AD_WF_EventAudit.class);
}
record.setEventType(audit.getEventType().getCode());
record.setAD_Org_ID(audit.getOrgId().getRepoId());
record.setAD_WF_Process_ID(audit.getWfProcessId().getRepoId());
record.setAD_WF_Node_ID(WFNodeId.toRepoId(audit.getWfNodeId()));
record.setAD_Table_ID(audit.getDocumentRef().getAD_Table_ID());
record.setRecord_ID(audit.getDocumentRef().getRecord_ID());
record.setAD_WF_Responsible_ID(audit.getWfResponsibleId().getRepoId());
record.setAD_User_ID(UserId.toRepoId(audit.getUserId()));
record.setWFState(audit.getWfState().getCode());
record.setTextMsg(audit.getTextMsg());
record.setElapsedTimeMS(BigDecimal.valueOf(audit.getElapsedTime().toMillis()));
record.setAttributeName(audit.getAttributeName());
record.setOldValue(audit.getAttributeValueOld());
record.setNewValue(audit.getAttributeValueNew());
InterfaceWrapperHelper.save(record);
audit.setId(record.getAD_WF_EventAudit_ID());
audit.setCreated(TimeUtil.asInstant(record.getCreated()));
}
@SuppressWarnings("unused")
private static WFEventAudit toWFEventAudit(@NonNull final I_AD_WF_EventAudit record)
{
return WFEventAudit.builder()
.id(record.getAD_WF_EventAudit_ID()) | .eventType(WFEventAuditType.ofCode(record.getEventType()))
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
//
.wfProcessId(WFProcessId.ofRepoId(record.getAD_WF_Process_ID()))
.wfNodeId(WFNodeId.ofRepoIdOrNull(record.getAD_WF_Node_ID()))
//
.documentRef(TableRecordReference.of(record.getAD_Table_ID(), record.getRecord_ID()))
//
.wfResponsibleId(WFResponsibleId.ofRepoId(record.getAD_WF_Responsible_ID()))
.userId(UserId.ofRepoIdOrNullIfSystem(record.getAD_User_ID()))
//
.wfState(WFState.ofCode(record.getWFState()))
.textMsg(record.getTextMsg())
//
.created(TimeUtil.asInstant(record.getCreated()))
.elapsedTime(Duration.ofMillis(record.getElapsedTimeMS().longValue()))
//
.attributeName(record.getAttributeName())
.attributeValueOld(record.getOldValue())
.attributeValueNew(record.getNewValue())
//
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\service\WFEventAuditRepository.java | 2 |
请完成以下Java代码 | private List<I_C_BPartner> getAllBPartnerRecords()
{
final IQueryBuilder<I_C_BPartner> bPartnerQuery = queryBL.createQueryBuilder(I_C_BPartner.class)
.addOnlyActiveRecordsFilter();
if (orgId > 0)
{
bPartnerQuery.addEqualsFilter(I_C_BPartner.COLUMNNAME_AD_Org_ID, orgId);
}
return bPartnerQuery.create()
.stream()
.collect(ImmutableList.toImmutableList());
} | @NonNull
private List<I_C_BPartner> getSelectedBPartnerRecords()
{
final IQueryBuilder<I_C_BPartner> bPartnerQuery = retrieveSelectedRecordsQueryBuilder(I_C_BPartner.class);
if (orgId > 0)
{
bPartnerQuery.addEqualsFilter(I_C_BPartner.COLUMNNAME_AD_Org_ID, orgId);
}
return bPartnerQuery.create()
.stream()
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\process\InvokeAlbertaForBPartnerIds.java | 1 |
请完成以下Java代码 | public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Freight Category.
@param M_FreightCategory_ID
Category of the Freight
*/
public void setM_FreightCategory_ID (int M_FreightCategory_ID)
{
if (M_FreightCategory_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_FreightCategory_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_FreightCategory_ID, Integer.valueOf(M_FreightCategory_ID));
}
/** Get Freight Category.
@return Category of the Freight
*/
public int getM_FreightCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_FreightCategory_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\compiere\model\X_M_FreightCategory.java | 1 |
请完成以下Java代码 | public HistoricMilestoneInstanceQuery milestoneInstanceCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
return this;
}
@Override
public HistoricMilestoneInstanceQuery milestoneInstanceReachedBefore(Date reachedBefore) {
this.reachedBefore = reachedBefore;
return this;
}
@Override
public HistoricMilestoneInstanceQuery milestoneInstanceReachedAfter(Date reachedAfter) {
this.reachedAfter = reachedAfter;
return this;
}
@Override
public HistoricMilestoneInstanceQuery orderByMilestoneName() {
return orderBy(MilestoneInstanceQueryProperty.MILESTONE_NAME);
}
@Override
public HistoricMilestoneInstanceQuery orderByTimeStamp() {
return orderBy(MilestoneInstanceQueryProperty.MILESTONE_TIMESTAMP);
}
@Override
public HistoricMilestoneInstanceQuery milestoneInstanceTenantId(String tenantId) {
if (tenantId == null) {
throw new FlowableIllegalArgumentException("tenant id is null");
}
this.tenantId = tenantId;
return this;
}
@Override
public HistoricMilestoneInstanceQuery milestoneInstanceTenantIdLike(String tenantIdLike) {
if (tenantIdLike == null) {
throw new FlowableIllegalArgumentException("tenant id is null");
}
this.tenantIdLike = tenantIdLike;
return this;
}
@Override
public HistoricMilestoneInstanceQuery milestoneInstanceWithoutTenantId() {
this.withoutTenantId = true;
return this;
}
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getHistoricMilestoneInstanceEntityManager(commandContext).findHistoricMilestoneInstanceCountByQueryCriteria(this);
}
@Override | public List<HistoricMilestoneInstance> executeList(CommandContext commandContext) {
return CommandContextUtil.getHistoricMilestoneInstanceEntityManager(commandContext).findHistoricMilestoneInstancesByQueryCriteria(this);
}
@Override
public String getId() {
return id;
}
public String getName() {
return name;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public Date getReachedBefore() {
return reachedBefore;
}
public Date getReachedAfter() {
return reachedAfter;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricMilestoneInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public Builder setPaymentRequestAmt(final BigDecimal paymentRequestAmt)
{
Check.assumeNotNull(paymentRequestAmt, "paymentRequestAmt not null");
this.paymentRequestAmtSupplier = Suppliers.ofInstance(paymentRequestAmt);
return this;
}
public Builder setPaymentRequestAmt(final Supplier<BigDecimal> paymentRequestAmtSupplier)
{
this.paymentRequestAmtSupplier = paymentRequestAmtSupplier;
return this;
}
public Builder setMultiplierAP(final BigDecimal multiplierAP)
{
this.multiplierAP = multiplierAP;
return this;
}
public Builder setIsPrepayOrder(final boolean isPrepayOrder) | {
this.isPrepayOrder = isPrepayOrder;
return this;
}
public Builder setPOReference(final String POReference)
{
this.POReference = POReference;
return this;
}
public Builder setCreditMemo(final boolean creditMemo)
{
this.creditMemo = creditMemo;
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\InvoiceRow.java | 1 |
请完成以下Java代码 | public static List<String> splitExternalIds(@Nullable final String externalIds)
{
if (Check.isBlank(externalIds))
{
return ImmutableList.of();
}
return Splitter
.on(EXTERNAL_ID_DELIMITER)
.splitToList(externalIds);
}
public static int extractSingleRecordId(@NonNull final List<String> externalIds)
{
if (externalIds.size() != 1)
{
return -1;
}
final String externalId = CollectionUtils.singleElement(externalIds); | final List<String> externalIdSegments = Splitter
.on("_")
.splitToList(externalId);
if (externalIdSegments.isEmpty())
{
return -1;
}
final String recordIdStr = externalIdSegments.get(externalIdSegments.size() - 1);
try
{
return Integer.parseInt(recordIdStr);
}
catch (NumberFormatException nfe)
{
return -1;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\lang\ExternalIdsUtil.java | 1 |
请完成以下Java代码 | public void setIsError (boolean IsError)
{
set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError));
}
/** Get Fehler.
@return Ein Fehler ist bei der Durchführung aufgetreten
*/
@Override
public boolean isError ()
{
Object oo = get_Value(COLUMNNAME_IsError);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Request Message.
@param RequestMessage Request Message */
@Override
public void setRequestMessage (java.lang.String RequestMessage)
{
set_Value (COLUMNNAME_RequestMessage, RequestMessage);
} | /** Get Request Message.
@return Request Message */
@Override
public java.lang.String getRequestMessage ()
{
return (java.lang.String)get_Value(COLUMNNAME_RequestMessage);
}
/** Set Response Message.
@param ResponseMessage Response Message */
@Override
public void setResponseMessage (java.lang.String ResponseMessage)
{
set_Value (COLUMNNAME_ResponseMessage, ResponseMessage);
}
/** Get Response Message.
@return Response Message */
@Override
public java.lang.String getResponseMessage ()
{
return (java.lang.String)get_Value(COLUMNNAME_ResponseMessage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrder_Log.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setCouchbaseTemplate(CouchbaseTemplate template) {
this.template = template;
}
public Optional<Person> findOne(String id) {
return Optional.of(template.findById(Person.class).one(id));
}
public List<Person> findAll() {
return template.findByQuery(Person.class).all();
}
public List<Person> findByFirstName(String firstName) {
return template.findByQuery(Person.class).matching(where("firstName").is(firstName)).all();
}
public List<Person> findByLastName(String lastName) { | return template.findByQuery(Person.class).matching(where("lastName").is(lastName)).all();
}
public void create(Person person) {
person.setCreated(DateTime.now());
template.insertById(Person.class).one(person);
}
public void update(Person person) {
person.setUpdated(DateTime.now());
template.removeById(Person.class).oneEntity(person);
}
public void delete(Person person) {
template.removeById(Person.class).oneEntity(person);
}
} | repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\service\PersonTemplateService.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class CommissionSettingsLineId implements RepoIdAware
{
int repoId;
public static int toRepoId(@Nullable final CommissionSettingsLineId commissionSettingsLineId)
{
if (commissionSettingsLineId == null)
{
return -1;
}
return commissionSettingsLineId.getRepoId();
}
@JsonCreator
public static CommissionSettingsLineId ofRepoId(final int repoId)
{
return new CommissionSettingsLineId(repoId);
} | public static CommissionSettingsLineId ofRepoIdOrNull(@Nullable final Integer repoId)
{
if (repoId == null || repoId <= 0)
{
return null;
}
return new CommissionSettingsLineId(repoId);
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\CommissionSettingsLineId.java | 2 |
请完成以下Java代码 | public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** 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 Sql ORDER BY.
@param OrderByClause
Fully qualified ORDER BY clause
*/ | public void setOrderByClause (String OrderByClause)
{
set_Value (COLUMNNAME_OrderByClause, OrderByClause);
}
/** Get Sql ORDER BY.
@return Fully qualified ORDER BY clause
*/
public String getOrderByClause ()
{
return (String)get_Value(COLUMNNAME_OrderByClause);
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
public void setWhereClause (String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
public String getWhereClause ()
{
return (String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ReportView.java | 1 |
请完成以下Java代码 | public class C_Flatrate_Term_Create_For_MaterialTracking
extends C_Flatrate_Term_Create
implements IProcessPrecondition
{
private final IProductDAO productsRepo = Services.get(IProductDAO.class);
private int p_flatrateconditionsID;
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (I_M_Material_Tracking.Table_Name.equals(context.getTableName()))
{
final I_M_Material_Tracking materialTracking = context.getSelectedModel(I_M_Material_Tracking.class);
// no need to create a new flatrate term if it is already set
if (materialTracking.getC_Flatrate_Term_ID() > 0)
{
return ProcessPreconditionsResolution.reject("contract already set");
}
final List<I_C_Flatrate_Term> existingTerm = Services.get(IMaterialTrackingDAO.class).retrieveC_Flatrate_Terms_For_MaterialTracking(materialTracking);
// the term exists. It just has to be set
if (!existingTerm.isEmpty())
{
return ProcessPreconditionsResolution.reject("contract already exists");
}
// create the flatrate term only if it doesn't exist
return ProcessPreconditionsResolution.accept();
}
return ProcessPreconditionsResolution.reject();
}
@Override
protected void prepare()
{
final IParams para = getParameterAsIParams(); | p_flatrateconditionsID = para.getParameterAsInt(I_C_Flatrate_Term.COLUMNNAME_C_Flatrate_Conditions_ID, -1);
final int materialTrackingID = getRecord_ID();
final I_M_Material_Tracking materialTracking = InterfaceWrapperHelper.create(getCtx(), materialTrackingID, I_M_Material_Tracking.class, getTrxName());
final I_C_Flatrate_Conditions conditions = InterfaceWrapperHelper.create(getCtx(), p_flatrateconditionsID, I_C_Flatrate_Conditions.class, getTrxName());
setConditions(conditions);
addProduct(productsRepo.getById(materialTracking.getM_Product_ID()));
setStartDate(materialTracking.getValidFrom());
setEndDate(materialTracking.getValidTo());
final UserId salesRepId = UserId.ofRepoIdOrNull(materialTracking.getSalesRep_ID());
final I_AD_User salesRep = salesRepId != null
? Services.get(IUserDAO.class).getById(salesRepId)
: null;
setUserInCharge(salesRep);
setIsCompleteDocument(true);
}
@Override
public Iterable<I_C_BPartner> getBPartners()
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final I_M_Material_Tracking materialTracking = getProcessInfo().getRecord(I_M_Material_Tracking.class);
// made this iterator to fit he superclass method
final BPartnerId bpartnerId = BPartnerId.ofRepoId(materialTracking.getC_BPartner_ID());
final Iterator<I_C_BPartner> it = queryBL.createQueryBuilder(I_C_BPartner.class, materialTracking)
.addEqualsFilter(I_C_BPartner.COLUMNNAME_C_BPartner_ID, bpartnerId)
.create()
.iterate(I_C_BPartner.class);
return () -> it;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\process\C_Flatrate_Term_Create_For_MaterialTracking.java | 1 |
请完成以下Java代码 | public void setC_BPartner_ID (int C_BPartner_ID)
{
if (C_BPartner_ID < 1)
set_Value (COLUMNNAME_C_BPartner_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_ID, Integer.valueOf(C_BPartner_ID));
}
/** Get Geschäftspartner.
@return Bezeichnet einen Geschäftspartner
*/
@Override
public int getC_BPartner_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BPartner_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set C_Customer_Retention_ID.
@param C_Customer_Retention_ID C_Customer_Retention_ID */
@Override
public void setC_Customer_Retention_ID (int C_Customer_Retention_ID)
{
if (C_Customer_Retention_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Customer_Retention_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Customer_Retention_ID, Integer.valueOf(C_Customer_Retention_ID));
}
/** Get C_Customer_Retention_ID.
@return C_Customer_Retention_ID */
@Override
public int getC_Customer_Retention_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Customer_Retention_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** | * CustomerRetention AD_Reference_ID=540937
* Reference name: C_BPartner_TimeSpan_List
*/
public static final int CUSTOMERRETENTION_AD_Reference_ID=540937;
/** Neukunde = N */
public static final String CUSTOMERRETENTION_Neukunde = "N";
/** Stammkunde = S */
public static final String CUSTOMERRETENTION_Stammkunde = "S";
/** Set Customer Retention.
@param CustomerRetention Customer Retention */
@Override
public void setCustomerRetention (java.lang.String CustomerRetention)
{
set_Value (COLUMNNAME_CustomerRetention, CustomerRetention);
}
/** Get Customer Retention.
@return Customer Retention */
@Override
public java.lang.String getCustomerRetention ()
{
return (java.lang.String)get_Value(COLUMNNAME_CustomerRetention);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Customer_Retention.java | 1 |
请完成以下Java代码 | public class FormData implements Map<String, Object> {
TaskEntity task;
public FormData(TaskEntity task) {
this.task = task;
}
@Override
public void clear() {
}
@Override
public boolean containsKey(Object key) {
return false;
}
@Override
public boolean containsValue(Object value) {
return false;
}
@Override
public Set<Map.Entry<String, Object>> entrySet() {
return null;
}
@Override
public Object get(Object key) {
return null;
}
@Override
public boolean isEmpty() {
return false;
}
@Override
public Set<String> keySet() {
return null;
}
@Override
public Object put(String key, Object value) {
return null; | }
@Override
public void putAll(Map<? extends String, ? extends Object> m) {
}
@Override
public Object remove(Object key) {
return null;
}
@Override
public int size() {
return 0;
}
@Override
public Collection<Object> values() {
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\form\FormData.java | 1 |
请完成以下Java代码 | class NestedFileStore extends FileStore {
private final NestedFileSystem fileSystem;
NestedFileStore(NestedFileSystem fileSystem) {
this.fileSystem = fileSystem;
}
@Override
public String name() {
return this.fileSystem.toString();
}
@Override
public String type() {
return "nestedfs";
}
@Override
public boolean isReadOnly() {
return this.fileSystem.isReadOnly();
}
@Override
public long getTotalSpace() throws IOException {
return 0;
}
@Override
public long getUsableSpace() throws IOException {
return 0;
}
@Override
public long getUnallocatedSpace() throws IOException {
return 0;
}
@Override
public boolean supportsFileAttributeView(Class<? extends FileAttributeView> type) {
return getJarPathFileStore().supportsFileAttributeView(type);
}
@Override
public boolean supportsFileAttributeView(String name) {
return getJarPathFileStore().supportsFileAttributeView(name);
}
@Override | public <V extends FileStoreAttributeView> V getFileStoreAttributeView(Class<V> type) {
return getJarPathFileStore().getFileStoreAttributeView(type);
}
@Override
public Object getAttribute(String attribute) throws IOException {
try {
return getJarPathFileStore().getAttribute(attribute);
}
catch (UncheckedIOException ex) {
throw ex.getCause();
}
}
protected FileStore getJarPathFileStore() {
try {
return Files.getFileStore(this.fileSystem.getJarPath());
}
catch (IOException ex) {
throw new UncheckedIOException(ex);
}
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\nio\file\NestedFileStore.java | 1 |
请完成以下Java代码 | public static EventPayload headerWithCorrelation(String name, String type) {
EventPayload payload = new EventPayload(name, type);
payload.setHeader(true);
payload.setCorrelationParameter(true);
return payload;
}
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public boolean isCorrelationParameter() {
return correlationParameter;
}
public void setCorrelationParameter(boolean correlationParameter) {
this.correlationParameter = correlationParameter;
}
public static EventPayload correlation(String name, String type) {
EventPayload payload = new EventPayload(name, type);
payload.setCorrelationParameter(true);
return payload;
}
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public boolean isFullPayload() {
return isFullPayload;
}
public void setFullPayload(boolean isFullPayload) {
this.isFullPayload = isFullPayload;
}
public static EventPayload fullPayload(String name) {
EventPayload payload = new EventPayload();
payload.name = name;
payload.setFullPayload(true);
return payload;
}
@JsonInclude(JsonInclude.Include.NON_DEFAULT)
public boolean isMetaParameter() {
return metaParameter;
}
public void setMetaParameter(boolean metaParameter) {
this.metaParameter = metaParameter; | }
@JsonIgnore
public boolean isNotForBody() {
return header || isFullPayload || metaParameter;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
EventPayload that = (EventPayload) o;
return Objects.equals(name, that.name) && Objects.equals(type, that.type) && correlationParameter == that.correlationParameter
&& header == that.header && isFullPayload == that.isFullPayload && metaParameter == that.metaParameter;
}
@Override
public int hashCode() {
return Objects.hash(name, type);
}
} | repos\flowable-engine-main\modules\flowable-event-registry-model\src\main\java\org\flowable\eventregistry\model\EventPayload.java | 1 |
请完成以下Java代码 | public java.lang.String getInternalName()
{
return get_ValueAsString(COLUMNNAME_InternalName);
}
@Override
public void setMobile_Application_Action_ID (final int Mobile_Application_Action_ID)
{
if (Mobile_Application_Action_ID < 1)
set_ValueNoCheck (COLUMNNAME_Mobile_Application_Action_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Mobile_Application_Action_ID, Mobile_Application_Action_ID);
}
@Override
public int getMobile_Application_Action_ID()
{
return get_ValueAsInt(COLUMNNAME_Mobile_Application_Action_ID);
} | @Override
public void setMobile_Application_ID (final int Mobile_Application_ID)
{
if (Mobile_Application_ID < 1)
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Mobile_Application_ID, Mobile_Application_ID);
}
@Override
public int getMobile_Application_ID()
{
return get_ValueAsInt(COLUMNNAME_Mobile_Application_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Mobile_Application_Action.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static boolean canEdit(final Document document, final IUserRolePermissions permissions)
{
final BooleanWithReason canEdit = checkCanEdit(document, permissions);
return canEdit.isTrue();
}
private static BooleanWithReason checkCanEdit(@NonNull final Document document, @NonNull final IUserRolePermissions permissions)
{
// In case document type is not Window, return OK because we cannot validate
final DocumentPath documentPath = document.getDocumentPath();
if (documentPath.getDocumentType() != DocumentType.Window)
{
return BooleanWithReason.TRUE; // OK
}
// Check if we have window write permission
final AdWindowId adWindowId = documentPath.getWindowId().toAdWindowIdOrNull();
if (adWindowId != null && !permissions.checkWindowPermission(adWindowId).hasWriteAccess())
{
return BooleanWithReason.falseBecause("no window edit permission");
}
final int adTableId = getAdTableId(document);
if (adTableId <= 0)
{
return BooleanWithReason.TRUE; // not table based => OK
}
final int recordId = getRecordId(document);
final ClientId adClientId = document.getClientId();
final OrgId adOrgId = document.getOrgId();
if (adOrgId == null)
{
return BooleanWithReason.TRUE; // the user cleared the field; field is flagged as mandatory; until user set the field, don't make a fuss.
}
return permissions.checkCanUpdate(adClientId, adOrgId, adTableId, recordId);
}
private static int getAdTableId(final Document document)
{
final String tableName = document.getEntityDescriptor().getTableNameOrNull(); | if (tableName == null)
{
// cannot apply security because this is not table based
return -1; // OK
}
return Services.get(IADTableDAO.class).retrieveTableId(tableName);
}
private static int getRecordId(final Document document)
{
if (document.isNew())
{
return -1;
}
else
{
return document.getDocumentId().toIntOr(-1);
}
}
public static boolean isNewDocumentAllowed(@NonNull final DocumentEntityDescriptor entityDescriptor, @NonNull final UserSession userSession)
{
final AdWindowId adWindowId = entityDescriptor.getWindowId().toAdWindowIdOrNull();
if (adWindowId == null) {return true;}
final IUserRolePermissions permissions = userSession.getUserRolePermissions();
final ElementPermission windowPermission = permissions.checkWindowPermission(adWindowId);
if (!windowPermission.hasWriteAccess()) {return false;}
final ILogicExpression allowExpr = entityDescriptor.getAllowCreateNewLogic();
final LogicExpressionResult allow = allowExpr.evaluateToResult(userSession.toEvaluatee(), IExpressionEvaluator.OnVariableNotFound.ReturnNoResult);
return allow.isTrue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\controller\DocumentPermissionsHelper.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class LoginController {
@Resource
private TestService testService;
@GetMapping("/getLogin/{username}/{password}")
public String doLoginGet(@PathVariable("username") String username,@PathVariable("password") String password) {
Subject subject = SecurityUtils.getSubject();
try {
subject.login(new UsernamePasswordToken(username, password));
System.out.println("登录成功!");
return "redirect:/getIndex.html";
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("登录失败!");
}
return "redirect:/login";
}
@PostMapping("/doLogin")
public String doLogin(String username, String password) {
Subject subject = SecurityUtils.getSubject();
try {
subject.login(new UsernamePasswordToken(username, password));
System.out.println("登录成功!");
return "redirect:/index";
} catch (AuthenticationException e) {
e.printStackTrace();
System.out.println("登录失败!");
}
return "redirect:/login";
}
@GetMapping("/hello")
@ResponseBody
public String hello() {
return "hello";
}
@GetMapping("/index")
@ResponseBody
public String index() {
String wel = "hello ~ ";
// Subject subject = SecurityUtils.getSubject();
// System.out.println(subject.hasRole("admin")); | // String s = testService.vipPrint();
// wel = wel + s;
return wel;
}
@GetMapping("/login")
@ResponseBody
public String login() {
return "please login!";
}
@GetMapping("/vip")
@ResponseBody
public String vip() {
return "hello vip";
}
@GetMapping("/common")
@ResponseBody
public String common() {
return "hello common";
}
} | repos\spring-boot-quick-master\quick-shiro\src\main\java\com\shiro\quick\controller\LoginController.java | 2 |
请完成以下Java代码 | public boolean isDetached() {
return incident.getExecutionId() == null;
}
public void detachState() {
incident.setExecution(null);
}
public void attachState(MigratingScopeInstance newOwningInstance) {
attachTo(newOwningInstance.resolveRepresentativeExecution());
}
@Override
public void attachState(MigratingTransitionInstance targetTransitionInstance) {
attachTo(targetTransitionInstance.resolveRepresentativeExecution());
}
public void migrateState() {
incident.setActivityId(targetScope.getId());
incident.setProcessDefinitionId(targetScope.getProcessDefinition().getId());
incident.setJobDefinitionId(targetJobDefinitionId);
migrateHistory();
} | protected void migrateHistory() {
HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
if (historyLevel.isHistoryEventProduced(HistoryEventTypes.INCIDENT_MIGRATE, this)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricIncidentMigrateEvt(incident);
}
});
}
}
public void migrateDependentEntities() {
// nothing to do
}
protected void attachTo(ExecutionEntity execution) {
incident.setExecution(execution);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingIncident.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory cf) {
RedisTemplate<String, String> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(cf);
return redisTemplate;
}
@Bean
public CacheManager cacheManager(RedisTemplate<?, ?> redisTemplate) {
RedisCacheManager cacheManager = new RedisCacheManager(redisTemplate);
cacheManager.setDefaultExpiration(600);
return cacheManager;
}
public CacheErrorHandler errorHandler() {
return new CacheErrorHandler(){
@Override
public void handleCacheGetError(RuntimeException exception, Cache cache, Object key) {
logger.warn("handleCacheGetError in redis: {}", exception.getMessage()); | }
@Override
public void handleCachePutError(RuntimeException exception, Cache cache, Object key, Object value) {
logger.warn("handleCachePutError in redis: {}", exception.getMessage());
}
@Override
public void handleCacheEvictError(RuntimeException exception, Cache cache, Object key) {
logger.warn("handleCacheEvictError in redis: {}", exception.getMessage());
}
@Override
public void handleCacheClearError(RuntimeException exception, Cache cache) {
logger.warn("handleCacheClearError in redis: {}", exception.getMessage());
}};
}
} | repos\springBoot-master\springboot-Cache\src\main\java\com\us\example\config\RedisConfig.java | 2 |
请完成以下Java代码 | public static AccountConceptualName ofNullableString(@Nullable final String name)
{
final String nameNorm = StringUtils.trimBlankToNull(name);
return nameNorm != null ? ofString(nameNorm) : null;
}
public static AccountConceptualName ofString(@NonNull final String name)
{
final String nameNorm = StringUtils.trimBlankToNull(name);
if (nameNorm == null)
{
throw new AdempiereException("empty/null account conceptual name is not allowed");
}
return cache.computeIfAbsent(nameNorm, AccountConceptualName::new);
}
@Override
public String toString() {return name;}
public String getAsString() {return name;}
@Override
public int compareTo(@NonNull final AccountConceptualName other)
{
return this.name.compareTo(other.name);
}
public static boolean equals(@Nullable final AccountConceptualName o1, @Nullable final AccountConceptualName o2) {return Objects.equals(o1, o2);}
public boolean isAnyOf(@Nullable final AccountConceptualName... names) | {
if (names == null)
{
return false;
}
for (final AccountConceptualName name : names)
{
if (name != null && equals(this, name))
{
return true;
}
}
return false;
}
public boolean isProductMandatory()
{
return isAnyOf(P_Asset_Acct);
}
public boolean isWarehouseLocatorMandatory()
{
return isAnyOf(P_Asset_Acct);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\AccountConceptualName.java | 1 |
请完成以下Java代码 | public Set<ProductId> getProductIdsMatchingQueryString(
@NonNull final String queryString,
@NonNull final ClientId clientId,
@NonNull final QueryLimit limit)
{
return productsRepo.getProductIdsMatchingQueryString(queryString, clientId, limit);
}
@Override
@NonNull
public List<I_M_Product> getByIds(@NonNull final Set<ProductId> productIds)
{
return productsRepo.getByIds(productIds);
}
@Override
public boolean isExistingValue(@NonNull final String value, @NonNull final ClientId clientId)
{
return productsRepo.isExistingValue(value, clientId);
}
@Override | public void setProductCodeFieldsFromGTIN(@NonNull final I_M_Product record, @Nullable final GTIN gtin)
{
record.setGTIN(gtin != null ? gtin.getAsString() : null);
record.setUPC(gtin != null ? gtin.getAsString() : null);
if (gtin != null)
{
record.setEAN13_ProductCode(null);
}
}
@Override
public void setProductCodeFieldsFromEAN13ProductCode(@NonNull final I_M_Product record, @Nullable final EAN13ProductCode ean13ProductCode)
{
record.setEAN13_ProductCode(ean13ProductCode != null ? ean13ProductCode.getAsString() : null);
if (ean13ProductCode != null)
{
record.setGTIN(null);
record.setUPC(null);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\impl\ProductBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SimulatedDemandCreatedHandler implements MaterialEventHandler<SimulatedDemandCreatedEvent>
{
private final CandidateChangeService candidateChangeHandler;
public SimulatedDemandCreatedHandler(@NonNull final CandidateChangeService candidateChangeHandler)
{
this.candidateChangeHandler = candidateChangeHandler;
}
@Override
public Collection<Class<? extends SimulatedDemandCreatedEvent>> getHandledEventType()
{
return ImmutableList.of(SimulatedDemandCreatedEvent.class);
}
@Override
public void handleEvent(@NonNull final SimulatedDemandCreatedEvent event)
{
final DemandDetail demandDetail = DemandDetail.forDocumentLine(
UNSPECIFIED_REPO_ID, | event.getDocumentLineDescriptor(),
event.getMaterialDescriptor().getQuantity())
.withTraceId(event.getTraceId());
final Candidate.CandidateBuilder candidateBuilder = Candidate
.builderForEventDescriptor(event.getEventDescriptor())
.materialDescriptor(event.getMaterialDescriptor())
.type(CandidateType.DEMAND)
.businessCase(CandidateBusinessCase.SHIPMENT)
.businessCaseDetail(demandDetail)
.simulated(true);
candidateChangeHandler.onCandidateNewOrChange(candidateBuilder.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-service\src\main\java\de\metas\material\dispo\service\event\handler\simulation\SimulatedDemandCreatedHandler.java | 2 |
请完成以下Java代码 | public ProductId getSingleProductId()
{
return getSingleValue(ScheduledPackageable::getProductId).orElseThrow(() -> new AdempiereException("No single product found in " + list));
}
public HUPIItemProductId getSinglePackToHUPIItemProductId()
{
return getSingleValue(ScheduledPackageable::getPackToHUPIItemProductId).orElseThrow(() -> new AdempiereException("No single PackToHUPIItemProductId found in " + list));
}
public Quantity getQtyToPick()
{
return list.stream()
.map(ScheduledPackageable::getQtyToPick)
.reduce(Quantity::add)
.orElseThrow(() -> new AdempiereException("No QtyToPick found in " + list));
}
public Optional<ShipmentScheduleAndJobScheduleId> getSingleScheduleIdIfUnique() | {
final ShipmentScheduleAndJobScheduleIdSet scheduleIds = getScheduleIds();
return scheduleIds.size() == 1 ? Optional.of(scheduleIds.iterator().next()) : Optional.empty();
}
public Optional<UomId> getSingleCatchWeightUomIdIfUnique()
{
final List<UomId> catchWeightUomIds = list.stream()
.map(ScheduledPackageable::getCatchWeightUomId)
// don't filter out null catch UOMs
.distinct()
.collect(Collectors.toList());
return catchWeightUomIds.size() == 1 ? Optional.ofNullable(catchWeightUomIds.get(0)) : Optional.empty();
}
public Optional<PPOrderId> getSingleManufacturingOrderId() {return getSingleValue(ScheduledPackageable::getPickFromOrderId);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\ScheduledPackageableList.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void audit(String settId, String settStatus, String remark){
RpSettRecord settRecord = rpSettRecordDao.getById(settId);
if(!settRecord.getSettStatus().equals(SettRecordStatusEnum.WAIT_CONFIRM.name())){
throw SettBizException.SETT_STATUS_ERROR;
}
settRecord.setSettStatus(settStatus);
settRecord.setEditTime(new Date());
settRecord.setRemark(remark);
rpSettRecordDao.update(settRecord);
if(settStatus.equals(SettRecordStatusEnum.CANCEL.name())){//审核不通过
//解冻金额
rpAccountTransactionService.unFreezeSettAmount(settRecord.getUserNo(), settRecord.getSettAmount());
}
}
/**
* 打款
*/
@Transactional(rollbackFor = Exception.class) | public void remit(String settId, String settStatus, String remark){
RpSettRecord settRecord = rpSettRecordDao.getById(settId);
if(!settRecord.getSettStatus().equals(SettRecordStatusEnum.CONFIRMED.name())){
throw SettBizException.SETT_STATUS_ERROR;
}
settRecord.setSettStatus(settStatus);
settRecord.setEditTime(new Date());
settRecord.setRemitRemark(remark);
settRecord.setRemitAmount(settRecord.getSettAmount());
settRecord.setRemitConfirmTime(new Date());
settRecord.setRemitRequestTime(new Date());
rpSettRecordDao.update(settRecord);
if(settStatus.equals(SettRecordStatusEnum.REMIT_FAIL.name())){//打款失败
//解冻金额
rpAccountTransactionService.unFreezeSettAmount(settRecord.getUserNo(), settRecord.getSettAmount());
}else if(settStatus.equals(SettRecordStatusEnum.REMIT_SUCCESS.name())){
rpAccountTransactionService.unFreezeAmount(settRecord.getUserNo(), settRecord.getSettAmount(), settRecord.getId(), TrxTypeEnum.REMIT.name(), remark);
}
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\service\impl\RpSettHandleServiceImpl.java | 2 |
请完成以下Java代码 | protected CComboBox<Operator> getEditor()
{
if (_editor == null)
{
_editor = new CComboBox<>();
_editor.enableAutoCompletion();
}
return _editor;
}
private void updateEditor(final JTable table, final int viewRowIndex)
{
final CComboBox<Operator> editor = getEditor();
final IUserQueryRestriction row = getRow(table, viewRowIndex);
final FindPanelSearchField searchField = FindPanelSearchField.castToFindPanelSearchField(row.getSearchField());
if (searchField != null)
{
// check if the column is columnSQL with reference (08757)
// final String columnName = searchField.getColumnName();
final int displayType = searchField.getDisplayType();
final boolean isColumnSQL = searchField.isVirtualColumn();
final boolean isReference = searchField.getAD_Reference_Value_ID() != null;
if (isColumnSQL && isReference)
{
// make sure also the columnSQLs with reference are only getting the ID operators (08757)
editor.setModel(modelForLookupColumns);
}
else if (DisplayType.isAnyLookup(displayType))
{
editor.setModel(modelForLookupColumns); | }
else if (DisplayType.YesNo == displayType)
{
editor.setModel(modelForYesNoColumns);
}
else
{
editor.setModel(modelDefault);
}
}
else
{
editor.setModel(modelEmpty);
}
}
private IUserQueryRestriction getRow(final JTable table, final int viewRowIndex)
{
final FindAdvancedSearchTableModel model = (FindAdvancedSearchTableModel)table.getModel();
final int modelRowIndex = table.convertRowIndexToModel(viewRowIndex);
return model.getRow(modelRowIndex);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindOperatorCellEditor.java | 1 |
请完成以下Java代码 | public void setM_FreightCost_includedTab (String M_FreightCost_includedTab)
{
set_ValueNoCheck (COLUMNNAME_M_FreightCost_includedTab, M_FreightCost_includedTab);
}
/** Get M_FreightCost_includedTab.
@return M_FreightCost_includedTab */
public String getM_FreightCost_includedTab ()
{
return (String)get_Value(COLUMNNAME_M_FreightCost_includedTab);
}
public I_M_Product getM_Product() throws RuntimeException
{
return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name)
.getPO(getM_Product_ID(), get_TrxName()); }
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumerische Bezeichnung fuer diesen Eintrag
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name. | @return Alphanumerische Bezeichnung fuer diesen Eintrag
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Suchschluessel.
@param Value
Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschluessel.
@return Suchschluessel fuer den Eintrag im erforderlichen Format - muss eindeutig sein
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\model\X_M_FreightCost.java | 1 |
请完成以下Java代码 | public class ConditionalEventDefinition extends EventDefinition {
protected String conditionExpression;
protected String conditionLanguage;
public String getConditionExpression() {
return conditionExpression;
}
public void setConditionExpression(String conditionExpression) {
this.conditionExpression = conditionExpression;
}
public String getConditionLanguage() {
return conditionLanguage;
}
public void setConditionLanguage(String conditionLanguage) {
this.conditionLanguage = conditionLanguage; | }
@Override
public ConditionalEventDefinition clone() {
ConditionalEventDefinition clone = new ConditionalEventDefinition();
clone.setValues(this);
return clone;
}
public void setValues(ConditionalEventDefinition otherDefinition) {
super.setValues(otherDefinition);
setConditionExpression(otherDefinition.getConditionExpression());
setConditionLanguage(otherDefinition.getConditionLanguage());
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ConditionalEventDefinition.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public IPricingResult calculatePrice(@NonNull final ServiceRepairProjectCostCollector costCollector)
{
final IEditablePricingContext pricingCtx = createPricingContext(costCollector)
.setFailIfNotCalculated();
try
{
return pricingBL.calculatePrice(pricingCtx);
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.setParameter("pricingInfo", pricingInfo)
.setParameter("pricingContext", pricingCtx)
.setParameter("costCollector", costCollector);
}
}
private IEditablePricingContext createPricingContext(
@NonNull final ServiceRepairProjectCostCollector costCollector)
{ | return pricingBL.createPricingContext()
.setFailIfNotCalculated()
.setOrgId(pricingInfo.getOrgId())
.setProductId(costCollector.getProductId())
.setBPartnerId(pricingInfo.getShipBPartnerId())
.setQty(costCollector.getQtyReservedOrConsumed())
.setConvertPriceToContextUOM(true)
.setSOTrx(SOTrx.SALES)
.setPriceDate(pricingInfo.getDatePromised().toLocalDate())
.setPricingSystemId(pricingInfo.getPricingSystemId())
.setPriceListId(pricingInfo.getPriceListId())
.setPriceListVersionId(pricingInfo.getPriceListVersionId())
.setCountryId(pricingInfo.getCountryId())
.setCurrencyId(pricingInfo.getCurrencyId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\service\commands\createQuotationFromProjectCommand\ProjectQuotationPriceCalculator.java | 2 |
请完成以下Java代码 | public final class MSV3Client
{
private final WebServiceTemplate webServiceTemplate;
private final MSV3ClientConfig config;
private final String urlPrefix;
private final FaultInfoExtractor faultInfoExtractor;
@Builder
private MSV3Client(
@NonNull final MSV3ConnectionFactory connectionFactory,
@NonNull final MSV3ClientConfig config,
@NonNull final String urlPrefix,
@NonNull final FaultInfoExtractor faultInfoExtractor)
{
this.config = config;
this.urlPrefix = urlPrefix;
this.faultInfoExtractor = faultInfoExtractor;
webServiceTemplate = connectionFactory.createWebServiceTemplate(config);
}
public ClientSoftwareId getClientSoftwareId()
{
return config.getClientSoftwareId();
}
/**
* @param expectedResponseClass if the response is not an instance of this class, the method throws an exception.
*/
public <T> T sendAndReceive(
@NonNull final JAXBElement<?> messagePayload,
@NonNull final Class<? extends T> expectedResponseClass)
{
final String uri = config.getBaseUrl() + urlPrefix;
final JAXBElement<?> responseElement = (JAXBElement<?>)webServiceTemplate.marshalSendAndReceive(uri, messagePayload);
final Object responseValue = responseElement.getValue();
if (expectedResponseClass.isInstance(responseValue))
{
return expectedResponseClass.cast(responseValue);
}
final FaultInfo faultInfo = faultInfoExtractor.extractFaultInfoOrNull(responseValue);
if (faultInfo != null)
{
throw Msv3ClientException.builder()
.msv3FaultInfo(faultInfo)
.build()
.setParameter("uri", uri)
.setParameter("config", config); | }
else
{
throw new AdempiereException("Webservice returned unexpected response")
.appendParametersToMessage()
.setParameter("uri", uri)
.setParameter("config", config)
.setParameter("response", responseValue);
}
}
@VisibleForTesting
public WebServiceTemplate getWebServiceTemplate()
{
return webServiceTemplate;
}
@FunctionalInterface
public static interface FaultInfoExtractor
{
FaultInfo extractFaultInfoOrNull(Object value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java\de\metas\vertical\pharma\vendor\gateway\msv3\MSV3Client.java | 1 |
请完成以下Java代码 | public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getMobilePhone() {
return mobilePhone;
}
public void setMobilePhone(String mobilePhone) {
this.mobilePhone = mobilePhone;
}
public String getWechatId() {
return wechatId;
}
public void setWechatId(String wechatId) {
this.wechatId = wechatId;
}
public String getSkill() {
return skill;
}
public void setSkill(String skill) {
this.skill = skill;
}
public Integer getDepartmentId() {
return departmentId;
}
public void setDepartmentId(Integer departmentId) {
this.departmentId = departmentId;
}
public Integer getLoginCount() {
return loginCount;
} | public void setLoginCount(Integer loginCount) {
this.loginCount = loginCount;
}
public List<Role> getRoles() {
return roles;
}
public void setRoles(List<Role> roles) {
this.roles = roles;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", cnname=" + cnname +
", username=" + username +
", password=" + password +
", email=" + email +
", telephone=" + telephone +
", mobilePhone=" + mobilePhone +
", wechatId=" + wechatId +
", skill=" + skill +
", departmentId=" + departmentId +
", loginCount=" + loginCount +
'}';
}
} | repos\springBoot-master\springboot-shiro\src\main\java\com\us\bean\User.java | 1 |
请完成以下Java代码 | public Boolean getGenerateUniqueProcessApplicationName() {
return generateUniqueProcessApplicationName;
}
public void setGenerateUniqueProcessApplicationName(Boolean generateUniqueProcessApplicationName) {
this.generateUniqueProcessApplicationName = generateUniqueProcessApplicationName;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("enabled=" + enabled)
.add("processEngineName=" + processEngineName)
.add("generateUniqueProcessEngineName=" + generateUniqueProcessEngineName)
.add("generateUniqueProcessApplicationName=" + generateUniqueProcessApplicationName)
.add("historyLevel=" + historyLevel)
.add("historyLevelDefault=" + historyLevelDefault)
.add("autoDeploymentEnabled=" + autoDeploymentEnabled)
.add("deploymentResourcePattern=" + Arrays.toString(deploymentResourcePattern))
.add("defaultSerializationFormat=" + defaultSerializationFormat)
.add("licenseFile=" + licenseFile) | .add("metrics=" + metrics)
.add("database=" + database)
.add("jobExecution=" + jobExecution)
.add("webapp=" + webapp)
.add("restApi=" + restApi)
.add("authorization=" + authorization)
.add("genericProperties=" + genericProperties)
.add("adminUser=" + adminUser)
.add("filter=" + filter)
.add("idGenerator=" + idGenerator)
.add("jobExecutorAcquireByPriority=" + jobExecutorAcquireByPriority)
.add("defaultNumberOfRetries" + defaultNumberOfRetries)
.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\CamundaBpmProperties.java | 1 |
请完成以下Java代码 | public class SetJobPriorityCmd implements Command<Void> {
public static final String JOB_PRIORITY_PROPERTY = "priority";
protected String jobId;
protected long priority;
public SetJobPriorityCmd(String jobId, long priority) {
this.jobId = jobId;
this.priority = priority;
}
public Void execute(CommandContext commandContext) {
EnsureUtil.ensureNotNull("job id must not be null", "jobId", jobId);
JobEntity job = commandContext.getJobManager().findJobById(jobId);
EnsureUtil.ensureNotNull(NotFoundException.class, "No job found with id '" + jobId + "'", "job", job);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateJob(job);
}
long currentPriority = job.getPriority();
job.setPriority(priority); | createOpLogEntry(commandContext, currentPriority, job);
return null;
}
protected void createOpLogEntry(CommandContext commandContext, long previousPriority, JobEntity job) {
PropertyChange propertyChange = new PropertyChange(JOB_PRIORITY_PROPERTY, previousPriority, job.getPriority());
commandContext
.getOperationLogManager()
.logJobOperation(
UserOperationLogEntry.OPERATION_TYPE_SET_PRIORITY,
job.getId(),
job.getJobDefinitionId(),
job.getProcessInstanceId(),
job.getProcessDefinitionId(),
job.getProcessDefinitionKey(),
propertyChange);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SetJobPriorityCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
// TODO persist clients details
// @formatter:off
clients.inMemory()
.withClient("browser")
.authorizedGrantTypes("refresh_token", "password")
.scopes("ui")
.and()
.withClient("account-service")
.secret(env.getProperty("ACCOUNT_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("statistics-service")
.secret(env.getProperty("STATISTICS_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token")
.scopes("server")
.and()
.withClient("notification-service")
.secret(env.getProperty("NOTIFICATION_SERVICE_PASSWORD"))
.authorizedGrantTypes("client_credentials", "refresh_token") | .scopes("server");
// @formatter:on
}
@Override
public void configure(AuthorizationServerEndpointsConfigurer endpoints) throws Exception {
endpoints
.tokenStore(tokenStore)
.authenticationManager(authenticationManager)
.userDetailsService(userDetailsService);
}
@Override
public void configure(AuthorizationServerSecurityConfigurer oauthServer) throws Exception {
oauthServer
.tokenKeyAccess("permitAll()")
.checkTokenAccess("isAuthenticated()")
.passwordEncoder(NoOpPasswordEncoder.getInstance());
}
} | repos\piggymetrics-master\auth-service\src\main\java\com\piggymetrics\auth\config\OAuth2AuthorizationConfig.java | 2 |
请完成以下Java代码 | public class M_Inventory_CreateLines_RestrictBy_LocatorsAndValue extends DraftInventoryBase
{
private final HuForInventoryLineFactory huForInventoryLineFactory = SpringContextHolder.instance.getBean(HuForInventoryLineFactory.class);
private final IOrgDAO orgDAO = Services.get(IOrgDAO.class);
@Param(parameterName = "MinValueOfGoods")
private BigDecimal minimumPrice;
@Param(parameterName = "MaxNumberOfLocators")
private int maxLocators;
@Param(parameterName = "StockFilterOption")
private String stockFilterOption;
@Override
protected LeastRecentTransactionStrategy createStrategy(@NonNull final Inventory inventory)
{
final ZoneId timeZone = orgDAO.getTimeZone(inventory.getOrgId()); | final LocalDate movementDate = TimeUtil.asLocalDate(inventory.getMovementDate(), timeZone);
final LeastRecentTransactionStrategy.LeastRecentTransactionStrategyBuilder builder = HUsForInventoryStrategies.leastRecentTransaction()
.maxLocators(maxLocators)
.minimumPrice(minimumPrice)
.movementDate(movementDate)
.huForInventoryLineFactory(huForInventoryLineFactory);
switch (ProductStockFilter.of(stockFilterOption))
{
case STOCKED:
builder.onlyStockedProducts(true);
break;
case NON_STOCKED:
builder.onlyStockedProducts(false);
break;
}
return builder.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inventory\draftlinescreator\process\M_Inventory_CreateLines_RestrictBy_LocatorsAndValue.java | 1 |
请完成以下Java代码 | public final class UserGroupsCollection
{
@NonNull
public static UserGroupsCollection of(@Nullable final Collection<UserGroupUserAssignment> assignments)
{
if (Check.isEmpty(assignments))
{
return EMPTY;
}
else
{
return new UserGroupsCollection(assignments);
}
}
private static final UserGroupsCollection EMPTY = new UserGroupsCollection();
private final ImmutableSet<UserGroupUserAssignment> assignments;
private UserGroupsCollection()
{ | assignments = ImmutableSet.of();
}
private UserGroupsCollection(final Collection<UserGroupUserAssignment> assignments)
{
Check.assumeNotEmpty(assignments, "assignments is not empty");
this.assignments = assignments.stream().collect(ImmutableSet.toImmutableSet());
}
@NonNull
public Stream<UserGroupUserAssignment> streamAssignmentsFor(@NonNull final UserGroupId userGroupId, @NonNull final Instant targetDate)
{
return assignments.stream()
.filter(userGroupUserAssignment -> userGroupUserAssignment.getUserGroupId().equals(userGroupId))
.filter(userGroupUserAssignment -> userGroupUserAssignment.getValidDates().contains(targetDate));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\UserGroupsCollection.java | 1 |
请完成以下Java代码 | public BigDecimal calculateQtyLUForTotalQtyTUsByMaxWeight(
@NonNull final I_M_HU_LUTU_Configuration lutuConfiguration,
final BigDecimal qtyTUsTotal,
@NonNull final I_M_HU_PackingMaterial packingMaterial)
{
Check.assumeNotNull(lutuConfiguration, "lutuConfiguration not null");
if (qtyTUsTotal == null || qtyTUsTotal.signum() <= 0)
{
return BigDecimal.ZERO;
}
if (isNoLU(lutuConfiguration))
{
return BigDecimal.ZERO;
}
final BigDecimal qtyTUsPerLU = lutuConfiguration.getQtyTU();
if (qtyTUsPerLU.signum() <= 0)
{
// Qty TU not available => cannot compute
return BigDecimal.ZERO;
} | final BigDecimal qtyCUsPerTU = lutuConfiguration.getQtyCUsPerTU();
if (qtyCUsPerTU.signum() <= 0)
{
// Qty TU not available => cannot compute
return BigDecimal.ZERO;
}
//
// calculate total CUs per LU
final BigDecimal totalQtyCUs = qtyCUsPerTU.multiply(qtyTUsTotal);
//
// CUs are counted by product's UOM
final I_M_Product pp = InterfaceWrapperHelper.load(lutuConfiguration.getM_Product_ID(), I_M_Product.class);
final I_C_UOM productUOM = InterfaceWrapperHelper.load(pp.getC_UOM_ID(), I_C_UOM.class);
final BigDecimal qtyLU = calculateQtyLUForTotalQtyCUsByLUMaxWeight(lutuConfiguration, Quantity.of(totalQtyCUs, productUOM), packingMaterial);
return qtyLU;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\LUTUConfigurationFactory.java | 1 |
请完成以下Java代码 | public boolean isFinished() {
return finished;
}
public boolean isUnfinished() {
return unfinished;
}
public boolean isDeleted() {
return deleted;
}
public boolean isNotDeleted() {
return notDeleted;
}
public boolean isIncludeProcessVariables() {
return includeProcessVariables;
}
public boolean isWithJobException() {
return withJobException;
} | public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public List<HistoricProcessInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\HistoricProcessInstanceQueryImpl.java | 1 |
请完成以下Java代码 | Book newBook(@Valid @RequestBody Book newBook) {
return repository.save(newBook);
}
// Find
@GetMapping("/books/{id}")
Book findOne(@PathVariable @Min(1) Long id) {
return repository.findById(id)
.orElseThrow(() -> new BookNotFoundException(id));
}
// Save or update
@PutMapping("/books/{id}")
Book saveOrUpdate(@RequestBody Book newBook, @PathVariable Long id) {
return repository.findById(id)
.map(x -> {
x.setName(newBook.getName());
x.setAuthor(newBook.getAuthor());
x.setPrice(newBook.getPrice());
return repository.save(x);
})
.orElseGet(() -> {
newBook.setId(id);
return repository.save(newBook);
});
}
// update author only
@PatchMapping("/books/{id}")
Book patch(@RequestBody Map<String, String> update, @PathVariable Long id) {
return repository.findById(id)
.map(x -> {
String author = update.get("author");
if (!StringUtils.isEmpty(author)) {
x.setAuthor(author); | // better create a custom method to update a value = :newValue where id = :id
return repository.save(x);
} else {
throw new BookUnSupportedFieldPatchException(update.keySet());
}
})
.orElseGet(() -> {
throw new BookNotFoundException(id);
});
}
@DeleteMapping("/books/{id}")
void deleteBook(@PathVariable Long id) {
repository.deleteById(id);
}
} | repos\spring-boot-master\spring-rest-error-handling\src\main\java\com\mkyong\BookController.java | 1 |
请完成以下Java代码 | private ILogicExpression compile(final Iterator<String> tokens, final boolean goingDown)
{
LogicExpressionBuilder result = new LogicExpressionBuilder();
while (tokens.hasNext())
{
final String token = tokens.next();
//
// Sub-expression start
if ("(".equals(token))
{
final ILogicExpression child = compile(tokens, false);
result.addChild(child);
}
//
// Operator
else if (AbstractLogicExpression.LOGIC_OPERATORS.contains(token))
{
final String operator = token;
if (result.getRight() == null)
{
result.setOperator(operator);
}
else
{
if (isUseOperatorPrecedence() && AbstractLogicExpression.LOGIC_OPERATOR_AND.equals(operator))
{
// If precedence is enabled, & nodes are sent down the tree, | nodes up.
final ILogicExpression right = LogicExpressionBuilder.build(result.getRight(), operator, compile(tokens, false));
result.setRight(right);
}
else
{
result = result.buildAndCompose(operator, compile(tokens, true));
}
}
}
//
// Sub-expression end
else if (")".equals(token))
{
return result.build();
}
//
// Tuple
else if (isTuple(token))
{
final ILogicExpression tuple = compileTuple(token);
result.addChild(tuple);
if (goingDown)
{
return result.build();
}
}
//
// Error
else
{
throw new ExpressionCompileException("Unexpected token(2): " + token
+ "\n Partial compiled expression: " + result);
}
}
return result.build();
} | private ILogicExpression compileTuple(final String tupleExpressionStr)
{
// Prepare: normalize tuple expression
final String tupleExpressionStrNormalized = tupleExpressionStr
.replace("!=", LogicTuple.OPERATOR_NotEquals) // fix common mistakes: using "!=" instead of "!"
.trim();
final boolean returnDelims = true;
final StringTokenizer tokenizer = new StringTokenizer(tupleExpressionStrNormalized, TUPLE_OPERATORS, returnDelims);
if (tokenizer.countTokens() != 3)
{
throw new ExpressionCompileException("Logic tuple does not comply with format "
+ "'@context@=value' where operand could be one of '" + TUPLE_OPERATORS + "' => " + tupleExpressionStr);
}
return LogicTuple.parseFrom(tokenizer.nextToken(), tokenizer.nextToken(), tokenizer.nextToken());
}
private static boolean isTuple(final String token)
{
for (int i = 0, size = TUPLE_OPERATORS.length(); i < size; i++)
{
final char operator = TUPLE_OPERATORS.charAt(i);
if (token.indexOf(operator) > 0)
{
return true;
}
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\LogicExpressionCompiler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public TaskBuilder dueDate(Date dueDate) {
this.dueDate = dueDate;
return this;
}
@Override
public TaskBuilder category(String category) {
this.category = category;
return this;
}
@Override
public TaskBuilder parentTaskId(String parentTaskId) {
this.parentTaskId = parentTaskId;
return this;
}
@Override
public TaskBuilder tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
@Override
public TaskBuilder formKey(String formKey) {
this.formKey = formKey;
return this;
}
@Override
public TaskBuilder taskDefinitionId(String taskDefinitionId) {
this.taskDefinitionId = taskDefinitionId;
return this;
}
@Override
public TaskBuilder taskDefinitionKey(String taskDefinitionKey) {
this.taskDefinitionKey = taskDefinitionKey;
return this;
}
@Override
public TaskBuilder identityLinks(Set<? extends IdentityLinkInfo> identityLinks) {
this.identityLinks = identityLinks;
return this;
}
@Override
public TaskBuilder scopeId(String scopeId) {
this.scopeId = scopeId;
return this;
}
@Override
public TaskBuilder scopeType(String scopeType) {
this.scopeType = scopeType;
return this;
}
@Override
public String getId() {
return id;
}
@Override
public String getName() {
return name;
}
@Override
public String getDescription() {
return description;
}
@Override
public int getPriority() {
return priority;
} | @Override
public String getOwner() {
return ownerId;
}
@Override
public String getAssignee() {
return assigneeId;
}
@Override
public String getTaskDefinitionId() {
return taskDefinitionId;
}
@Override
public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
@Override
public Date getDueDate() {
return dueDate;
}
@Override
public String getCategory() {
return category;
}
@Override
public String getParentTaskId() {
return parentTaskId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getFormKey() {
return formKey;
}
@Override
public Set<? extends IdentityLinkInfo> getIdentityLinks() {
return identityLinks;
}
@Override
public String getScopeId() {
return this.scopeId;
}
@Override
public String getScopeType() {
return this.scopeType;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseTaskBuilderImpl.java | 2 |
请完成以下Java代码 | public org.compiere.model.I_R_MailText getPayPal_PayerApprovalRequest_MailTemplate()
{
return get_ValueAsPO(COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, org.compiere.model.I_R_MailText.class);
}
@Override
public void setPayPal_PayerApprovalRequest_MailTemplate(final org.compiere.model.I_R_MailText PayPal_PayerApprovalRequest_MailTemplate)
{
set_ValueFromPO(COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, org.compiere.model.I_R_MailText.class, PayPal_PayerApprovalRequest_MailTemplate);
}
@Override
public void setPayPal_PayerApprovalRequest_MailTemplate_ID (final int PayPal_PayerApprovalRequest_MailTemplate_ID)
{
if (PayPal_PayerApprovalRequest_MailTemplate_ID < 1)
set_Value (COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, null);
else
set_Value (COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID, PayPal_PayerApprovalRequest_MailTemplate_ID);
}
@Override
public int getPayPal_PayerApprovalRequest_MailTemplate_ID()
{
return get_ValueAsInt(COLUMNNAME_PayPal_PayerApprovalRequest_MailTemplate_ID);
}
@Override
public void setPayPal_PaymentApprovedCallbackUrl (final @Nullable java.lang.String PayPal_PaymentApprovedCallbackUrl)
{
set_Value (COLUMNNAME_PayPal_PaymentApprovedCallbackUrl, PayPal_PaymentApprovedCallbackUrl);
}
@Override
public java.lang.String getPayPal_PaymentApprovedCallbackUrl()
{
return get_ValueAsString(COLUMNNAME_PayPal_PaymentApprovedCallbackUrl);
}
@Override | public void setPayPal_Sandbox (final boolean PayPal_Sandbox)
{
set_Value (COLUMNNAME_PayPal_Sandbox, PayPal_Sandbox);
}
@Override
public boolean isPayPal_Sandbox()
{
return get_ValueAsBoolean(COLUMNNAME_PayPal_Sandbox);
}
@Override
public void setPayPal_WebUrl (final @Nullable java.lang.String PayPal_WebUrl)
{
set_Value (COLUMNNAME_PayPal_WebUrl, PayPal_WebUrl);
}
@Override
public java.lang.String getPayPal_WebUrl()
{
return get_ValueAsString(COLUMNNAME_PayPal_WebUrl);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java-gen\de\metas\payment\paypal\model\X_PayPal_Config.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ReloadableProperties extends Properties {
private PropertiesConfiguration propertiesConfiguration;
public ReloadableProperties(PropertiesConfiguration propertiesConfiguration) throws IOException {
super.load(new FileReader(propertiesConfiguration.getFile()));
this.propertiesConfiguration = propertiesConfiguration;
}
@Override
public synchronized Object setProperty(String key, String value) {
propertiesConfiguration.setProperty(key, value);
return super.setProperty(key, value);
}
@Override
public String getProperty(String key) {
String val = propertiesConfiguration.getString(key);
super.setProperty(key, val);
return val; | }
@Override
public String getProperty(String key, String defaultValue) {
String val = propertiesConfiguration.getString(key, defaultValue);
super.setProperty(key, val);
return val;
}
@Override
public synchronized void load(Reader reader) throws IOException {
throw new PropertiesException(new OperationNotSupportedException());
}
@Override
public synchronized void load(InputStream inStream) throws IOException {
throw new PropertiesException(new OperationNotSupportedException());
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties-2\src\main\java\com\baeldung\properties\reloading\configs\ReloadableProperties.java | 2 |
请完成以下Java代码 | public static DomDocument getEmptyDocument(DocumentBuilderFactory documentBuilderFactory) {
try {
DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
return new DomDocumentImpl(documentBuilder.newDocument());
} catch (ParserConfigurationException e) {
throw new ModelParseException("Unable to create a new document", e);
}
}
/**
* Create a new DOM document from the input stream
*
* @param documentBuilderFactory the factory to build to DOM document
* @param inputStream the input stream to parse
* @return the new DOM document
* @throws ModelParseException if a parsing or IO error is triggered
*/
public static DomDocument parseInputStream(DocumentBuilderFactory documentBuilderFactory, InputStream inputStream) {
try { | DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
documentBuilder.setErrorHandler(new DomErrorHandler());
return new DomDocumentImpl(documentBuilder.parse(inputStream));
} catch (ParserConfigurationException e) {
throw new ModelParseException("ParserConfigurationException while parsing input stream", e);
} catch (SAXException e) {
throw new ModelParseException("SAXException while parsing input stream", e);
} catch (IOException e) {
throw new ModelParseException("IOException while parsing input stream", e);
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\util\DomUtil.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_M_AttributeSet getM_AttributeSet()
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class);
}
@Override
public void setM_AttributeSet(final org.compiere.model.I_M_AttributeSet M_AttributeSet)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSet_ID, org.compiere.model.I_M_AttributeSet.class, M_AttributeSet);
}
@Override
public void setM_AttributeSet_ID (final int M_AttributeSet_ID)
{
if (M_AttributeSet_ID < 0)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_ID, M_AttributeSet_ID);
}
@Override
public int getM_AttributeSet_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSet_ID);
}
@Override | public void setM_AttributeSet_IncludedTab_ID (final int M_AttributeSet_IncludedTab_ID)
{
if (M_AttributeSet_IncludedTab_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_IncludedTab_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSet_IncludedTab_ID, M_AttributeSet_IncludedTab_ID);
}
@Override
public int getM_AttributeSet_IncludedTab_ID()
{
return get_ValueAsInt(COLUMNNAME_M_AttributeSet_IncludedTab_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_AttributeSet_IncludedTab.java | 1 |
请完成以下Java代码 | public class ExporterFactory implements IExporterFactory
{
private final Map<String, Class<? extends IExporter>> exporterClasses = new HashMap<String, Class<? extends IExporter>>();
public ExporterFactory()
{
// Register defaults
registerExporter(MIMETYPE_CSV, CSVExporter.class);
}
@Override
public IExporter createExporter(final String mimeType, final IExportDataSource dataSource, final Properties config)
{
Check.assumeNotNull(dataSource, "dataSource not null");
final Class<? extends IExporter> exporterClass = exporterClasses.get(mimeType);
if (exporterClass == null)
{
throw new AdempiereException("Exporter class not found for MimeType '" + mimeType + "'");
}
IExporter exporter = null;
try
{
exporter = exporterClass.newInstance();
}
catch (Exception e)
{
throw new AdempiereException(e.getLocalizedMessage(), e);
} | exporter.setDataSource(dataSource);
exporter.setConfig(config);
return exporter;
}
@Override
public void registerExporter(String mimeType, Class<? extends IExporter> exporterClass)
{
Check.assume(!Check.isEmpty(mimeType, true), "mimeType not empty");
Check.assumeNotNull(exporterClass, "exporterClass not null");
exporterClasses.put(mimeType.trim(), exporterClass);
// TODO Auto-generated method stub
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\ExporterFactory.java | 1 |
请完成以下Java代码 | public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Serial No.
@param SerNo
Product Serial Number
*/
public void setSerNo (String SerNo)
{
set_ValueNoCheck (COLUMNNAME_SerNo, SerNo);
}
/** Get Serial No.
@return Product Serial Number
*/
public String getSerNo ()
{
return (String)get_Value(COLUMNNAME_SerNo);
}
/** Set Details.
@param TextDetails Details */
public void setTextDetails (String TextDetails)
{
set_ValueNoCheck (COLUMNNAME_TextDetails, TextDetails);
}
/** Get Details.
@return Details */
public String getTextDetails ()
{
return (String)get_Value(COLUMNNAME_TextDetails);
}
/** Set Usable Life - Months.
@param UseLifeMonths
Months of the usable life of the asset
*/
public void setUseLifeMonths (int UseLifeMonths)
{
set_ValueNoCheck (COLUMNNAME_UseLifeMonths, Integer.valueOf(UseLifeMonths));
}
/** Get Usable Life - Months.
@return Months of the usable life of the asset
*/
public int getUseLifeMonths ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeMonths);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usable Life - Years.
@param UseLifeYears
Years of the usable life of the asset
*/
public void setUseLifeYears (int UseLifeYears)
{
set_ValueNoCheck (COLUMNNAME_UseLifeYears, Integer.valueOf(UseLifeYears));
}
/** Get Usable Life - Years.
@return Years of the usable life of the asset
*/
public int getUseLifeYears () | {
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeYears);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Use units.
@param UseUnits
Currently used units of the assets
*/
public void setUseUnits (int UseUnits)
{
set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits));
}
/** Get Use units.
@return Currently used units of the assets
*/
public int getUseUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Version No.
@param VersionNo
Version Number
*/
public void setVersionNo (String VersionNo)
{
set_ValueNoCheck (COLUMNNAME_VersionNo, VersionNo);
}
/** Get Version No.
@return Version Number
*/
public String getVersionNo ()
{
return (String)get_Value(COLUMNNAME_VersionNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Change.java | 1 |
请完成以下Java代码 | public Spliterator<T> spliterator() {
return new BookSpliterator(elements, 0);
}
@Override
public Stream<T> parallelStream() {
return StreamSupport.stream(spliterator(), false);
}
// standard overridden methods of Collection Interface
@Override
public int size() {
return elements.length;
}
@Override
public boolean isEmpty() {
return elements.length == 0;
}
@Override
public boolean contains(Object o) {
return false;
}
@Override
public Iterator<T> iterator() {
return null;
}
@Override
public Object[] toArray() {
return new Object[0];
}
@Override
public <T1> T1[] toArray(T1[] a) {
return null;
}
@Override
public boolean add(T t) {
return false;
} | @Override
public boolean remove(Object o) {
return false;
}
@Override
public boolean containsAll(Collection<?> c) {
return false;
}
@Override
public boolean addAll(Collection<? extends T> c) {
return false;
}
@Override
public boolean removeAll(Collection<?> c) {
return false;
}
@Override
public boolean retainAll(Collection<?> c) {
return false;
}
@Override
public void clear() {
}
} | repos\tutorials-master\core-java-modules\core-java-streams-5\src\main\java\com\baeldung\streams\parallelstream\MyBookContainer.java | 1 |
请完成以下Java代码 | public class MProductPO extends X_M_Product_PO
{
/**
*
*/
private static final long serialVersionUID = -747761340543484440L;
/**
* Get current PO of Product
* @param ctx context
* @param M_Product_ID product
* @param trxName transaction
* @return PO - current vendor first
*/
public static MProductPO[] getOfProduct (Properties ctx, int M_Product_ID, String trxName)
{
final String whereClause = "M_Product_ID=? AND IsActive=?";
List<MProductPO> list = new Query(ctx, Table_Name, whereClause, trxName)
.setParameters(new Object[]{M_Product_ID, "Y"})
.setOrderBy("IsCurrentVendor DESC")
.list(MProductPO.class);
return list.toArray(new MProductPO[list.size()]);
} // getOfProduct
/**
* Persistency Constructor
* @param ctx context
* @param ignored ignored
* @param trxName transaction
*/
public MProductPO (Properties ctx, int ignored, String trxName)
{ | super(ctx, 0, trxName);
if (ignored != 0)
throw new IllegalArgumentException("Multi-Key");
else
{
// setM_Product_ID (0); // @M_Product_ID@
// setC_BPartner_ID (0); // 0
// setVendorProductNo (null); // @Value@
setIsCurrentVendor (true); // Y
}
} // MProduct_PO
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MProductPO(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MProductPO
} // MProductPO | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MProductPO.java | 1 |
请完成以下Java代码 | public static ExecutionTree buildExecutionTreeForProcessInstance(Collection<ExecutionEntity> executions) {
ExecutionTree executionTree = new ExecutionTree();
if (executions.size() == 0) {
return executionTree;
}
// Map the executions to their parents. Catch and store the root element (process instance execution) while were at it
Map<String, List<ExecutionEntity>> parentMapping = new HashMap<String, List<ExecutionEntity>>();
for (ExecutionEntity executionEntity : executions) {
String parentId = executionEntity.getParentId();
if (parentId != null) {
if (!parentMapping.containsKey(parentId)) {
parentMapping.put(parentId, new ArrayList<ExecutionEntity>());
}
parentMapping.get(parentId).add(executionEntity);
} else {
executionTree.setRoot(new ExecutionTreeNode(executionEntity));
}
}
fillExecutionTree(executionTree, parentMapping);
return executionTree;
}
protected static void fillExecutionTree(
ExecutionTree executionTree,
Map<String, List<ExecutionEntity>> parentMapping
) {
if (executionTree.getRoot() == null) {
throw new ActivitiException(
"Programmatic error: the list of passed executions in the argument of the method should contain the process instance execution"
);
}
// Now build the tree, top-down
LinkedList<ExecutionTreeNode> executionsToHandle = new LinkedList<ExecutionTreeNode>();
executionsToHandle.add(executionTree.getRoot()); | while (!executionsToHandle.isEmpty()) {
ExecutionTreeNode parentNode = executionsToHandle.pop();
String parentId = parentNode.getExecutionEntity().getId();
if (parentMapping.containsKey(parentId)) {
List<ExecutionEntity> childExecutions = parentMapping.get(parentId);
List<ExecutionTreeNode> childNodes = new ArrayList<ExecutionTreeNode>(childExecutions.size());
for (ExecutionEntity childExecutionEntity : childExecutions) {
ExecutionTreeNode childNode = new ExecutionTreeNode(childExecutionEntity);
childNode.setParent(parentNode);
childNodes.add(childNode);
executionsToHandle.add(childNode);
}
parentNode.setChildren(childNodes);
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\debug\ExecutionTreeUtil.java | 1 |
请完成以下Java代码 | public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Classname.
@param Classname
Java Classname
*/
@Override
public void setClassname (java.lang.String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
@Override
public java.lang.String getClassname ()
{
return (java.lang.String)get_Value(COLUMNNAME_Classname);
}
/**
* EntityType AD_Reference_ID=389
* Reference name: _EntityTypeNew
*/
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public void setEntityType (java.lang.String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
} | /** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
@Override
public java.lang.String getEntityType ()
{
return (java.lang.String)get_Value(COLUMNNAME_EntityType);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Field_ContextMenu.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ExternalWorkerJobBaseResource {
protected ManagementService managementService;
protected CmmnManagementService cmmnManagementService;
protected ExternalWorkerJobRestApiInterceptor restApiInterceptor;
protected ExternalWorkerJobQuery createExternalWorkerJobQuery() {
if (managementService != null) {
return managementService.createExternalWorkerJobQuery();
} else if (cmmnManagementService != null) {
return cmmnManagementService.createExternalWorkerJobQuery();
} else {
throw new FlowableException("Cannot query external jobs. There is no BPMN or CMMN engine available");
}
}
protected ExternalWorkerJob getExternalWorkerJobById(String jobId) {
ExternalWorkerJob job = createExternalWorkerJobQuery().jobId(jobId).singleResult();
if (job == null) {
throw new FlowableObjectNotFoundException("Could not find external worker job with id '" + jobId + "'.", ExternalWorkerJob.class);
}
if (restApiInterceptor != null) { | restApiInterceptor.accessExternalWorkerJobById(job);
}
return job;
}
@Autowired(required = false)
public void setManagementService(ManagementService managementService) {
this.managementService = managementService;
}
@Autowired(required = false)
public void setCmmnManagementService(CmmnManagementService cmmnManagementService) {
this.cmmnManagementService = cmmnManagementService;
}
@Autowired(required = false)
public void setRestApiInterceptor(ExternalWorkerJobRestApiInterceptor restApiInterceptor) {
this.restApiInterceptor = restApiInterceptor;
}
} | repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\ExternalWorkerJobBaseResource.java | 2 |
请完成以下Java代码 | public static boolean isReported(@Nullable final Throwable exception)
{
Throwable currentEx = exception;
while (currentEx != null)
{
if (currentEx instanceof IIssueReportableAware)
{
final IIssueReportableAware issueReportable = (IIssueReportableAware)currentEx;
if (issueReportable.isIssueReported())
{
return true;
}
}
currentEx = currentEx.getCause();
}
return false;
} | @Nullable
public static AdIssueId getAdIssueIdOrNull(@NonNull final Throwable exception)
{
if (exception instanceof IIssueReportableAware)
{
final IIssueReportableAware issueReportable = (IIssueReportableAware)exception;
if (issueReportable.isIssueReported())
{
return issueReportable.getAdIssueId();
}
else
{
return null;
}
}
else
{
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\exceptions\IssueReportableExceptions.java | 1 |
请完成以下Java代码 | public Object getParameterComponent(int index)
{
if (index == 0)
return fieldCityZip;
else if (index == 1)
return fieldRadius;
else
return null;
}
@Override
public String[] getWhereClauses(List<Object> params)
{
final GeodbObject go = getGeodbObject();
final String searchText = getText();
if (go == null && !Check.isEmpty(searchText, true))
return new String[]{"1=2"};
if (go == null)
return new String[]{"1=1"};
final int radius = getRadius();
//
final String whereClause = "EXISTS (SELECT 1 FROM geodb_coordinates co WHERE "
+ " co.zip=" + locationTableAlias + ".Postal" // join to C_Location.Postal
+ " AND co.c_country_id=" + locationTableAlias + ".C_Country_ID"
+ " AND " + getSQLDistanceFormula("co", go.getLat(), go.getLon()) + " <= " + radius
+ ")";
return new String[]{whereClause};
}
private static String getSQLDistanceFormula(String tableAlias, double lat, double lon) | {
return "DEGREES("
+ " (ACOS("
+ " SIN(RADIANS(" + lat + ")) * SIN(RADIANS(" + tableAlias + ".lat)) "
+ " + COS(RADIANS(" + lat + "))*COS(RADIANS(" + tableAlias + ".lat))*COS(RADIANS(" + tableAlias + ".lon) - RADIANS(" + lon + "))"
+ ") * 60 * 1.1515 " // miles
+ " * 1.609344" // KM factor
+ " )"
+ " )";
}
private GeodbObject getGeodbObject()
{
return (GeodbObject)fieldCityZipAutocompleter.getUserOject();
}
@Override
public String getText()
{
return fieldCityZipAutocompleter.getText();
}
private int getRadius()
{
if (fieldRadius == null)
return 0;
Object o = fieldRadius.getValue();
if (o instanceof Number)
return ((Number)o).intValue();
return 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\gui\search\InfoQueryCriteriaBPRadius.java | 1 |
请完成以下Java代码 | default TableRecordReference getTableRecordReferenceOrNull(@NonNull final DocumentId rowId)
{
final int recordId = rowId.toIntOr(-1);
if (recordId < 0)
{
return null;
}
final String tableName = getTableNameOrNull(rowId);
if (tableName == null)
{
return null;
}
return TableRecordReference.of(tableName, recordId);
}
@Nullable
SqlViewRowsWhereClause getSqlWhereClause(DocumentIdsSelection rowIds, SqlOptions sqlOpts);
default boolean hasAttributesSupport()
{
return false;
}
<T> List<T> retrieveModelsByIds(DocumentIdsSelection rowIds, Class<T> modelClass);
@NonNull
default <T> Stream<T> streamModelsByIds(@NonNull final DocumentIdsSelection rowIds, @NonNull final Class<T> modelClass)
{
return retrieveModelsByIds(rowIds, modelClass).stream();
}
/**
* @return a stream which contains only the {@link IViewRow}s which given <code>rowId</code>s.
* If a {@link IViewRow} was not found for given ID, this method simply ignores it.
*/
Stream<? extends IViewRow> streamByIds(DocumentIdsSelection rowIds);
default Stream<? extends IViewRow> streamByIds(DocumentIdsSelection rowIds, QueryLimit suggestedLimit)
{
return streamByIds(rowIds);
}
default Stream<? extends IViewRow> streamByIds(DocumentIdsSelection rowIds, DocumentQueryOrderByList orderBys, QueryLimit suggestedLimit)
{
return streamByIds(rowIds); | }
/**
* Notify the view that given record(s) has changed.
*/
void notifyRecordsChanged(TableRecordReferenceSet recordRefs, boolean watchedByFrontend);
/**
* @return actions which were registered particularly for this view instance
*/
default ViewActionDescriptorsList getActions()
{
return ViewActionDescriptorsList.EMPTY;
}
default boolean isConsiderTableRelatedProcessDescriptors(@NonNull final ProcessHandlerType processHandlerType, @NonNull final DocumentIdsSelection selectedRowIds)
{
return true;
}
default List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{
return ImmutableList.of();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\IView.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DemoApplication {
private final Logger logger = LoggerFactory.getLogger(DemoApplication.class);
@Autowired private CustomerRepository repository;
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
@EventListener(ApplicationReadyEvent.class)
public void runAfterStartup() {
queryAllCustomers();
createCustomer();
queryAllCustomers();
} | private void createCustomer() {
Customer newCustomer = new Customer();
newCustomer.setFirstName("John");
newCustomer.setLastName("Doe");
logger.info("Saving new customer...");
this.repository.save(newCustomer);
}
private void queryAllCustomers() {
List<Customer> allCustomers = this.repository.findAll();
logger.info("Number of customers: " + allCustomers.size());
}
} | repos\tutorials-master\docker-modules\docker-spring-boot-postgres\src\main\java\com\baeldung\docker\DemoApplication.java | 2 |
请完成以下Java代码 | public String toString()
{
final StringBuilder sb = new StringBuilder("词条数量:");
sb.append(trie.size());
return sb.toString();
}
@Override
public boolean saveTxtTo(String path)
{
if (trie.size() == 0) return true; // 如果没有词条,那也算成功了
try
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path), "UTF-8"));
Set<Map.Entry<String, Item>> entries = trie.entrySet();
for (Map.Entry<String, Item> entry : entries)
{
bw.write(entry.getValue().toString());
bw.newLine();
}
bw.close();
}
catch (Exception e)
{
Predefine.logger.warning("保存到" + path + "失败" + e);
return false;
}
return true;
}
public void add(String param)
{
Item item = Item.create(param);
if (item != null) add(item);
}
public static interface Filter
{
/**
* 是否保存这个条目
* @param item
* @return true表示保存
*/
boolean onSave(Item item);
}
/**
* 允许保存之前对其做一些调整
*
* @param path
* @param filter
* @return
*/
public boolean saveTxtTo(String path, Filter filter)
{
try
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(IOUtil.newOutputStream(path), "UTF-8"));
Set<Map.Entry<String, Item>> entries = trie.entrySet();
for (Map.Entry<String, Item> entry : entries)
{
if (filter.onSave(entry.getValue()))
{
bw.write(entry.getValue().toString());
bw.newLine();
}
} | bw.close();
}
catch (Exception e)
{
Predefine.logger.warning("保存到" + path + "失败" + e);
return false;
}
return true;
}
/**
* 调整频次,按排序后的次序给定频次
*
* @param itemList
* @return 处理后的列表
*/
public static List<Item> normalizeFrequency(List<Item> itemList)
{
for (Item item : itemList)
{
ArrayList<Map.Entry<String, Integer>> entryArray = new ArrayList<Map.Entry<String, Integer>>(item.labelMap.entrySet());
Collections.sort(entryArray, new Comparator<Map.Entry<String, Integer>>()
{
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2)
{
return o1.getValue().compareTo(o2.getValue());
}
});
int index = 1;
for (Map.Entry<String, Integer> pair : entryArray)
{
item.labelMap.put(pair.getKey(), index);
++index;
}
}
return itemList;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\DictionaryMaker.java | 1 |
请完成以下Java代码 | public String getTitl() {
return titl;
}
/**
* Sets the value of the titl property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTitl(String value) {
this.titl = value;
}
/**
* Gets the value of the nm property.
*
* @return
* possible object is
* {@link String } | *
*/
public String getNm() {
return nm;
}
/**
* Sets the value of the nm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNm(String value) {
this.nm = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\TaxAuthorisation1.java | 1 |
请完成以下Java代码 | public void contribute(Info.Builder builder) {
builder.withDetail("build", generateContent());
}
@Override
protected PropertySource<?> toSimplePropertySource() {
Properties props = new Properties();
copyIfSet(props, "group");
copyIfSet(props, "artifact");
copyIfSet(props, "name");
copyIfSet(props, "version");
copyIfSet(props, "time");
return new PropertiesPropertySource("build", props);
}
@Override | protected void postProcessContent(Map<String, Object> content) {
replaceValue(content, "time", getProperties().getTime());
}
static class BuildInfoContributorRuntimeHints implements RuntimeHintsRegistrar {
private final BindingReflectionHintsRegistrar bindingRegistrar = new BindingReflectionHintsRegistrar();
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
this.bindingRegistrar.registerReflectionHints(hints.reflection(), BuildProperties.class);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\info\BuildInfoContributor.java | 1 |
请完成以下Java代码 | public void notify(DelegateTask delegateTask) {
validateParameters();
TaskComparatorImpl taskComparator = new TaskComparatorImpl();
taskComparator.setOriginalTask((TaskInfo) delegateTask);
ScriptingEngines scriptingEngines = Context.getProcessEngineConfiguration().getScriptingEngines();
Object result = scriptingEngines.evaluate(
script.getExpressionText(),
language.getExpressionText(),
delegateTask,
autoStoreVariables
);
if (resultVariable != null) {
delegateTask.setVariable(resultVariable.getExpressionText(), result);
}
TaskUpdater taskUpdater = new TaskUpdater(Context.getCommandContext(), false);
taskUpdater.updateTask(taskComparator.getOriginalTask(), (TaskInfo) delegateTask);
}
protected void validateParameters() {
if (script == null) {
throw new IllegalArgumentException("The field 'script' should be set on the TaskListener"); | }
if (language == null) {
throw new IllegalArgumentException("The field 'language' should be set on the TaskListener");
}
}
public void setScript(Expression script) {
this.script = script;
}
public void setLanguage(Expression language) {
this.language = language;
}
public void setResultVariable(Expression resultVariable) {
this.resultVariable = resultVariable;
}
public void setAutoStoreVariables(boolean autoStoreVariables) {
this.autoStoreVariables = autoStoreVariables;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\listener\ScriptTaskListener.java | 1 |
请完成以下Java代码 | public abstract class JobResult implements Serializable {
private int successfulCount;
private int failedCount;
private int discardedCount;
private Integer totalCount = null; // set when all tasks are submitted
private List<TaskResult> results = new ArrayList<>();
private String generalError;
private long startTs;
private long finishTs;
private long cancellationTs;
@JsonIgnore
public int getCompletedCount() {
return successfulCount + failedCount + discardedCount;
}
public void processTaskResult(TaskResult taskResult) {
if (taskResult.isSuccess()) {
if (totalCount == null || successfulCount < totalCount) {
successfulCount++; | }
} else if (taskResult.isDiscarded()) {
if (totalCount == null || discardedCount < totalCount) {
discardedCount++;
}
} else {
if (totalCount == null || failedCount < totalCount) {
failedCount++;
}
if (results.size() < 100) { // preserving only first 100 errors, not reprocessing if there are more failures
results.add(taskResult);
}
}
}
@JsonIgnore
public abstract JobType getJobType();
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\job\JobResult.java | 1 |
请完成以下Java代码 | public void fireJobFailedEvent(final Job job, final Throwable exception) {
if (isHistoryEventProduced(HistoryEventTypes.JOB_FAIL, job)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricJobLogFailedEvt(job, exception);
}
@Override
public void postHandleSingleHistoryEventCreated(HistoryEvent event) {
((JobEntity) job).setLastFailureLogId(event.getId());
}
});
}
}
public void fireJobSuccessfulEvent(final Job job) {
if (isHistoryEventProduced(HistoryEventTypes.JOB_SUCCESS, job)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricJobLogSuccessfulEvt(job);
}
});
}
}
public void fireJobDeletedEvent(final Job job) {
if (isHistoryEventProduced(HistoryEventTypes.JOB_DELETE, job)) {
HistoryEventProcessor.processHistoryEvents(new HistoryEventProcessor.HistoryEventCreator() {
@Override
public HistoryEvent createHistoryEvent(HistoryEventProducer producer) {
return producer.createHistoricJobLogDeleteEvt(job);
}
});
}
} | // helper /////////////////////////////////////////////////////////
protected boolean isHistoryEventProduced(HistoryEventType eventType, Job job) {
ProcessEngineConfigurationImpl configuration = Context.getProcessEngineConfiguration();
HistoryLevel historyLevel = configuration.getHistoryLevel();
return historyLevel.isHistoryEventProduced(eventType, job);
}
protected void configureQuery(HistoricJobLogQueryImpl query) {
getAuthorizationManager().configureHistoricJobLogQuery(query);
getTenantManager().configureQuery(query);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricJobLogManager.java | 1 |
请完成以下Java代码 | public final static ELResolver lookupResolver(AbstractProcessApplication processApplication) {
ServiceLoader<ProcessApplicationElResolver> providers = ServiceLoader.load(ProcessApplicationElResolver.class);
List<ProcessApplicationElResolver> sortedProviders = new ArrayList<ProcessApplicationElResolver>();
for (ProcessApplicationElResolver provider : providers) {
sortedProviders.add(provider);
}
if(sortedProviders.isEmpty()) {
return null;
} else {
// sort providers first
Collections.sort(sortedProviders, new ProcessApplicationElResolver.ProcessApplicationElResolverSorter());
// add all providers to a composite resolver
CompositeELResolver compositeResolver = new CompositeELResolver();
StringBuilder summary = new StringBuilder();
summary.append(String.format("ElResolvers found for Process Application %s", processApplication.getName())); | for (ProcessApplicationElResolver processApplicationElResolver : sortedProviders) {
ELResolver elResolver = processApplicationElResolver.getElResolver(processApplication);
if (elResolver != null) {
compositeResolver.add(elResolver);
summary.append(String.format("Class %s", processApplicationElResolver.getClass().getName()));
}
else {
LOG.noElResolverProvided(processApplication.getName(), processApplicationElResolver.getClass().getName());
}
}
LOG.paElResolversDiscovered(summary.toString());
return compositeResolver;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\DefaultElResolverLookup.java | 1 |
请完成以下Java代码 | public boolean catchesError(String errorCode) {
return this.errorCode == null || this.errorCode.equals(errorCode);
}
public boolean catchesException(Exception ex) {
if(this.errorCode == null) {
return false;
} else {
// unbox exception
while ((ex instanceof ProcessEngineException || ex instanceof ScriptException) && ex.getCause() != null) {
ex = (Exception) ex.getCause();
}
// check exception hierarchy
Class<?> exceptionClass = ex.getClass();
do {
if(this.errorCode.equals(exceptionClass.getName())) {
return true;
} | exceptionClass = exceptionClass.getSuperclass();
} while(exceptionClass != null);
return false;
}
}
public void setErrorCodeVariable(String errorCodeVariable) {
this.errorCodeVariable = errorCodeVariable;
}
public String getErrorCodeVariable() {
return errorCodeVariable;
}
public void setErrorMessageVariable(String errorMessageVariable) {
this.errorMessageVariable = errorMessageVariable;
}
public String getErrorMessageVariable() {
return errorMessageVariable;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\ErrorEventDefinition.java | 1 |
请完成以下Java代码 | public Builder onErrorThrowException(final boolean onErrorThrowException)
{
this.onErrorThrowException = onErrorThrowException;
return this;
}
/**
* Advice the executor to switch current context with process info's context.
*
* @see ProcessInfo#getCtx()
* @see Env#switchContext(Properties)
*/
public Builder switchContextWhenRunning()
{
this.switchContextWhenRunning = true;
return this; | }
/**
* Sets the callback to be executed after AD_PInstance is created but before the actual process is started.
* If the callback fails, the exception is propagated, so the process will not be started.
* <p>
* A common use case of <code>beforeCallback</code> is to create to selections which are linked to this process instance.
*/
public Builder callBefore(final Consumer<ProcessInfo> beforeCallback)
{
this.beforeCallback = beforeCallback;
return this;
}
}
} // ProcessCtl | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessExecutor.java | 1 |
请完成以下Java代码 | public class DataEntryListValueLookupDescriptor implements LookupDescriptor
{
private final DataEntryListValueDataSourceFetcher dataEntryListValueDataSourceFetcher;
public static DataEntryListValueLookupDescriptor of(@NonNull final List<DataEntryListValue> listValues)
{
return new DataEntryListValueLookupDescriptor(listValues);
}
private DataEntryListValueLookupDescriptor(@NonNull final List<DataEntryListValue> listValues)
{
dataEntryListValueDataSourceFetcher = new DataEntryListValueDataSourceFetcher(listValues);
}
@Override
public LookupDataSourceFetcher getLookupDataSourceFetcher()
{
return dataEntryListValueDataSourceFetcher;
}
@Override
public boolean isHighVolume()
{
return false;
}
@Override
public LookupSource getLookupSourceType()
{
return LookupSource.list;
} | @Override
public boolean hasParameters()
{
return false;
}
@Override
public boolean isNumericKey()
{
return true;
}
@Override
public Set<String> getDependsOnFieldNames()
{
return ImmutableSet.of();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\window\descriptor\factory\DataEntryListValueLookupDescriptor.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
if (context.isMoreThanOneSelected())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
final boolean invoiceRelationsFound = queryBL.createQueryBuilder(I_C_Invoice_Relation.class)
.addInSubQueryFilter(I_C_Invoice_Relation.COLUMN_C_Invoice_To_ID, I_C_Invoice.COLUMN_C_Invoice_ID,
queryBL.createQueryBuilder(I_C_Invoice.class)
.filter(context.getQueryFilter(I_C_Invoice.class))
.create())
.create().anyMatch();
if (!invoiceRelationsFound)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("No invoice relations found.");
}
return ProcessPreconditionsResolution.accept();
}
@Override | protected String doIt() throws Exception
{
removeRelations();
return MSG_OK;
}
private void removeRelations()
{
queryBL.createQueryBuilder(I_C_Invoice_Relation.class)
.addEqualsFilter(I_C_Invoice_Relation.COLUMNNAME_C_Invoice_Relation_Type, relationToRemove)
.addEqualsFilter(I_C_Invoice_Relation.COLUMNNAME_C_Invoice_From_ID, poInvoiceRepoId)
.addEqualsFilter(I_C_Invoice_Relation.COLUMNNAME_C_Invoice_To_ID, getRecord_ID())
.create()
.delete();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\process\C_Invoice_RemoveRelation.java | 1 |
请完成以下Spring Boot application配置 | spring.datasource.url=jdbc:mysql://127.0.0.1:3306/demo?useUnicode=true&characterEncoding=utf-8&useSSL=false
spring.datasource.username=root
spring.datasource.password=123456
s | pring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
server.port=8081 | repos\springboot-demo-master\shedlock\src\main\resources\application-node1.properties | 2 |
请完成以下Java代码 | public void setIsSyncBPartnersToRabbitMQ (final boolean IsSyncBPartnersToRabbitMQ)
{
set_Value (COLUMNNAME_IsSyncBPartnersToRabbitMQ, IsSyncBPartnersToRabbitMQ);
}
@Override
public boolean isSyncBPartnersToRabbitMQ()
{
return get_ValueAsBoolean(COLUMNNAME_IsSyncBPartnersToRabbitMQ);
}
@Override
public void setIsSyncExternalReferencesToRabbitMQ (final boolean IsSyncExternalReferencesToRabbitMQ)
{
set_Value (COLUMNNAME_IsSyncExternalReferencesToRabbitMQ, IsSyncExternalReferencesToRabbitMQ);
}
@Override
public boolean isSyncExternalReferencesToRabbitMQ()
{
return get_ValueAsBoolean(COLUMNNAME_IsSyncExternalReferencesToRabbitMQ);
}
@Override
public void setRemoteURL (final java.lang.String RemoteURL)
{
set_Value (COLUMNNAME_RemoteURL, RemoteURL);
}
@Override
public String getRemoteURL()
{
return get_ValueAsString(COLUMNNAME_RemoteURL); | }
@Override
public void setRouting_Key (final String Routing_Key)
{
set_Value (COLUMNNAME_Routing_Key, Routing_Key);
}
@Override
public String getRouting_Key()
{
return get_ValueAsString(COLUMNNAME_Routing_Key);
}
@Override
public void setAuthToken (final String AuthToken)
{
set_Value (COLUMNNAME_AuthToken, AuthToken);
}
@Override
public String getAuthToken()
{
return get_ValueAsString(COLUMNNAME_AuthToken);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_RabbitMQ_HTTP.java | 1 |
请完成以下Java代码 | public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType; | }
@Override
public String getSubScopeId() {
return ScopeTypes.BPMN.equals(scopeType) ? executionId : null;
}
@Override
public String getScopeDefinitionId() {
return ScopeTypes.BPMN.equals(scopeType) ? processDefinitionId : null;
}
@Override
public String getVariableInstanceId() {
return variableInstanceId;
}
public void setVariableInstanceId(String variableInstanceId) {
this.variableInstanceId = variableInstanceId;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiVariableEventImpl.java | 1 |
请完成以下Java代码 | public static JobEntity createJob(ExecutionEntity execution, BaseElement baseElement, String jobHandlerType, ProcessEngineConfigurationImpl processEngineConfiguration) {
JobService jobService = processEngineConfiguration.getJobServiceConfiguration().getJobService();
JobEntity job = jobService.createJob();
job.setExecutionId(execution.getId());
job.setProcessInstanceId(execution.getProcessInstanceId());
job.setProcessDefinitionId(execution.getProcessDefinitionId());
job.setElementId(baseElement.getId());
if (baseElement instanceof FlowElement) {
job.setElementName(((FlowElement) baseElement).getName());
}
job.setJobHandlerType(jobHandlerType);
List<ExtensionElement> jobCategoryElements = baseElement.getExtensionElements().get("jobCategory");
if (jobCategoryElements != null && jobCategoryElements.size() > 0) {
ExtensionElement jobCategoryElement = jobCategoryElements.get(0);
if (StringUtils.isNotEmpty(jobCategoryElement.getElementText())) { | Expression categoryExpression = processEngineConfiguration.getExpressionManager().createExpression(jobCategoryElement.getElementText());
Object categoryValue = categoryExpression.getValue(execution);
if (categoryValue != null) {
job.setCategory(categoryValue.toString());
}
}
}
// Inherit tenant id (if applicable)
if (execution.getTenantId() != null) {
job.setTenantId(execution.getTenantId());
}
return job;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\JobUtil.java | 1 |
请完成以下Java代码 | public String getStatusActivitySubtitle() {
return statusActivitySubtitle.getExpressionString();
}
public void setStatusActivitySubtitle(String statusActivitySubtitle) {
this.statusActivitySubtitle = parser.parseExpression(statusActivitySubtitle, ParserContext.TEMPLATE_EXPRESSION);
}
@Data
@Builder
public static class Message {
private final String summary;
private final String themeColor;
private final String title;
@Builder.Default
private final List<Section> sections = new ArrayList<>();
}
@Data | @Builder
public static class Section {
private final String activityTitle;
private final String activitySubtitle;
@Builder.Default
private final List<Fact> facts = new ArrayList<>();
}
public record Fact(String name, @Nullable String value) {
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\MicrosoftTeamsNotifier.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.