instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String getCamundaCaseVersion() {
return camundaCaseVersionAttribute.getValue(this);
}
public void setCamundaCaseVersion(String camundaCaseVersion) {
camundaCaseVersionAttribute.setValue(this, camundaCaseVersion);
}
public String getCamundaCaseTenantId() {
return camundaCaseTenantIdAttribute.getValue(this);
}
public void setCamundaCaseTenantId(String camundaCaseTenantId) {
camundaCaseTenantIdAttribute.setValue(this, camundaCaseTenantId);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseTask.class, CMMN_ELEMENT_CASE_TASK)
.extendsType(Task.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<CaseTask>() {
public CaseTask newInstance(ModelTypeInstanceContext instanceContext) {
return new CaseTaskImpl(instanceContext);
}
});
caseRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_CASE_REF)
.build();
/** camunda extensions */ | camundaCaseBindingAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_BINDING)
.namespace(CAMUNDA_NS)
.build();
camundaCaseVersionAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_VERSION)
.namespace(CAMUNDA_NS)
.build();
camundaCaseTenantIdAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_CASE_TENANT_ID)
.namespace(CAMUNDA_NS)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
parameterMappingCollection = sequenceBuilder.elementCollection(ParameterMapping.class)
.build();
caseRefExpressionChild = sequenceBuilder.element(CaseRefExpression.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseTaskImpl.java | 1 |
请完成以下Java代码 | public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName (final @Nullable java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUPC (final @Nullable java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
@Override
public java.lang.String getUPC()
{ | return get_ValueAsString(COLUMNNAME_UPC);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Item_Product.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected JakartaTransactionProcessEngineConfiguration createProcessEngineConfiguration() {
String configurationClassName = ManagedJtaProcessEngineConfiguration.class.getName();
if(processEngineMetadata.getConfiguration() != null && !processEngineMetadata.getConfiguration().isEmpty()) {
configurationClassName = processEngineMetadata.getConfiguration();
}
Object configurationObject = createInstance(configurationClassName);
if (configurationObject instanceof JakartaTransactionProcessEngineConfiguration) {
return (JakartaTransactionProcessEngineConfiguration) configurationObject;
} else {
throw new ProcessEngineException("Configuration class '"+configurationClassName+"' " +
"is not a subclass of " + JakartaTransactionProcessEngineConfiguration.class.getName());
}
}
private Object createInstance(String configurationClassName) {
try {
Class<?> configurationClass = getClass().getClassLoader().loadClass(configurationClassName);
return configurationClass.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new ProcessEngineException("Could not load '"+configurationClassName+"': the class must be visible from the camunda-wildfly-subsystem module.", e);
}
}
public void initializeServiceBuilder(ManagedProcessEngineMetadata processEngineConfiguration,
ServiceBuilder<?> serviceBuilder, ServiceName name, String jobExecutorName) { | ContextNames.BindInfo datasourceBindInfo = ContextNames.bindInfoFor(processEngineConfiguration.getDatasourceJndiName());
transactionManagerSupplier = serviceBuilder.requires(ServiceName.JBOSS.append("txn").append("TransactionManager"));
datasourceBinderServiceSupplier = serviceBuilder.requires(datasourceBindInfo.getBinderServiceName());
runtimeContainerDelegateSupplier = serviceBuilder.requires(ServiceNames.forMscRuntimeContainerDelegate());
mscRuntimeContainerJobExecutorSupplier = serviceBuilder.requires(ServiceNames.forMscRuntimeContainerJobExecutorService(jobExecutorName));
serviceBuilder.setInitialMode(Mode.ACTIVE);
serviceBuilder.requires(ServiceNames.forMscExecutorService());
processEngineConsumers.add(serviceBuilder.provides(name));
this.executorSupplier = JBossCompatibilityExtension.addServerExecutorDependency(serviceBuilder);
JBossCompatibilityExtension.addServerExecutorDependency(serviceBuilder);
}
public ProcessEngine getProcessEngine() {
return processEngine;
}
public ManagedProcessEngineMetadata getProcessEngineMetadata() {
return processEngineMetadata;
}
} | repos\camunda-bpm-platform-master\distro\wildfly\subsystem\src\main\java\org\camunda\bpm\container\impl\jboss\service\MscManagedProcessEngineController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public IQueryBL queryBL()
{
return Services.get(IQueryBL.class);
}
@Bean
public ImportQueue<ImportTimeBookingInfo> timeBookingImportQueue()
{
return new ImportQueue<>(TIME_BOOKING_QUEUE_CAPACITY, IMPORT_TIME_BOOKINGS_LOG_MESSAGE_PREFIX);
}
@Bean
public ImportQueue<ImportIssueInfo> importIssuesQueue()
{
return new ImportQueue<>(ISSUE_QUEUE_CAPACITY, IMPORT_LOG_MESSAGE_PREFIX); | }
@Bean
public ObjectMapper objectMapper()
{
return JsonObjectMapperHolder.sharedJsonObjectMapper();
}
@Bean
public IMsgBL msgBL()
{
return Services.get(IMsgBL.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java\de\metas\serviceprovider\configuration\ApplicationConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public CategoryEntity getSubCategEntity() {
return subCategEntity;
}
public void setSubCategEntity(CategoryEntity subCategEntity) {
this.subCategEntity = subCategEntity;
}
public BrandEntity getBrandEntity() {
return brandEntity;
}
public void setBrandEntity(BrandEntity brandEntity) {
this.brandEntity = brandEntity;
}
public ProdStateEnum getProdStateEnum() {
return prodStateEnum;
}
public void setProdStateEnum(ProdStateEnum prodStateEnum) {
this.prodStateEnum = prodStateEnum;
}
public List<ProdImageEntity> getProdImageEntityList() {
return prodImageEntityList;
}
public void setProdImageEntityList(List<ProdImageEntity> prodImageEntityList) {
this.prodImageEntityList = prodImageEntityList;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public UserEntity getCompanyEntity() {
return companyEntity;
} | public void setCompanyEntity(UserEntity companyEntity) {
this.companyEntity = companyEntity;
}
public int getSales() {
return sales;
}
public void setSales(int sales) {
this.sales = sales;
}
@Override
public String toString() {
return "ProductEntity{" +
"id='" + id + '\'' +
", prodName='" + prodName + '\'' +
", marketPrice='" + marketPrice + '\'' +
", shopPrice='" + shopPrice + '\'' +
", stock=" + stock +
", sales=" + sales +
", weight='" + weight + '\'' +
", topCateEntity=" + topCateEntity +
", subCategEntity=" + subCategEntity +
", brandEntity=" + brandEntity +
", prodStateEnum=" + prodStateEnum +
", prodImageEntityList=" + prodImageEntityList +
", content='" + content + '\'' +
", companyEntity=" + companyEntity +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\product\ProductEntity.java | 2 |
请在Spring Boot框架中完成以下Java代码 | protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
// Engine scoped
protected VariableServiceConfiguration getVariableServiceConfiguration() {
return variableServiceConfiguration;
}
protected Clock getClock() { | return getVariableServiceConfiguration().getClock();
}
protected FlowableEventDispatcher getEventDispatcher() {
return getVariableServiceConfiguration().getEventDispatcher();
}
protected VariableInstanceEntityManager getVariableInstanceEntityManager() {
return getVariableServiceConfiguration().getVariableInstanceEntityManager();
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() {
return getVariableServiceConfiguration().getHistoricVariableInstanceEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\persistence\AbstractManager.java | 2 |
请完成以下Java代码 | public boolean isVerfuegbarkeitBulkVereinbart() {
return verfuegbarkeitBulkVereinbart;
}
/**
* Sets the value of the verfuegbarkeitBulkVereinbart property.
*
*/
public void setVerfuegbarkeitBulkVereinbart(boolean value) {
this.verfuegbarkeitBulkVereinbart = value;
}
/**
* Gets the value of the ruecknahmeangebotVereinbart property.
*
*/
public boolean isRuecknahmeangebotVereinbart() {
return ruecknahmeangebotVereinbart;
}
/**
* Sets the value of the ruecknahmeangebotVereinbart property.
*
*/
public void setRuecknahmeangebotVereinbart(boolean value) {
this.ruecknahmeangebotVereinbart = value;
}
/**
* Gets the value of the sondertag 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 sondertag property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getSondertag().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link TypSondertag }
*
*
*/
public List<TypSondertag> getSondertag() {
if (sondertag == null) { | sondertag = new ArrayList<TypSondertag>();
}
return this.sondertag;
}
/**
* Gets the value of the automatischerAbruf property.
*
*/
public boolean isAutomatischerAbruf() {
return automatischerAbruf;
}
/**
* Sets the value of the automatischerAbruf property.
*
*/
public void setAutomatischerAbruf(boolean value) {
this.automatischerAbruf = value;
}
/**
* Gets the value of the kundenKennung property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getKundenKennung() {
return kundenKennung;
}
/**
* Sets the value of the kundenKennung property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setKundenKennung(String value) {
this.kundenKennung = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\VertragsdatenAntwort.java | 1 |
请完成以下Java代码 | public boolean supports(ConfigAttribute attribute) {
for (AccessDecisionVoter<?> voter : this.decisionVoters) {
if (voter.supports(attribute)) {
return true;
}
}
return false;
}
/**
* Iterates through all <code>AccessDecisionVoter</code>s and ensures each can support
* the presented class.
* <p>
* If one or more voters cannot support the presented class, <code>false</code> is
* returned.
* @param clazz the type of secured object being presented
* @return true if this type is supported
*/
@Override
public boolean supports(Class<?> clazz) { | for (AccessDecisionVoter<?> voter : this.decisionVoters) {
if (!voter.supports(clazz)) {
return false;
}
}
return true;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + " [DecisionVoters=" + this.decisionVoters
+ ", AllowIfAllAbstainDecisions=" + this.allowIfAllAbstainDecisions + "]";
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\AbstractAccessDecisionManager.java | 1 |
请完成以下Java代码 | public abstract class AbstractJasyptMojo extends AbstractMojo {
/**
* The encrypted property prefix
*/
@Parameter(property = "jasypt.plugin.encrypt.prefix", defaultValue = "ENC(")
private String encryptPrefix = "ENC(";
/**
* The encrypted property suffix
*/
@Parameter(property = "jasypt.plugin.encrypt.suffix", defaultValue = ")")
private String encryptSuffix = ")";
/**
* The decrypted property prefix
*/
@Parameter(property = "jasypt.plugin.decrypt.prefix", defaultValue = "DEC(")
private String decryptPrefix = "DEC(";
/**
* The decrypted property suffix
*/
@Parameter(property = "jasypt.plugin.decrypt.suffix", defaultValue = ")")
private String decryptSuffix = ")";
private Environment environment;
/**
* <p>Getter for the field <code>environment</code>.</p>
*
* @return a {@link org.springframework.core.env.Environment} object
*/
protected Environment getEnvironment() {
return environment;
}
/** {@inheritDoc} */ | @Override
public void execute() throws MojoExecutionException {
Map<String, Object> defaultProperties = new HashMap<>();
defaultProperties.put("spring.config.location", "optional:file:./src/main/resources/");
ConfigurableApplicationContext context = new SpringApplicationBuilder()
.sources(Application.class)
.bannerMode(Banner.Mode.OFF)
.properties(defaultProperties)
.run();
this.environment = context.getEnvironment();
String[] activeProfiles = context.getEnvironment().getActiveProfiles();
String profiles = activeProfiles.length != 0 ? String.join(",", activeProfiles) : "Default";
log.info("Active Profiles: {}", profiles);
StringEncryptor encryptor = context.getBean(StringEncryptor.class);
run(new EncryptionService(encryptor), context, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix);
}
/**
* Run the encryption task.
*
* @param encryptionService the service for encryption
* @param context app context
*/
abstract void run(EncryptionService encryptionService, ConfigurableApplicationContext context, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix)
throws MojoExecutionException;
} | repos\jasypt-spring-boot-master\jasypt-maven-plugin\src\main\java\com\ulisesbocchio\jasyptmavenplugin\mojo\AbstractJasyptMojo.java | 1 |
请完成以下Java代码 | public int getDepreciationType ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DepreciationType);
if (ii == null)
return 0;
return ii.intValue();
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
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 Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false; | }
/** Set Usable Life - Months.
@param UseLifeMonths
Months of the usable life of the asset
*/
public void setUseLifeMonths (int UseLifeMonths)
{
set_Value (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_Value (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();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Group_Acct.java | 1 |
请完成以下Java代码 | public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitaets-Art.
@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());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_AD_TriggerUI.java | 1 |
请完成以下Java代码 | public TextAnnotation newInstance(ModelTypeInstanceContext context) {
return new TextAnnotationImpl(context);
}
});
textFormatAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_TEXT_FORMAT)
.defaultValue("text/plain")
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
textChild = sequenceBuilder.element(Text.class)
.build();
typeBuilder.build();
}
public TextAnnotationImpl(ModelTypeInstanceContext context) { | super(context);
}
public String getTextFormat() {
return textFormatAttribute.getValue(this);
}
public void setTextFormat(String textFormat) {
textFormatAttribute.setValue(this, textFormat);
}
public Text getText() {
return textChild.getChild(this);
}
public void setText(Text text) {
textChild.setChild(this, text);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\TextAnnotationImpl.java | 1 |
请完成以下Java代码 | Map<String, Object> getJson() {
Map<String, Object> result = new HashMap<>();
result.put("firstname", "Dave");
result.put("lastname", "Matthews");
return result;
}
/**
* Returns the payload of {@link #getJson()} wrapped into another element to simulate a change in the representation.
*
* @return
*/
@GetMapping(path = "/changed", produces = MediaType.APPLICATION_JSON_VALUE)
Map<String, Object> getChangedJson() {
return Collections.singletonMap("user", getJson());
}
/**
* Returns a simple XML payload.
*
* @return
*/
@GetMapping(path = "/", produces = MediaType.APPLICATION_XML_VALUE)
String getXml() {
return "<user>".concat(XML_PAYLOAD).concat("</user>");
}
/**
* Returns the payload of {@link #getXml()} wrapped into another XML element to simulate a change in the
* representation structure.
*
* @return
*/
@GetMapping(path = "/changed", produces = MediaType.APPLICATION_XML_VALUE)
String getChangedXml() {
return "<user><username>".concat(XML_PAYLOAD).concat("</username></user>");
} | /**
* The projection interface using XPath and JSON Path expression to selectively pick elements from the payload.
*
* @author Oliver Gierke
*/
@ProjectedPayload
public interface UserPayload {
@XBRead("//firstname")
@JsonPath("$..firstname")
String getFirstname();
@XBRead("//lastname")
@JsonPath("$..lastname")
String getLastname();
}
} | repos\spring-data-examples-main\web\projection\src\main\java\example\users\UserController.java | 1 |
请完成以下Java代码 | public class Decision extends DRGElement {
protected String question;
protected String allowedAnswers;
protected InformationItem variable;
protected List<InformationRequirement> requiredDecisions = new ArrayList<>();
protected List<InformationRequirement> requiredInputs = new ArrayList<>();
protected List<AuthorityRequirement> authorityRequirements = new ArrayList<>();
protected Expression expression;
protected boolean forceDMN11;
@JsonIgnore
protected DmnDefinition dmnDefinition;
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getAllowedAnswers() {
return allowedAnswers;
}
public void setAllowedAnswers(String allowedAnswers) {
this.allowedAnswers = allowedAnswers;
}
public InformationItem getVariable() {
return variable;
}
public void setVariable(InformationItem variable) {
this.variable = variable;
}
public List<InformationRequirement> getRequiredDecisions() {
return requiredDecisions;
}
public void setRequiredDecisions(List<InformationRequirement> requiredDecisions) {
this.requiredDecisions = requiredDecisions;
}
public void addRequiredDecision(InformationRequirement requiredDecision) {
this.requiredDecisions.add(requiredDecision);
}
public List<InformationRequirement> getRequiredInputs() {
return requiredInputs; | }
public void setRequiredInputs(List<InformationRequirement> requiredInputs) {
this.requiredInputs = requiredInputs;
}
public void addRequiredInput(InformationRequirement requiredInput) {
this.requiredInputs.add(requiredInput);
}
public List<AuthorityRequirement> getAuthorityRequirements() {
return authorityRequirements;
}
public void setAuthorityRequirements(List<AuthorityRequirement> authorityRequirements) {
this.authorityRequirements = authorityRequirements;
}
public void addAuthorityRequirement(AuthorityRequirement authorityRequirement) {
this.authorityRequirements.add(authorityRequirement);
}
public Expression getExpression() {
return expression;
}
public void setExpression(Expression expression) {
this.expression = expression;
}
public boolean isForceDMN11() {
return forceDMN11;
}
public void setForceDMN11(boolean forceDMN11) {
this.forceDMN11 = forceDMN11;
}
@JsonIgnore
public DmnDefinition getDmnDefinition() {
return dmnDefinition;
}
public void setDmnDefinition(DmnDefinition dmnDefinition) {
this.dmnDefinition = dmnDefinition;
}
} | repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\Decision.java | 1 |
请完成以下Java代码 | public boolean shouldFilter() {
String requestUri = RequestContext.getCurrentContext().getRequest().getRequestURI();
String contextPath = RequestContext.getCurrentContext().getRequest().getContextPath();
// If the request Uri does not start with the path of the authorized endpoints, we block the request
for (Route route : routeLocator.getRoutes()) {
String serviceUrl = contextPath + route.getFullPath();
String serviceName = route.getId();
// If this route correspond to the current request URI
// We do a substring to remove the "**" at the end of the route URL
if (requestUri.startsWith(serviceUrl.substring(0, serviceUrl.length() - 2))) {
return !isAuthorizedRequest(serviceUrl, serviceName, requestUri);
}
}
return true;
}
private boolean isAuthorizedRequest(String serviceUrl, String serviceName, String requestUri) {
Map<String, List<String>> authorizedMicroservicesEndpoints = jHipsterProperties.getGateway()
.getAuthorizedMicroservicesEndpoints();
// If the authorized endpoints list was left empty for this route, all access are allowed
if (authorizedMicroservicesEndpoints.get(serviceName) == null) {
log.debug("Access Control: allowing access for {}, as no access control policy has been set up for " +
"service: {}", requestUri, serviceName);
return true;
} else { | List<String> authorizedEndpoints = authorizedMicroservicesEndpoints.get(serviceName);
// Go over the authorized endpoints to control that the request URI matches it
for (String endpoint : authorizedEndpoints) {
// We do a substring to remove the "**/" at the end of the route URL
String gatewayEndpoint = serviceUrl.substring(0, serviceUrl.length() - 3) + endpoint;
if (requestUri.startsWith(gatewayEndpoint)) {
log.debug("Access Control: allowing access for {}, as it matches the following authorized " +
"microservice endpoint: {}", requestUri, gatewayEndpoint);
return true;
}
}
}
return false;
}
@Override
public Object run() {
RequestContext ctx = RequestContext.getCurrentContext();
ctx.setResponseStatusCode(HttpStatus.FORBIDDEN.value());
ctx.setSendZuulResponse(false);
log.debug("Access Control: filtered unauthorized access on endpoint {}", ctx.getRequest().getRequestURI());
return null;
}
} | repos\tutorials-master\jhipster-modules\jhipster-uaa\gateway\src\main\java\com\baeldung\jhipster\gateway\gateway\accesscontrol\AccessControlFilter.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_API_Request_Audit getAPI_Request_Audit()
{
return get_ValueAsPO(COLUMNNAME_API_Request_Audit_ID, org.compiere.model.I_API_Request_Audit.class);
}
@Override
public void setAPI_Request_Audit(final org.compiere.model.I_API_Request_Audit API_Request_Audit)
{
set_ValueFromPO(COLUMNNAME_API_Request_Audit_ID, org.compiere.model.I_API_Request_Audit.class, API_Request_Audit);
}
@Override
public void setAPI_Request_Audit_ID (final int API_Request_Audit_ID)
{
if (API_Request_Audit_ID < 1)
set_Value (COLUMNNAME_API_Request_Audit_ID, null);
else
set_Value (COLUMNNAME_API_Request_Audit_ID, API_Request_Audit_ID);
}
@Override
public int getAPI_Request_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_API_Request_Audit_ID);
}
@Override
public void setAPI_Response_Audit_ID (final int API_Response_Audit_ID)
{
if (API_Response_Audit_ID < 1)
set_ValueNoCheck (COLUMNNAME_API_Response_Audit_ID, null);
else
set_ValueNoCheck (COLUMNNAME_API_Response_Audit_ID, API_Response_Audit_ID);
}
@Override
public int getAPI_Response_Audit_ID()
{
return get_ValueAsInt(COLUMNNAME_API_Response_Audit_ID);
}
@Override | public void setBody (final @Nullable java.lang.String Body)
{
set_Value (COLUMNNAME_Body, Body);
}
@Override
public java.lang.String getBody()
{
return get_ValueAsString(COLUMNNAME_Body);
}
@Override
public void setHttpCode (final @Nullable java.lang.String HttpCode)
{
set_Value (COLUMNNAME_HttpCode, HttpCode);
}
@Override
public java.lang.String getHttpCode()
{
return get_ValueAsString(COLUMNNAME_HttpCode);
}
@Override
public void setHttpHeaders (final @Nullable java.lang.String HttpHeaders)
{
set_Value (COLUMNNAME_HttpHeaders, HttpHeaders);
}
@Override
public java.lang.String getHttpHeaders()
{
return get_ValueAsString(COLUMNNAME_HttpHeaders);
}
@Override
public void setTime (final @Nullable java.sql.Timestamp Time)
{
set_Value (COLUMNNAME_Time, Time);
}
@Override
public java.sql.Timestamp getTime()
{
return get_ValueAsTimestamp(COLUMNNAME_Time);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_API_Response_Audit.java | 1 |
请完成以下Java代码 | public DecisionExecutionAuditContainer executeWithAuditTrail() {
return decisionService.executeWithAuditTrail(this);
}
@Override
public DecisionExecutionAuditContainer executeDecisionWithAuditTrail() {
return decisionService.executeDecisionWithAuditTrail(this);
}
@Override
public DecisionServiceExecutionAuditContainer executeDecisionServiceWithAuditTrail() {
return decisionService.executeDecisionServiceWithAuditTrail(this);
}
public String getDecisionKey() {
return decisionKey;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public String getInstanceId() {
return instanceId;
}
public String getExecutionId() {
return executionId;
}
public String getActivityId() {
return activityId;
}
public String getScopeType() {
return scopeType;
}
public String getTenantId() { | return tenantId;
}
public boolean isFallbackToDefaultTenant() {
return this.fallbackToDefaultTenant;
}
public Map<String, Object> getVariables() {
return variables;
}
@Override
public ExecuteDecisionContext buildExecuteDecisionContext() {
ExecuteDecisionContext executeDecisionContext = new ExecuteDecisionContext();
executeDecisionContext.setDecisionKey(decisionKey);
executeDecisionContext.setParentDeploymentId(parentDeploymentId);
executeDecisionContext.setInstanceId(instanceId);
executeDecisionContext.setExecutionId(executionId);
executeDecisionContext.setActivityId(activityId);
executeDecisionContext.setScopeType(scopeType);
executeDecisionContext.setVariables(variables);
executeDecisionContext.setTenantId(tenantId);
executeDecisionContext.setFallbackToDefaultTenant(fallbackToDefaultTenant);
executeDecisionContext.setDisableHistory(disableHistory);
return executeDecisionContext;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\ExecuteDecisionBuilderImpl.java | 1 |
请完成以下Java代码 | public int available() throws IOException {
return in().available();
}
@Override
public boolean markSupported() {
try {
return in().markSupported();
}
catch (IOException ex) {
return false;
}
}
@Override
public synchronized void mark(int readLimit) {
try {
in().mark(readLimit);
}
catch (IOException ex) {
// Ignore
}
}
@Override
public synchronized void reset() throws IOException {
in().reset();
}
private InputStream in() throws IOException {
InputStream in = this.in;
if (in == null) {
synchronized (this) {
in = this.in;
if (in == null) {
in = getDelegateInputStream();
this.in = in;
}
}
}
return in; | }
@Override
public void close() throws IOException {
InputStream in = this.in;
if (in != null) {
synchronized (this) {
in = this.in;
if (in != null) {
in.close();
}
}
}
}
protected abstract InputStream getDelegateInputStream() throws IOException;
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\protocol\jar\LazyDelegatingInputStream.java | 1 |
请完成以下Java代码 | public class GroupsClaimMapper {
private final String authoritiesPrefix;
private final String groupsClaim;
private final Map<String, List<String>> groupToAuthorities;
public GroupsClaimMapper(String authoritiesPrefix, String groupsClaim, Map<String, List<String>> groupToAuthorities) {
this.authoritiesPrefix = authoritiesPrefix;
this.groupsClaim = groupsClaim;
this.groupToAuthorities = Collections.unmodifiableMap(groupToAuthorities);
}
public Collection<? extends GrantedAuthority> mapAuthorities(ClaimAccessor source) {
List<String> groups = source.getClaimAsStringList(groupsClaim);
if ( groups == null || groups.isEmpty()) {
return Collections.emptyList();
}
List<GrantedAuthority> result = new ArrayList<>();
for( String g : groups) { | List<String> authNames = groupToAuthorities.get(g);
if ( authNames == null ) {
continue;
}
List<SimpleGrantedAuthority> mapped = authNames.stream()
.map( s -> authoritiesPrefix + s)
.map( SimpleGrantedAuthority::new)
.collect(Collectors.toList());
result.addAll(mapped);
}
return result;
}
} | repos\tutorials-master\spring-security-modules\spring-security-azuread\src\main\java\com\baeldung\security\azuread\support\GroupsClaimMapper.java | 1 |
请完成以下Java代码 | public class X_M_Package_HU extends org.compiere.model.PO implements I_M_Package_HU, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = 576149678L;
/** Standard Constructor */
public X_M_Package_HU (final Properties ctx, final int M_Package_HU_ID, @Nullable final String trxName)
{
super (ctx, M_Package_HU_ID, trxName);
}
/** Load Constructor */
public X_M_Package_HU (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public de.metas.handlingunits.model.I_M_HU getM_HU()
{
return get_ValueAsPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setM_HU(final de.metas.handlingunits.model.I_M_HU M_HU)
{
set_ValueFromPO(COLUMNNAME_M_HU_ID, de.metas.handlingunits.model.I_M_HU.class, M_HU);
}
@Override
public void setM_HU_ID (final int M_HU_ID)
{
if (M_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_ID, M_HU_ID);
}
@Override
public int getM_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_ID);
}
@Override
public void setM_Package_HU_ID (final int M_Package_HU_ID)
{
if (M_Package_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Package_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Package_HU_ID, M_Package_HU_ID);
}
@Override
public int getM_Package_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Package_HU_ID);
}
@Override
public org.compiere.model.I_M_Package getM_Package()
{
return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class);
}
@Override
public void setM_Package(final org.compiere.model.I_M_Package M_Package) | {
set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package);
}
@Override
public void setM_Package_ID (final int M_Package_ID)
{
if (M_Package_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Package_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Package_ID, M_Package_ID);
}
@Override
public int getM_Package_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Package_ID);
}
@Override
public void setM_PickingSlot_ID (final int M_PickingSlot_ID)
{
if (M_PickingSlot_ID < 1)
set_Value (COLUMNNAME_M_PickingSlot_ID, null);
else
set_Value (COLUMNNAME_M_PickingSlot_ID, M_PickingSlot_ID);
}
@Override
public int getM_PickingSlot_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PickingSlot_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Package_HU.java | 1 |
请完成以下Java代码 | public static EngineInfo retry(String resourceUrl) {
LOGGER.debug("retying initializing of resource {}", resourceUrl);
try {
return initDmnEngineFromResource(new URL(resourceUrl));
} catch (MalformedURLException e) {
throw new FlowableException("invalid url: " + resourceUrl, e);
}
}
/**
* provides access to dmn engine to application clients in a managed server environment.
*/
public static Map<String, DmnEngine> getDmnEngines() {
return dmnEngines;
}
/**
* closes all dmn engines. This method should be called when the server shuts down.
*/
public static synchronized void destroy() {
if (isInitialized()) {
Map<String, DmnEngine> engines = new HashMap<>(dmnEngines);
dmnEngines = new HashMap<>();
for (String dmnEngineName : engines.keySet()) {
DmnEngine dmnEngine = engines.get(dmnEngineName);
try {
dmnEngine.close();
} catch (Exception e) {
LOGGER.error("exception while closing {}", (dmnEngineName == null ? "the default dmn engine" : "dmn engine " + dmnEngineName), e);
}
} | dmnEngineInfosByName.clear();
dmnEngineInfosByResourceUrl.clear();
dmnEngineInfos.clear();
setInitialized(false);
}
}
public static boolean isInitialized() {
return isInitialized;
}
public static void setInitialized(boolean isInitialized) {
DmnEngines.isInitialized = isInitialized;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\DmnEngines.java | 1 |
请完成以下Java代码 | public void requestUpdateFromServerPeer()
{
msv3ServerPeerService.requestAllUpdates();
}
@PutMapping("/logLevel")
public void setLoggerLevel(@RequestBody final String logLevelStr)
{
final Level level = toSLF4JLevel(logLevelStr);
getSLF4JRootLogger().setLevel(level);
}
@GetMapping("/logLevel")
public String getLoggerLevel()
{
Level level = getSLF4JRootLogger().getLevel();
return level != null ? level.toString() : null;
} | private ch.qos.logback.classic.Logger getSLF4JRootLogger()
{
return (ch.qos.logback.classic.Logger)ROOT_LOGGER;
}
private static Level toSLF4JLevel(final String logLevelStr)
{
if (logLevelStr == null)
{
return null;
}
return Level.toLevel(logLevelStr.trim());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\MSV3ServerRestEndpoint.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public EthGetTransactionCount getTransactionCount() {
EthGetTransactionCount result = new EthGetTransactionCount();
try {
result = this.web3j.ethGetTransactionCount(DEFAULT_ADDRESS, DefaultBlockParameter.valueOf("latest")).sendAsync().get();
} catch (Exception ex) {
System.out.println(GENERIC_EXCEPTION);
}
return result;
}
public EthGetBalance getEthBalance() {
EthGetBalance result = new EthGetBalance();
try {
result = this.web3j.ethGetBalance(DEFAULT_ADDRESS, DefaultBlockParameter.valueOf("latest")).sendAsync().get();
} catch (Exception ex) {
System.out.println(GENERIC_EXCEPTION);
}
return result;
}
public String fromScratchContractExample() {
String contractAddress = "";
try {
//Create a wallet
WalletUtils.generateNewWalletFile("PASSWORD", new File("/path/to/destination"), true);
//Load the credentials from it
Credentials credentials = WalletUtils.loadCredentials("PASSWORD", "/path/to/walletfile");
//Deploy contract to address specified by wallet
Example contract = Example.deploy(this.web3j,
credentials,
ManagedTransaction.GAS_PRICE,
Contract.GAS_LIMIT).send();
//Het the address
contractAddress = contract.getContractAddress();
} catch (Exception ex) {
System.out.println(PLEASE_SUPPLY_REAL_DATA);
return PLEASE_SUPPLY_REAL_DATA;
} | return contractAddress;
}
@Async
public String sendTx() {
String transactionHash = "";
try {
List inputParams = new ArrayList();
List outputParams = new ArrayList();
Function function = new Function("fuctionName", inputParams, outputParams);
String encodedFunction = FunctionEncoder.encode(function);
BigInteger nonce = BigInteger.valueOf(100);
BigInteger gasprice = BigInteger.valueOf(100);
BigInteger gaslimit = BigInteger.valueOf(100);
Transaction transaction = Transaction.createFunctionCallTransaction("FROM_ADDRESS", nonce, gasprice, gaslimit, "TO_ADDRESS", encodedFunction);
org.web3j.protocol.core.methods.response.EthSendTransaction transactionResponse = web3j.ethSendTransaction(transaction).sendAsync().get();
transactionHash = transactionResponse.getTransactionHash();
} catch (Exception ex) {
System.out.println(PLEASE_SUPPLY_REAL_DATA);
return PLEASE_SUPPLY_REAL_DATA;
}
return transactionHash;
}
} | repos\tutorials-master\ethereum\src\main\java\com\baeldung\web3j\services\Web3Service.java | 2 |
请完成以下Java代码 | public static RemoteToLocalSyncResult error(@NonNull final DataRecord datarecord, String errorMessage)
{
return RemoteToLocalSyncResult.builder()
.synchedDataRecord(datarecord)
.remoteToLocalStatus(RemoteToLocalStatus.ERROR)
.errorMessage(errorMessage)
.build();
}
public enum RemoteToLocalStatus
{
/** See {@link RemoteToLocalSyncResult#deletedOnRemotePlatform(DataRecord)}. */
DELETED_ON_REMOTE_PLATFORM,
/** See {@link RemoteToLocalSyncResult#notYetAddedToRemotePlatform(DataRecord)}. */
NOT_YET_ADDED_TO_REMOTE_PLATFORM,
/** See {@link RemoteToLocalSyncResult#obtainedRemoteId(DataRecord)}. */
OBTAINED_REMOTE_ID,
/** See {@link RemoteToLocalSyncResult#obtainedRemoteEmail(DataRecord)}. */
OBTAINED_REMOTE_EMAIL,
/** See {@link RemoteToLocalSyncResult#obtainedEmailBounceInfo(DataRecord)}. */
OBTAINED_EMAIL_BOUNCE_INFO,
OBTAINED_NEW_CONTACT_PERSON, NO_CHANGES, OBTAINED_OTHER_REMOTE_DATA, ERROR; | }
RemoteToLocalStatus remoteToLocalStatus;
String errorMessage;
DataRecord synchedDataRecord;
@Builder
private RemoteToLocalSyncResult(
@NonNull final DataRecord synchedDataRecord,
@Nullable final RemoteToLocalStatus remoteToLocalStatus,
@Nullable final String errorMessage)
{
this.synchedDataRecord = synchedDataRecord;
this.remoteToLocalStatus = remoteToLocalStatus;
this.errorMessage = errorMessage;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java\de\metas\marketing\base\model\RemoteToLocalSyncResult.java | 1 |
请完成以下Java代码 | private static ShipmentCandidateRowUserChangeRequest toUserChangeRequest(@NonNull final List<JSONDocumentChangedEvent> fieldChangeRequests)
{
Check.assumeNotEmpty(fieldChangeRequests, "fieldChangeRequests is not empty");
final ShipmentCandidateRowUserChangeRequestBuilder builder = ShipmentCandidateRowUserChangeRequest.builder();
for (final JSONDocumentChangedEvent fieldChangeRequest : fieldChangeRequests)
{
final String fieldName = fieldChangeRequest.getPath();
if (ShipmentCandidateRow.FIELD_qtyToDeliverUserEntered.equals(fieldName))
{
builder.qtyToDeliverUserEntered(fieldChangeRequest.getValueAsBigDecimal());
}
else if (ShipmentCandidateRow.FIELD_qtyToDeliverCatchOverride.equals(fieldName))
{
builder.qtyToDeliverCatchOverride(fieldChangeRequest.getValueAsBigDecimal());
}
else if (ShipmentCandidateRow.FIELD_asi.equals(fieldName))
{
builder.asi(fieldChangeRequest.getValueAsIntegerLookupValue());
}
}
return builder.build();
}
private void changeRow(
@NonNull final DocumentId rowId,
@NonNull final UnaryOperator<ShipmentCandidateRow> mapper)
{
if (!rowIds.contains(rowId))
{
throw new EntityNotFoundException(rowId.toJson());
}
rowsById.compute(rowId, (key, oldRow) -> {
if (oldRow == null)
{ | throw new EntityNotFoundException(rowId.toJson());
}
return mapper.apply(oldRow);
});
}
Optional<ShipmentScheduleUserChangeRequestsList> createShipmentScheduleUserChangeRequestsList()
{
final ImmutableList<ShipmentScheduleUserChangeRequest> userChanges = rowsById.values()
.stream()
.map(row -> row.createShipmentScheduleUserChangeRequest().orElse(null))
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
return !userChanges.isEmpty()
? Optional.of(ShipmentScheduleUserChangeRequestsList.of(userChanges))
: Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\shipment_candidates_editor\ShipmentCandidateRows.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void prepareContext(@NonNull final Exchange exchange)
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
final PrintingClientContext context = PrintingClientContext.builder()
.printingQueueId(request.getParameters().get(ExternalSystemConstants.PARAM_PRINTING_QUEUE_ID))
.targetDirectory(request.getParameters().get(ExternalSystemConstants.PARAM_TARGET_DIRECTORY))
.build();
exchange.setProperty(PrintingClientConstants.PRINTING_CLIENT_CONTEXT, context);
}
private void getPrintingData(@NonNull final Exchange exchange){
final PrintingClientContext context = exchange.getProperty(PrintingClientConstants.PRINTING_CLIENT_CONTEXT, PrintingClientContext.class);
exchange.getIn().removeHeaders("*");
exchange.getIn().setHeader(HEADER_PRINTING_QUEUE_ID, context.getPrintingQueueId());
exchange.getIn().setBody(null);
}
private void setPrintingResult(@NonNull final Exchange exchange)
{
final Object printingDataCandidate = exchange.getIn().getBody();
if (!(printingDataCandidate instanceof JsonPrintingDataResponse))
{
throw new RuntimeCamelException("API Request " + MF_PRINT_V2_BASE + "getPrintingData/" + "{" + HEADER_PRINTING_QUEUE_ID + "}" + "expected result to be instanceof JsonPrintingDataResponse."
+ " However, it is " + (printingDataCandidate == null ? "null" : printingDataCandidate.getClass().getName())); | }
final JsonPrintingDataResponse request = (JsonPrintingDataResponse) printingDataCandidate;
final PrintingClientContext context = exchange.getProperty(PrintingClientConstants.PRINTING_CLIENT_CONTEXT, PrintingClientContext.class);
try
{
printingClientPDFFileStorer.storeInFileSystem(request, context.getTargetDirectory());
}
catch (final PrintingException e)
{
final JsonPrintingResultRequest response = JsonPrintingResultRequest.builder()
.processed(false)
.errorMsg("ERROR: " + e.getMessage())
.build();
exchange.getIn().setBody(response);
return;
}
final JsonPrintingResultRequest response = JsonPrintingResultRequest.builder()
.processed(true)
.build();
exchange.getIn().setBody(response);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-printingclient\src\main\java\de\metas\camel\externalsystems\PrintingClientCamelRoute.java | 2 |
请完成以下Java代码 | public void deleteDocTypeAccess(@NonNull final I_C_DocType docTypeRecord)
{
Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_Document_Action_Access.class)
.addEqualsFilter(I_AD_Document_Action_Access.COLUMN_C_DocType_ID, docTypeRecord.getC_DocType_ID())
.create()
.delete();
}
@ModelChange(
timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = { I_C_DocType.COLUMNNAME_C_DocType_Invoicing_Pool_ID, I_C_DocType.COLUMNNAME_IsSOTrx })
public void validateInvoicingPoolAssignment(@NonNull final I_C_DocType docType)
{
Optional.ofNullable(DocTypeInvoicingPoolId.ofRepoIdOrNull(docType.getC_DocType_Invoicing_Pool_ID()))
.map(docTypeInvoicingPoolService::getById)
.ifPresent(docTypeInvoicingPool -> {
if (!docTypeInvoicingPool.isActive())
{ | throw new AdempiereException(MSG_INACTIVE_INVOICING_POOL)
.markAsUserValidationError()
.appendParametersToMessage()
.setParameter("DocTypeInvoicingPool.Name", docTypeInvoicingPool.getName())
.setParameter("DocTypeId", docType.getC_DocType_ID());
}
if (docTypeInvoicingPool.getIsSoTrx().toBoolean() != docType.isSOTrx())
{
throw new AdempiereException(MSG_DIFFERENT_SO_TRX_INVOICING_POOL_DOCUMENT_TYPE)
.markAsUserValidationError()
.appendParametersToMessage()
.setParameter("DocTypeInvoicingPool.Name", docTypeInvoicingPool.getName())
.setParameter("DocTypeId", docType.getC_DocType_ID());
}
});
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\interceptor\C_DocType.java | 1 |
请完成以下Java代码 | public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
return handler.calculatePriceAndTax(ic);
}
@Override
public void setBPartnerData(@NonNull final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setBPartnerData(ic);
}
@Override
public void setInvoiceScheduleAndDateToInvoice(@NonNull final I_C_Invoice_Candidate icRecord)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(icRecord);
handler.setInvoiceScheduleAndDateToInvoice(icRecord);
}
@Override
public void setPickedData(final I_C_Invoice_Candidate ic)
{
final InvoiceCandidateRecordService invoiceCandidateRecordService = SpringContextHolder.instance.getBean(InvoiceCandidateRecordService.class); | final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setShipmentSchedule(ic);
final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoIdOrNull(ic.getM_ShipmentSchedule_ID());
if (shipmentScheduleId == null)
{
return;
}
final StockQtyAndUOMQty qtysPicked = invoiceCandidateRecordService.ofRecord(ic).computeQtysPicked();
ic.setQtyPicked(qtysPicked.getStockQty().toBigDecimal());
ic.setQtyPickedInUOM(qtysPicked.getUOMQtyNotNull().toBigDecimal());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceCandidateHandlerBL.java | 1 |
请完成以下Java代码 | public static InstanceExchangeFilterFunction handleCookies(final PerInstanceCookieStore store) {
return (instance, request, next) -> {
// we need an absolute URL to be able to deal with cookies
if (request.url().isAbsolute()) {
return next.exchange(enrichRequestWithStoredCookies(instance.getId(), request, store))
.map((response) -> storeCookiesFromResponse(instance.getId(), request, response, store));
}
return next.exchange(request);
};
}
private static ClientRequest enrichRequestWithStoredCookies(final InstanceId instId, final ClientRequest request,
final PerInstanceCookieStore store) {
final MultiValueMap<String, String> storedCookies = store.get(instId, request.url(), request.headers());
if (CollectionUtils.isEmpty(storedCookies)) {
log.trace("No cookies found for request [url={}]", request.url());
return request;
}
log.trace("Cookies found for request [url={}]", request.url()); | return ClientRequest.from(request).cookies((cm) -> cm.addAll(storedCookies)).build();
}
private static ClientResponse storeCookiesFromResponse(final InstanceId instId, final ClientRequest request,
final ClientResponse response, final PerInstanceCookieStore store) {
final HttpHeaders headers = response.headers().asHttpHeaders();
log.trace("Searching for cookies in header values of response [url={},headerValues={}]", request.url(),
headers);
store.put(instId, request.url(), headers);
return response;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\web\client\InstanceExchangeFilterFunctions.java | 1 |
请完成以下Java代码 | private static Map<String, Object> getConfiguration(String issuer, RestOperations rest, UriComponents... uris) {
String errorMessage = "Unable to resolve the Configuration with the provided Issuer of " + "\"" + issuer + "\"";
for (UriComponents uri : uris) {
try {
RequestEntity<Void> request = RequestEntity.get(uri.toUriString()).build();
ResponseEntity<Map<String, Object>> response = rest.exchange(request, STRING_OBJECT_MAP);
Map<String, Object> configuration = response.getBody();
Assert.isTrue(configuration.get("jwks_uri") != null, "The public JWK set URI must not be null");
return configuration;
}
catch (IllegalArgumentException ex) {
throw ex;
}
catch (RuntimeException ex) {
if (!(ex instanceof HttpClientErrorException
&& ((HttpClientErrorException) ex).getStatusCode().is4xxClientError())) {
throw new IllegalArgumentException(errorMessage, ex);
}
// else try another endpoint
}
}
throw new IllegalArgumentException(errorMessage);
}
static UriComponents oidc(String issuer) {
UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build();
// @formatter:off
return UriComponentsBuilder.newInstance().uriComponents(uri)
.replacePath(uri.getPath() + OIDC_METADATA_PATH)
.build(); | // @formatter:on
}
static UriComponents oidcRfc8414(String issuer) {
UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build();
// @formatter:off
return UriComponentsBuilder.newInstance().uriComponents(uri)
.replacePath(OIDC_METADATA_PATH + uri.getPath())
.build();
// @formatter:on
}
static UriComponents oauth(String issuer) {
UriComponents uri = UriComponentsBuilder.fromUriString(issuer).build();
// @formatter:off
return UriComponentsBuilder.newInstance().uriComponents(uri)
.replacePath(OAUTH_METADATA_PATH + uri.getPath())
.build();
// @formatter:on
}
} | repos\spring-security-main\oauth2\oauth2-jose\src\main\java\org\springframework\security\oauth2\jwt\JwtDecoderProviderConfigurationUtils.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getPRICETYPE() {
return pricetype;
}
/**
* Sets the value of the pricetype property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPRICETYPE(String value) {
this.pricetype = value;
}
/**
* Gets the value of the pricebasis property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPRICEBASIS() {
return pricebasis;
}
/**
* Sets the value of the pricebasis property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPRICEBASIS(String value) {
this.pricebasis = value;
}
/**
* Gets the value of the pricemeasureunit property.
*
* @return
* possible object is | * {@link String }
*
*/
public String getPRICEMEASUREUNIT() {
return pricemeasureunit;
}
/**
* Sets the value of the pricemeasureunit property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPRICEMEASUREUNIT(String value) {
this.pricemeasureunit = value;
}
/**
* Gets the value of the currency property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCURRENCY() {
return currency;
}
/**
* Sets the value of the currency property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCURRENCY(String value) {
this.currency = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DPRIC1.java | 2 |
请完成以下Java代码 | public boolean isDocumentTable(final String tableName)
{
final Class<?> clazz = TableModelClassLoader.instance.getClass(tableName);
if (clazz == null)
{
return false;
}
if (!IDocument.class.isAssignableFrom(clazz))
{
return false;
}
return true;
}
@Override
public int getC_DocType_ID(final Properties ctx, final int AD_Table_ID, final int Record_ID)
{
if (AD_Table_ID <= 0 || Record_ID <= 0)
return -1;
final POInfo poInfo = POInfo.getPOInfo(ctx, AD_Table_ID);
final String keyColumn = poInfo.getKeyColumnName();
if (keyColumn == null)
{
return -1;
}
final String tableName = poInfo.getTableName();
int C_DocType_ID = -1;
if (poInfo.hasColumnName("C_DocType_ID"))
{
final String sql = "SELECT C_DocType_ID FROM " + tableName + " WHERE " + keyColumn + "=?";
C_DocType_ID = DB.getSQLValueEx(ITrx.TRXNAME_None, sql, Record_ID);
}
if (C_DocType_ID <= 0 && poInfo.hasColumnName("C_DocTypeTarget_ID"))
{
final String sql = "SELECT C_DocTypeTarget_ID FROM " + tableName + " WHERE " + keyColumn + "=?";
C_DocType_ID = DB.getSQLValueEx(ITrx.TRXNAME_None, sql, Record_ID);
}
if (C_DocType_ID <= 0)
{
C_DocType_ID = -1;
}
return C_DocType_ID;
}
@Nullable
@Override
protected String retrieveString(final int adTableId, final int recordId, final String columnName)
{
if (adTableId <= 0 || recordId <= 0)
{
return null;
}
final POInfo poInfo = POInfo.getPOInfo(adTableId);
if (poInfo == null)
{
throw new AdempiereException("No POInfo found for AD_Table_ID=" + adTableId);
}
final String keyColumn = poInfo.getKeyColumnName();
if (keyColumn == null)
{ | return null;
}
String value = null;
if (poInfo.hasColumnName(columnName))
{
final String sql = "SELECT " + columnName + " FROM " + poInfo.getTableName() + " WHERE " + keyColumn + "=?";
value = DB.getSQLValueStringEx(ITrx.TRXNAME_None, sql, recordId);
}
return value;
}
@Override
protected Object retrieveModelOrNull(final Properties ctx, final int adTableId, final int recordId)
{
final String tableName = Services.get(IADTableDAO.class).retrieveTableName(adTableId);
final String trxName = ITrx.TRXNAME_None;
return TableModelLoader.instance.getPO(ctx, tableName, recordId, trxName);
}
@Nullable
@Override
public LocalDate getDocumentDate(final Properties ctx, final int adTableID, final int recordId)
{
final Object model = retrieveModelOrNull(ctx, adTableID, recordId);
return getDocumentDate(model);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\DocumentBL.java | 1 |
请完成以下Java代码 | public class OAuth2AuthorizationCodeAuthenticationToken extends OAuth2AuthorizationGrantAuthenticationToken {
private final String code;
private final String redirectUri;
/**
* Constructs an {@code OAuth2AuthorizationCodeAuthenticationToken} using the provided
* parameters.
* @param code the authorization code
* @param clientPrincipal the authenticated client principal
* @param redirectUri the redirect uri
* @param additionalParameters the additional parameters
*/
public OAuth2AuthorizationCodeAuthenticationToken(String code, Authentication clientPrincipal,
@Nullable String redirectUri, @Nullable Map<String, Object> additionalParameters) {
super(AuthorizationGrantType.AUTHORIZATION_CODE, clientPrincipal, additionalParameters);
Assert.hasText(code, "code cannot be empty");
this.code = code;
this.redirectUri = redirectUri;
}
/**
* Returns the authorization code. | * @return the authorization code
*/
public String getCode() {
return this.code;
}
/**
* Returns the redirect uri.
* @return the redirect uri
*/
@Nullable
public String getRedirectUri() {
return this.redirectUri;
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2AuthorizationCodeAuthenticationToken.java | 1 |
请完成以下Java代码 | public class Employee {
private String name;
private int salary;
private String department;
private String sex;
public Employee(String name, int salary, String department, String sex) {
this.name = name;
this.salary = salary;
this.department = department;
this.sex = sex;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getSalary() {
return salary;
} | public void setSalary(int salary) {
this.salary = salary;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
@Override
public String toString() {
return "Employee{" + "name='" + name + '\'' + ", salary=" + salary + ", department='" + department + '\'' +
", sex='" + sex + '\'' + '}';
}
} | repos\tutorials-master\core-java-modules\core-java-9-streams\src\main\java\com\baledung\streams\entity\Employee.java | 1 |
请完成以下Java代码 | public void log(@NonNull final GOClientLogEvent event)
{
try
{
createLogRecord(event);
}
catch (final Exception ex)
{
logger.warn("Failed creating GO log record: {}", event, ex);
}
// Also send it to SLF4J logger
SLF4JGOClientLogger.instance.log(event);
}
private void createLogRecord(@NonNull final GOClientLogEvent event)
{
final I_GO_DeliveryOrder_Log logRecord = InterfaceWrapperHelper.newInstance(I_GO_DeliveryOrder_Log.class);
logRecord.setAction(event.getAction());
logRecord.setGO_ConfigSummary(event.getConfigSummary());
logRecord.setDurationMillis((int)event.getDurationMillis());
if (event.getDeliveryOrderRepoId() > 0) | {
logRecord.setGO_DeliveryOrder_ID(event.getDeliveryOrderRepoId());
}
logRecord.setRequestMessage(event.getRequestAsString());
if (event.getResponseException() != null)
{
logRecord.setIsError(true);
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(event.getResponseException());
logRecord.setAD_Issue_ID(issueId.getRepoId());
}
else
{
logRecord.setIsError(false);
logRecord.setResponseMessage(event.getResponseAsString());
}
InterfaceWrapperHelper.save(logRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java\de\metas\shipper\gateway\go\DatabaseGOClientLogger.java | 1 |
请完成以下Java代码 | public SuspendedJobEntityManager getSuspendedJobEntityManager() {
return processEngineConfiguration.getSuspendedJobEntityManager();
}
public DeadLetterJobEntityManager getDeadLetterJobEntityManager() {
return processEngineConfiguration.getDeadLetterJobEntityManager();
}
public AttachmentEntityManager getAttachmentEntityManager() {
return processEngineConfiguration.getAttachmentEntityManager();
}
public TableDataManager getTableDataManager() {
return processEngineConfiguration.getTableDataManager();
}
public CommentEntityManager getCommentEntityManager() {
return processEngineConfiguration.getCommentEntityManager();
}
public PropertyEntityManager getPropertyEntityManager() {
return processEngineConfiguration.getPropertyEntityManager();
}
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return processEngineConfiguration.getEventSubscriptionEntityManager();
}
public HistoryManager getHistoryManager() {
return processEngineConfiguration.getHistoryManager();
}
public JobManager getJobManager() {
return processEngineConfiguration.getJobManager();
}
// Involved executions ////////////////////////////////////////////////////////
public void addInvolvedExecution(ExecutionEntity executionEntity) {
if (executionEntity.getId() != null) {
involvedExecutions.put(executionEntity.getId(), executionEntity);
}
}
public boolean hasInvolvedExecutions() {
return involvedExecutions.size() > 0;
}
public Collection<ExecutionEntity> getInvolvedExecutions() {
return involvedExecutions.values();
}
// getters and setters
// //////////////////////////////////////////////////////
public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
}
public Throwable getException() {
return exception; | }
public FailedJobCommandFactory getFailedJobCommandFactory() {
return failedJobCommandFactory;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public ActivitiEventDispatcher getEventDispatcher() {
return processEngineConfiguration.getEventDispatcher();
}
public ActivitiEngineAgenda getAgenda() {
return agenda;
}
public Object getResult() {
return resultStack.pollLast();
}
public void setResult(Object result) {
resultStack.add(result);
}
public boolean isReused() {
return reused;
}
public void setReused(boolean reused) {
this.reused = reused;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java | 1 |
请完成以下Java代码 | public void setOldValue (final java.lang.String OldValue)
{
set_Value (COLUMNNAME_OldValue, OldValue);
}
@Override
public java.lang.String getOldValue()
{
return get_ValueAsString(COLUMNNAME_OldValue);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setTextMsg (final java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
@Override
public java.lang.String getTextMsg()
{
return get_ValueAsString(COLUMNNAME_TextMsg);
}
/**
* WFState AD_Reference_ID=305
* Reference name: WF_Instance State
*/
public static final int WFSTATE_AD_Reference_ID=305;
/** NotStarted = ON */ | public static final String WFSTATE_NotStarted = "ON";
/** Running = OR */
public static final String WFSTATE_Running = "OR";
/** Suspended = OS */
public static final String WFSTATE_Suspended = "OS";
/** Completed = CC */
public static final String WFSTATE_Completed = "CC";
/** Aborted = CA */
public static final String WFSTATE_Aborted = "CA";
/** Terminated = CT */
public static final String WFSTATE_Terminated = "CT";
@Override
public void setWFState (final java.lang.String WFState)
{
set_Value (COLUMNNAME_WFState, WFState);
}
@Override
public java.lang.String getWFState()
{
return get_ValueAsString(COLUMNNAME_WFState);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_EventAudit.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DeploymentBuilder activateProcessDefinitionsOn(Date date) {
this.processDefinitionsActivationDate = date;
return this;
}
@Override
public Deployment deploy() {
return repositoryService.deploy(this);
}
// getters and setters //////////////////////////////////////////////////////
public DeploymentEntity getDeployment() {
return deployment;
}
public boolean isProcessValidationEnabled() {
return isProcessValidationEnabled; | }
public boolean isBpmn20XsdValidationEnabled() {
return isBpmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
public Date getProcessDefinitionsActivationDate() {
return processDefinitionsActivationDate;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\repository\DeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public boolean retainAll(Collection<?> collection) {
throw new UnsupportedOperationException();
}
@Override
public boolean contains(Object object) {
for (Object element : internal) {
if (object.equals(element)) {
return true;
}
}
return false;
}
@Override
public boolean containsAll(Collection<?> collection) {
for (Object element : collection)
if (!contains(element)) {
return false;
}
return true;
}
@SuppressWarnings("unchecked")
@Override
public E set(int index, E element) {
E oldElement = (E) internal[index];
internal[index] = element;
return oldElement;
}
@Override
public void clear() {
internal = new Object[0];
}
@Override
public int indexOf(Object object) {
for (int i = 0; i < internal.length; i++) {
if (object.equals(internal[i])) {
return i;
}
}
return -1;
}
@Override
public int lastIndexOf(Object object) {
for (int i = internal.length - 1; i >= 0; i--) {
if (object.equals(internal[i])) {
return i;
}
}
return -1;
}
@SuppressWarnings("unchecked")
@Override | public List<E> subList(int fromIndex, int toIndex) {
Object[] temp = new Object[toIndex - fromIndex];
System.arraycopy(internal, fromIndex, temp, 0, temp.length);
return (List<E>) Arrays.asList(temp);
}
@Override
public Object[] toArray() {
return Arrays.copyOf(internal, internal.length);
}
@SuppressWarnings("unchecked")
@Override
public <T> T[] toArray(T[] array) {
if (array.length < internal.length) {
return (T[]) Arrays.copyOf(internal, internal.length, array.getClass());
}
System.arraycopy(internal, 0, array, 0, internal.length);
if (array.length > internal.length) {
array[internal.length] = null;
}
return array;
}
@Override
public Iterator<E> iterator() {
return new CustomIterator();
}
@Override
public ListIterator<E> listIterator() {
return null;
}
@Override
public ListIterator<E> listIterator(int index) {
// ignored for brevity
return null;
}
private class CustomIterator implements Iterator<E> {
int index;
@Override
public boolean hasNext() {
return index != internal.length;
}
@SuppressWarnings("unchecked")
@Override
public E next() {
E element = (E) CustomList.this.internal[index];
index++;
return element;
}
}
} | repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\list\CustomList.java | 1 |
请完成以下Java代码 | public Set<DocumentId> getChangedOrRemovedRowIds()
{
return Sets.union(getChangedRowIds(), getRemovedRowIds());
}
//
//
//
public static class NotRecordingAddRemoveChangedRowIdsCollector extends AddRemoveChangedRowIdsCollector
{
private NotRecordingAddRemoveChangedRowIdsCollector() {}
@Override
public void collectAddedRowId(final DocumentId rowId) {}
@Override
public Set<DocumentId> getAddedRowIds()
{
throw new IllegalArgumentException("changes are not recorded");
}
@Override
public void collectRemovedRowIds(final Collection<DocumentId> rowIds) {}
@Override
public Set<DocumentId> getRemovedRowIds()
{
throw new IllegalArgumentException("changes are not recorded");
}
@Override
public void collectChangedRowIds(final Collection<DocumentId> rowIds) {}
@Override
public Set<DocumentId> getChangedRowIds()
{
throw new IllegalArgumentException("changes are not recorded");
}
}
//
//
//
@ToString
public static class RecordingAddRemoveChangedRowIdsCollector extends AddRemoveChangedRowIdsCollector
{
private HashSet<DocumentId> addedRowIds;
private HashSet<DocumentId> removedRowIds;
private HashSet<DocumentId> changedRowIds;
private RecordingAddRemoveChangedRowIdsCollector() {}
@Override
public void collectAddedRowId(@NonNull final DocumentId rowId)
{
if (addedRowIds == null)
{
addedRowIds = new HashSet<>();
}
addedRowIds.add(rowId);
}
@Override
public Set<DocumentId> getAddedRowIds()
{ | final HashSet<DocumentId> addedRowIds = this.addedRowIds;
return addedRowIds != null ? addedRowIds : ImmutableSet.of();
}
@Override
public boolean hasAddedRows()
{
final HashSet<DocumentId> addedRowIds = this.addedRowIds;
return addedRowIds != null && !addedRowIds.isEmpty();
}
@Override
public void collectRemovedRowIds(final Collection<DocumentId> rowIds)
{
if (removedRowIds == null)
{
removedRowIds = new HashSet<>(rowIds);
}
else
{
removedRowIds.addAll(rowIds);
}
}
@Override
public Set<DocumentId> getRemovedRowIds()
{
final HashSet<DocumentId> removedRowIds = this.removedRowIds;
return removedRowIds != null ? removedRowIds : ImmutableSet.of();
}
@Override
public void collectChangedRowIds(final Collection<DocumentId> rowIds)
{
if (changedRowIds == null)
{
changedRowIds = new HashSet<>(rowIds);
}
else
{
changedRowIds.addAll(rowIds);
}
}
@Override
public Set<DocumentId> getChangedRowIds()
{
final HashSet<DocumentId> changedRowIds = this.changedRowIds;
return changedRowIds != null ? changedRowIds : ImmutableSet.of();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\AddRemoveChangedRowIdsCollector.java | 1 |
请完成以下Java代码 | public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{ | return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Number Grouping Separator.
@param NumberGroupingSeparator Number Grouping Separator */
@Override
public void setNumberGroupingSeparator (java.lang.String NumberGroupingSeparator)
{
set_Value (COLUMNNAME_NumberGroupingSeparator, NumberGroupingSeparator);
}
/** Get Number Grouping Separator.
@return Number Grouping Separator */
@Override
public java.lang.String getNumberGroupingSeparator ()
{
return (java.lang.String)get_Value(COLUMNNAME_NumberGroupingSeparator);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportFormat.java | 1 |
请完成以下Java代码 | public Builder addAdditionalRelatedProcessDescriptors(@NonNull final List<RelatedProcessDescriptor> relatedProcessDescriptors)
{
additionalRelatedProcessDescriptors.addAll(relatedProcessDescriptors);
return this;
}
public Builder setParameter(@NonNull final String name, @Nullable final Object value)
{
if (value == null)
{
if (parameters != null)
{
parameters.remove(name);
}
}
else
{
if (parameters == null)
{
parameters = new LinkedHashMap<>();
}
parameters.put(name, value);
}
return this;
}
public Builder setParameters(@NonNull final Map<String, Object> parameters)
{
parameters.forEach(this::setParameter);
return this;
}
private ImmutableMap<String, Object> getParameters()
{
return parameters != null ? ImmutableMap.copyOf(parameters) : ImmutableMap.of();
}
public Builder applySecurityRestrictions(final boolean applySecurityRestrictions)
{
this.applySecurityRestrictions = applySecurityRestrictions;
return this;
}
private boolean isApplySecurityRestrictions()
{
return applySecurityRestrictions;
}
}
//
//
//
//
//
@ToString
private static final class WrappedDocumentFilterList
{
public static WrappedDocumentFilterList ofFilters(final DocumentFilterList filters)
{
if (filters == null || filters.isEmpty())
{
return EMPTY;
}
final ImmutableList<JSONDocumentFilter> jsonFiltersEffective = null;
return new WrappedDocumentFilterList(jsonFiltersEffective, filters);
} | public static WrappedDocumentFilterList ofJSONFilters(final List<JSONDocumentFilter> jsonFilters)
{
if (jsonFilters == null || jsonFilters.isEmpty())
{
return EMPTY;
}
final ImmutableList<JSONDocumentFilter> jsonFiltersEffective = ImmutableList.copyOf(jsonFilters);
final DocumentFilterList filtersEffective = null;
return new WrappedDocumentFilterList(jsonFiltersEffective, filtersEffective);
}
public static final WrappedDocumentFilterList EMPTY = new WrappedDocumentFilterList();
private final ImmutableList<JSONDocumentFilter> jsonFilters;
private final DocumentFilterList filters;
private WrappedDocumentFilterList(@Nullable final ImmutableList<JSONDocumentFilter> jsonFilters, @Nullable final DocumentFilterList filters)
{
this.jsonFilters = jsonFilters;
this.filters = filters;
}
/**
* empty constructor
*/
private WrappedDocumentFilterList()
{
filters = DocumentFilterList.EMPTY;
jsonFilters = null;
}
public DocumentFilterList unwrap(final DocumentFilterDescriptorsProvider descriptors)
{
if (filters != null)
{
return filters;
}
if (jsonFilters == null || jsonFilters.isEmpty())
{
return DocumentFilterList.EMPTY;
}
return JSONDocumentFilter.unwrapList(jsonFilters, descriptors);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\CreateViewRequest.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<?> saveDatarule(@RequestBody JSONObject jsonObject) {
try {
String permissionId = jsonObject.getString("permissionId");
String roleId = jsonObject.getString("roleId");
String dataRuleIds = jsonObject.getString("dataRuleIds");
log.info("保存数据规则>>"+"菜单ID:"+permissionId+"角色ID:"+ roleId+"数据权限ID:"+dataRuleIds);
LambdaQueryWrapper<SysDepartRolePermission> query = new LambdaQueryWrapper<SysDepartRolePermission>()
.eq(SysDepartRolePermission::getPermissionId, permissionId)
.eq(SysDepartRolePermission::getRoleId,roleId);
SysDepartRolePermission sysRolePermission = sysDepartRolePermissionService.getOne(query);
if(sysRolePermission==null) {
return Result.error("请先保存角色菜单权限!");
}else {
sysRolePermission.setDataRuleIds(dataRuleIds);
this.sysDepartRolePermissionService.updateById(sysRolePermission);
}
} catch (Exception e) {
log.error("SysRoleController.saveDatarule()发生异常:" + e.getMessage(),e);
return Result.error("保存失败");
}
return Result.ok("保存成功!");
}
/**
* 导出excel
*
* @param request
* @param sysDepartRole
*/ | @RequestMapping(value = "/exportXls")
public ModelAndView exportXls(HttpServletRequest request, SysDepartRole sysDepartRole) {
return super.exportXls(request, sysDepartRole, SysDepartRole.class, "部门角色");
}
/**
* 通过excel导入数据
*
* @param request
* @param response
* @return
*/
@RequestMapping(value = "/importExcel", method = RequestMethod.POST)
public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
return super.importExcel(request, response, SysDepartRole.class);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysDepartRoleController.java | 2 |
请完成以下Java代码 | private static final class AotContribution implements BeanFactoryInitializationAotContribution {
private final @Nullable ClassLoader classLoader;
private final Set<Class<? extends StructuredLoggingJsonMembersCustomizer<?>>> customizers;
private final @Nullable String stackTracePrinter;
private AotContribution(@Nullable ClassLoader classLoader,
Set<Class<? extends StructuredLoggingJsonMembersCustomizer<?>>> customizers,
@Nullable String stackTracePrinter) {
this.classLoader = classLoader;
this.customizers = customizers;
this.stackTracePrinter = stackTracePrinter;
} | @Override
public void applyTo(GenerationContext generationContext,
BeanFactoryInitializationCode beanFactoryInitializationCode) {
ReflectionHints reflection = generationContext.getRuntimeHints().reflection();
this.customizers.forEach((customizer) -> reflection.registerType(customizer,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS));
if (this.stackTracePrinter != null) {
reflection.registerTypeIfPresent(this.classLoader, this.stackTracePrinter,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS, MemberCategory.INVOKE_PUBLIC_CONSTRUCTORS);
}
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\structured\StructuredLoggingJsonPropertiesBeanFactoryInitializationAotProcessor.java | 1 |
请完成以下Java代码 | private static boolean hasJksTrustStoreProperties(Ssl ssl) {
return Ssl.isEnabled(ssl) && (ssl.getTrustStore() != null
|| (ssl.getTrustStoreType() != null && ssl.getTrustStoreType().equals("PKCS11")));
}
@Override
public String toString() {
ToStringCreator creator = new ToStringCreator(this);
creator.append("key", this.key);
creator.append("protocol", this.protocol);
creator.append("stores", this.stores);
creator.append("options", this.options);
return creator.toString();
}
private static final class WebServerSslStoreBundle implements SslStoreBundle {
private final @Nullable KeyStore keyStore;
private final @Nullable KeyStore trustStore;
private final @Nullable String keyStorePassword;
private WebServerSslStoreBundle(@Nullable KeyStore keyStore, @Nullable KeyStore trustStore,
@Nullable String keyStorePassword) {
Assert.state(keyStore != null || trustStore != null,
"SSL is enabled but no trust material is configured for the default host");
this.keyStore = keyStore;
this.trustStore = trustStore;
this.keyStorePassword = keyStorePassword;
}
@Override
public @Nullable KeyStore getKeyStore() {
return this.keyStore; | }
@Override
public @Nullable KeyStore getTrustStore() {
return this.trustStore;
}
@Override
public @Nullable String getKeyStorePassword() {
return this.keyStorePassword;
}
@Override
public String toString() {
ToStringCreator creator = new ToStringCreator(this);
creator.append("keyStore.type", (this.keyStore != null) ? this.keyStore.getType() : "none");
creator.append("keyStorePassword", (this.keyStorePassword != null) ? "******" : null);
creator.append("trustStore.type", (this.trustStore != null) ? this.trustStore.getType() : "none");
return creator.toString();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\WebServerSslBundle.java | 1 |
请完成以下Java代码 | public byte[] getBinaryData ()
{
return (byte[])get_Value(COLUMNNAME_BinaryData);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Fehler.
@param IsError
An Error occured in the execution
*/
@Override
public void setIsError (boolean IsError)
{
set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError));
}
/** Get Fehler.
@return An Error occured in the execution
*/
@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 Referenz.
@param Reference
Reference for this record
*/
@Override
public void setReference (java.lang.String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
/** Get Referenz.
@return Reference for this record
*/
@Override
public java.lang.String getReference ()
{
return (java.lang.String)get_Value(COLUMNNAME_Reference);
} | /** Set Zusammenfassung.
@param Summary
Textual summary of this request
*/
@Override
public void setSummary (java.lang.String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
}
/** Get Zusammenfassung.
@return Textual summary of this request
*/
@Override
public java.lang.String getSummary ()
{
return (java.lang.String)get_Value(COLUMNNAME_Summary);
}
/** Set Mitteilung.
@param TextMsg
Text Message
*/
@Override
public void setTextMsg (java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Mitteilung.
@return Text Message
*/
@Override
public java.lang.String getTextMsg ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_SchedulerLog.java | 1 |
请完成以下Java代码 | private static ProcessDescriptorType extractType(final I_AD_Process adProcess)
{
if (adProcess.getAD_Form_ID() > 0)
{
return ProcessDescriptorType.Form;
}
else if (adProcess.getAD_Workflow_ID() > 0)
{
return ProcessDescriptorType.Workflow;
}
else if (adProcess.isReport())
{
return ProcessDescriptorType.Report;
}
else
{
return ProcessDescriptorType.Process;
}
}
@Nullable
private static String extractClassnameOrNull(@NonNull final I_AD_Process adProcess)
{
if (!Check.isEmpty(adProcess.getClassname(), true))
{
return adProcess.getClassname();
}
return null;
}
private static final class ProcessPreconditionsResolutionSupplier implements Supplier<ProcessPreconditionsResolution>
{
private final IProcessPreconditionsContext preconditionsContext;
private final ProcessDescriptor processDescriptor;
@Builder
private ProcessPreconditionsResolutionSupplier(
@NonNull final IProcessPreconditionsContext preconditionsContext,
@NonNull final ProcessDescriptor processDescriptor)
{
this.preconditionsContext = preconditionsContext;
this.processDescriptor = processDescriptor;
}
@Override
public ProcessPreconditionsResolution get()
{
return processDescriptor.checkPreconditionsApplicable(preconditionsContext);
}
}
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 final class AspectJMethodSecurityInterceptor extends MethodSecurityInterceptor {
/**
* Method that is suitable for user with @Aspect notation.
* @param jp The AspectJ joint point being invoked which requires a security decision
* @return The returned value from the method invocation
* @throws Throwable if the invocation throws one
*/
public Object invoke(JoinPoint jp) throws Throwable {
return super.invoke(new MethodInvocationAdapter(jp));
}
/**
* Method that is suitable for user with traditional AspectJ-code aspects.
* @param jp The AspectJ joint point being invoked which requires a security decision
* @param advisorProceed the advice-defined anonymous class that implements
* {@code AspectJCallback} containing a simple {@code return proceed();} statement | * @return The returned value from the method invocation
*/
public Object invoke(JoinPoint jp, AspectJCallback advisorProceed) {
InterceptorStatusToken token = super.beforeInvocation(new MethodInvocationAdapter(jp));
Object result;
try {
result = advisorProceed.proceedWithObject();
}
finally {
super.finallyInvocation(token);
}
return super.afterInvocation(token, result);
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\intercept\aspectj\AspectJMethodSecurityInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LongMessageProducer longMessageProducer() {
return new LongMessageProducer();
}
@Bean
public LongMessageListener longMessageListener() {
return new LongMessageListener();
}
public static class LongMessageProducer {
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Value(value = "${long.message.topic.name}")
private String topicName;
public void sendMessage(String message) {
kafkaTemplate.send(topicName, message); | System.out.println("Long message Sent");
}
}
public static class LongMessageListener {
@KafkaListener(topics = "${long.message.topic.name}", groupId = "longMessage", containerFactory = "longMessageKafkaListenerContainerFactory")
public void listenGroupLongMessage(String message) {
System.out.println("Received Message in group 'longMessage'");
}
}
} | repos\tutorials-master\spring-kafka-4\src\main\java\com\baeldung\spring\kafka\KafkaApplicationLongMessage.java | 2 |
请完成以下Java代码 | public void handleMemberSuspect(MemberSuspectEvent event) { }
/**
* @inheritDoc
*/
@Override
public final void quorumLost(DistributionManager manager, Set<InternalDistributedMember> failedMembers,
List<InternalDistributedMember> remainingMembers) {
QuorumLostEvent event = new QuorumLostEvent(manager)
.withFailedMembers(failedMembers)
.withRemainingMembers(remainingMembers);
handleQuorumLost(event);
}
public void handleQuorumLost(QuorumLostEvent event) { }
/**
* Registers this {@link MembershipListener} with the given {@literal peer} {@link Cache}.
*
* @param peerCache {@literal peer} {@link Cache} on which to register this {@link MembershipListener}.
* @return this {@link MembershipListenerAdapter}. | * @see org.apache.geode.cache.Cache
*/
@SuppressWarnings("unchecked")
public T register(Cache peerCache) {
Optional.ofNullable(peerCache)
.map(Cache::getDistributedSystem)
.filter(InternalDistributedSystem.class::isInstance)
.map(InternalDistributedSystem.class::cast)
.map(InternalDistributedSystem::getDistributionManager)
.ifPresent(distributionManager -> distributionManager
.addMembershipListener(this));
return (T) this;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\apache-geode-extensions\src\main\java\org\springframework\geode\distributed\event\MembershipListenerAdapter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Object remove() {
// 设置查询条件参数
int age = 30;
String sex = "男";
// 创建条件对象
Criteria criteria = Criteria.where("age").is(age).and("sex").is(sex);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 执行删除查找到的匹配的全部文档信息
DeleteResult result = mongoTemplate.remove(query, COLLECTION_NAME);
// 输出结果信息
String resultInfo = "成功删除 " + result.getDeletedCount() + " 条文档信息";
log.info(resultInfo);
return resultInfo;
}
/**
* 删除【符合条件】的【单个文档】,并返回删除的文档。
*
* @return 删除的用户信息
*/
public Object findAndRemove() {
// 设置查询条件参数
String name = "zhangsansan";
// 创建条件对象
Criteria criteria = Criteria.where("name").is(name);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 执行删除查找到的匹配的第一条文档,并返回删除的文档信息
User result = mongoTemplate.findAndRemove(query, User.class, COLLECTION_NAME);
// 输出结果信息
String resultInfo = "成功删除文档信息,文档内容为:" + result;
log.info(resultInfo);
return result;
} | /**
* 删除【符合条件】的【全部文档】,并返回删除的文档。
*
* @return 删除的全部用户信息
*/
public Object findAllAndRemove() {
// 设置查询条件参数
int age = 22;
// 创建条件对象
Criteria criteria = Criteria.where("age").is(age);
// 创建查询对象,然后将条件对象添加到其中
Query query = new Query(criteria);
// 执行删除查找到的匹配的全部文档,并返回删除的全部文档信息
List<User> resultList = mongoTemplate.findAllAndRemove(query, User.class, COLLECTION_NAME);
// 输出结果信息
String resultInfo = "成功删除文档信息,文档内容为:" + resultList;
log.info(resultInfo);
return resultList;
}
} | repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\RemoveService.java | 2 |
请完成以下Java代码 | public static Collector<Packageable, ?, PackageableList> collect()
{
return GuavaCollectors.collectUsingListAccumulator(PackageableList::ofCollection);
}
public boolean isEmpty() {return list.isEmpty();}
public int size() {return list.size();}
public Stream<Packageable> stream() {return list.stream();}
@Override
public @NonNull Iterator<Packageable> iterator() {return list.iterator();}
public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIds()
{
return list.stream().map(Packageable::getShipmentScheduleId).sorted().collect(ImmutableSet.toImmutableSet());
}
public Optional<BPartnerId> getSingleCustomerId() {return getSingleValue(Packageable::getCustomerId);}
public <T> Optional<T> getSingleValue(@NonNull final Function<Packageable, T> mapper)
{
if (list.isEmpty())
{
return Optional.empty();
}
final ImmutableList<T> values = list.stream()
.map(mapper)
.filter(Objects::nonNull)
.distinct()
.collect(ImmutableList.toImmutableList()); | if (values.isEmpty())
{
return Optional.empty();
}
else if (values.size() == 1)
{
return Optional.of(values.get(0));
}
else
{
//throw new AdempiereException("More than one value were extracted (" + values + ") from " + list);
return Optional.empty();
}
}
public Stream<PackageableList> groupBy(Function<Packageable, ?> classifier)
{
return list.stream()
.collect(Collectors.groupingBy(classifier, LinkedHashMap::new, PackageableList.collect()))
.values()
.stream();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\picking\api\PackageableList.java | 1 |
请完成以下Java代码 | protected void configureQuery(AbstractQuery<?,?> query, Resource resource) {
getAuthorizationManager().configureQuery(query, resource);
}
protected void checkAuthorization(Permission permission, Resource resource, String resourceId) {
getAuthorizationManager().checkAuthorization(permission, resource, resourceId);
}
public boolean isAuthorizationEnabled() {
return Context.getProcessEngineConfiguration().isAuthorizationEnabled();
}
protected Authentication getCurrentAuthentication() {
return Context.getCommandContext().getAuthentication();
}
protected ResourceAuthorizationProvider getResourceAuthorizationProvider() {
return Context.getProcessEngineConfiguration()
.getResourceAuthorizationProvider();
}
protected void deleteAuthorizations(Resource resource, String resourceId) {
getAuthorizationManager().deleteAuthorizationsByResourceId(resource, resourceId);
}
protected void deleteAuthorizationsForUser(Resource resource, String resourceId, String userId) {
getAuthorizationManager().deleteAuthorizationsByResourceIdAndUserId(resource, resourceId, userId);
}
protected void deleteAuthorizationsForGroup(Resource resource, String resourceId, String groupId) {
getAuthorizationManager().deleteAuthorizationsByResourceIdAndGroupId(resource, resourceId, groupId);
}
public void saveDefaultAuthorizations(final AuthorizationEntity[] authorizations) {
if(authorizations != null && authorizations.length > 0) {
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() { | public Void call() {
AuthorizationManager authorizationManager = getAuthorizationManager();
for (AuthorizationEntity authorization : authorizations) {
if(authorization.getId() == null) {
authorizationManager.insert(authorization);
} else {
authorizationManager.update(authorization);
}
}
return null;
}
});
}
}
public void deleteDefaultAuthorizations(final AuthorizationEntity[] authorizations) {
if(authorizations != null && authorizations.length > 0) {
Context.getCommandContext().runWithoutAuthorization(new Callable<Void>() {
public Void call() {
AuthorizationManager authorizationManager = getAuthorizationManager();
for (AuthorizationEntity authorization : authorizations) {
authorizationManager.delete(authorization);
}
return null;
}
});
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\AbstractManager.java | 1 |
请完成以下Java代码 | public class EventDefinitionEntityImpl extends AbstractEventRegistryNoRevisionEntity implements EventDefinitionEntity, Serializable {
private static final long serialVersionUID = 1L;
protected String name;
protected String description;
protected String key;
protected int version;
protected String category;
protected String deploymentId;
protected String resourceName;
protected String tenantId = EventRegistryEngineConfiguration.NO_TENANT_ID;
@Override
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<>();
persistentState.put("category", this.category);
return persistentState;
}
// getters and setters
// //////////////////////////////////////////////////////
@Override
public String getKey() {
return key;
}
@Override
public void setKey(String key) {
this.key = key;
}
@Override
public int getVersion() {
return version;
}
@Override
public void setVersion(int version) {
this.version = version;
}
@Override
public String getName() {
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public void setDescription(String description) {
this.description = description;
}
@Override
public String getDescription() {
return description;
}
@Override
public String getDeploymentId() {
return deploymentId;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
} | @Override
public String getResourceName() {
return resourceName;
}
@Override
public void setResourceName(String resourceName) {
this.resourceName = resourceName;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getCategory() {
return category;
}
@Override
public void setCategory(String category) {
this.category = category;
}
@Override
public String toString() {
return "EventDefinitionEntity[" + id + "]";
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\persistence\entity\EventDefinitionEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void configure(HttpSecurity http) throws Exception {
// @formatter:off
http.cors()
// 关闭 CSRF
.and().csrf().disable()
// 登录行为由自己实现,参考 AuthController#login
.formLogin().disable()
.httpBasic().disable()
// 认证请求
.authorizeRequests()
// 所有请求都需要登录访问
.anyRequest()
.authenticated()
// RBAC 动态 url 认证
.anyRequest()
.access("@rbacAuthorityService.hasPermission(request,authentication)")
// 登出行为由自己实现,参考 AuthController#logout
.and().logout().disable()
// Session 管理
.sessionManagement()
// 因为使用了JWT,所以这里不管理Session
.sessionCreationPolicy(SessionCreationPolicy.STATELESS)
// 异常处理
.and().exceptionHandling().accessDeniedHandler(accessDeniedHandler);
// @formatter:on
// 添加自定义 JWT 过滤器
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
}
/**
* 放行所有不需要登录就可以访问的请求,参见 AuthController
* 也可以在 {@link #configure(HttpSecurity)} 中配置
* {@code http.authorizeRequests().antMatchers("/api/auth/**").permitAll()} | */
@Override
public void configure(WebSecurity web) {
WebSecurity and = web.ignoring().and();
// 忽略 GET
customConfig.getIgnores().getGet().forEach(url -> and.ignoring().antMatchers(HttpMethod.GET, url));
// 忽略 POST
customConfig.getIgnores().getPost().forEach(url -> and.ignoring().antMatchers(HttpMethod.POST, url));
// 忽略 DELETE
customConfig.getIgnores().getDelete().forEach(url -> and.ignoring().antMatchers(HttpMethod.DELETE, url));
// 忽略 PUT
customConfig.getIgnores().getPut().forEach(url -> and.ignoring().antMatchers(HttpMethod.PUT, url));
// 忽略 HEAD
customConfig.getIgnores().getHead().forEach(url -> and.ignoring().antMatchers(HttpMethod.HEAD, url));
// 忽略 PATCH
customConfig.getIgnores().getPatch().forEach(url -> and.ignoring().antMatchers(HttpMethod.PATCH, url));
// 忽略 OPTIONS
customConfig.getIgnores().getOptions().forEach(url -> and.ignoring().antMatchers(HttpMethod.OPTIONS, url));
// 忽略 TRACE
customConfig.getIgnores().getTrace().forEach(url -> and.ignoring().antMatchers(HttpMethod.TRACE, url));
// 按照请求格式忽略
customConfig.getIgnores().getPattern().forEach(url -> and.ignoring().antMatchers(url));
}
} | repos\spring-boot-demo-master\demo-rbac-security\src\main\java\com\xkcoding\rbac\security\config\SecurityConfig.java | 2 |
请完成以下Java代码 | public String getId() {
return id;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public Size getSize() {
return size;
}
public void setSize(Size size) {
this.size = size;
}
public List<InStock> getInStock() {
return inStock; | }
public void setInStock(List<InStock> inStock) {
this.inStock = inStock;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Inventory inventory = (Inventory) o;
return Objects.equals(id, inventory.id) && Objects.equals(item, inventory.item) && Objects.equals(status, inventory.status);
}
@Override
public int hashCode() {
return Objects.hash(id, item, status);
}
} | repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\projection\model\Inventory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class NoopJobExecutionObservationProvider implements JobExecutionObservationProvider {
@Override
public JobExecutionObservation create(JobInfo job) {
return JobExecutionObservation.NOOP;
}
static class NoopJobExecutionObservation implements JobExecutionObservation {
@Override
public void start() {
// Do nothing
}
@Override
public void stop() {
// Do nothing
}
@Override
public Scope lockScope() {
return NoopScope.INSTANCE;
}
@Override
public void lockError(Throwable lockException) {
// Do nothing
}
@Override
public Scope executionScope() { | return NoopScope.INSTANCE;
}
@Override
public void executionError(Throwable exception) {
// Do nothing
}
}
static class NoopScope implements JobExecutionObservation.Scope {
static final NoopScope INSTANCE = new NoopScope();
@Override
public void close() {
// Do nothing
}
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\NoopJobExecutionObservationProvider.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Saml2AuthenticationToken convert(HttpServletRequest request) {
AbstractSaml2AuthenticationRequest authenticationRequest = this.authenticationRequestRepository
.loadAuthenticationRequest(request);
String relyingPartyRegistrationId = (authenticationRequest != null)
? authenticationRequest.getRelyingPartyRegistrationId() : null;
RelyingPartyRegistration relyingPartyRegistration = this.relyingPartyRegistrationResolver.resolve(request,
relyingPartyRegistrationId);
if (relyingPartyRegistration == null) {
return null;
}
String saml2Response = decode(request);
if (saml2Response == null) {
return null;
}
return new Saml2AuthenticationToken(relyingPartyRegistration, saml2Response, authenticationRequest);
}
/**
* Use the given {@link Saml2AuthenticationRequestRepository} to load authentication
* request.
* @param authenticationRequestRepository the
* {@link Saml2AuthenticationRequestRepository} to use
* @since 5.6
*/
public void setAuthenticationRequestRepository(
Saml2AuthenticationRequestRepository<AbstractSaml2AuthenticationRequest> authenticationRequestRepository) {
Assert.notNull(authenticationRequestRepository, "authenticationRequestRepository cannot be null");
this.authenticationRequestRepository = authenticationRequestRepository;
}
/** | * Use the given {@code shouldConvertGetRequests} to convert {@code GET} requests.
* Default is {@code true}.
* @param shouldConvertGetRequests the {@code shouldConvertGetRequests} to use
* @since 7.0
*/
public void setShouldConvertGetRequests(boolean shouldConvertGetRequests) {
this.shouldConvertGetRequests = shouldConvertGetRequests;
}
private String decode(HttpServletRequest request) {
String encoded = request.getParameter(Saml2ParameterNames.SAML_RESPONSE);
if (encoded == null) {
return null;
}
boolean isGet = HttpMethod.GET.matches(request.getMethod());
if (!this.shouldConvertGetRequests && isGet) {
return null;
}
Saml2Utils.DecodingConfigurer decoding = Saml2Utils.withEncoded(encoded).requireBase64(true).inflate(isGet);
try {
return decoding.decode();
}
catch (Exception ex) {
throw new Saml2AuthenticationException(Saml2Error.invalidResponse(ex.getMessage()), ex);
}
}
} | repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\Saml2AuthenticationTokenConverter.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getDetailType() {
return detailType;
}
public void setDetailType(String detailType) {
this.detailType = detailType;
}
@ApiModelProperty(example = "2")
public Integer getRevision() {
return revision;
}
public void setRevision(Integer revision) {
this.revision = revision;
}
public RestVariable getVariable() {
return variable;
}
public void setVariable(RestVariable variable) {
this.variable = variable;
} | @ApiModelProperty(example = "null")
public String getPropertyId() {
return propertyId;
}
public void setPropertyId(String propertyId) {
this.propertyId = propertyId;
}
@ApiModelProperty(example = "null")
public String getPropertyValue() {
return propertyValue;
}
public void setPropertyValue(String propertyValue) {
this.propertyValue = propertyValue;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricDetailResponse.java | 2 |
请完成以下Java代码 | public ColorId saveFlatColorAndReturnId(@NonNull String flatColorHexString)
{
final Color flatColor = MFColor.ofFlatColorHexString(flatColorHexString).getFlatColor();
final I_AD_Color existingColorRecord = Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_AD_Color.class)
.addOnlyActiveRecordsFilter()
.addOnlyContextClientOrSystem()
.addEqualsFilter(I_AD_Color.COLUMNNAME_ColorType, X_AD_Color.COLORTYPE_NormalFlat)
.addEqualsFilter(I_AD_Color.COLUMNNAME_Red, flatColor.getRed())
.addEqualsFilter(I_AD_Color.COLUMNNAME_Green, flatColor.getGreen())
.addEqualsFilter(I_AD_Color.COLUMNNAME_Blue, flatColor.getBlue())
.orderByDescending(I_AD_Color.COLUMNNAME_AD_Client_ID)
.orderBy(I_AD_Color.COLUMNNAME_AD_Color_ID)
.create()
.first();
if (existingColorRecord != null)
{
return ColorId.ofRepoId(existingColorRecord.getAD_Color_ID());
}
final I_AD_Color newColorRecord = InterfaceWrapperHelper.newInstanceOutOfTrx(I_AD_Color.class);
newColorRecord.setAD_Org_ID(Env.CTXVALUE_AD_Org_ID_Any);
newColorRecord.setName(flatColorHexString.toLowerCase());
newColorRecord.setColorType(X_AD_Color.COLORTYPE_NormalFlat);
newColorRecord.setRed(flatColor.getRed());
newColorRecord.setGreen(flatColor.getGreen());
newColorRecord.setBlue(flatColor.getBlue());
//
newColorRecord.setAlpha(0);
newColorRecord.setImageAlpha(BigDecimal.ZERO);
// | InterfaceWrapperHelper.save(newColorRecord);
return ColorId.ofRepoId(newColorRecord.getAD_Color_ID());
}
@Override
public ColorId getColorIdByName(final String colorName)
{
return colorIdByName.getOrLoad(colorName, () -> retrieveColorIdByName(colorName));
}
private ColorId retrieveColorIdByName(final String colorName)
{
final int colorRepoId = Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_Color.class)
.addOnlyActiveRecordsFilter()
.addOnlyContextClientOrSystem()
.addEqualsFilter(I_AD_Color.COLUMNNAME_Name, colorName)
.create()
.firstIdOnly();
return ColorId.ofRepoIdOrNull(colorRepoId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\impl\ColorRepository.java | 1 |
请完成以下Java代码 | public CompletableFuture<HttpResponse> callAsync() {
CompletableFuture<HttpResponse> responseFuture = new CompletableFuture<>();
HttpClientContext context = HttpClientContext.create();
context.setRequestConfig(requestConfig);
client.execute(
request,
SimpleResponseConsumer.create(),
null,
context,
new FutureCallback<>() {
@Override
public void completed(SimpleHttpResponse result) {
responseFuture.complete(toFlowableHttpResponse(result));
}
@Override | public void failed(Exception ex) {
responseFuture.completeExceptionally(ex);
}
@Override
public void cancelled() {
responseFuture.cancel(true);
}
}
);
return responseFuture;
}
}
} | repos\flowable-engine-main\modules\flowable-http-common\src\main\java\org\flowable\http\common\impl\apache\client5\ApacheHttpComponents5FlowableHttpClient.java | 1 |
请完成以下Java代码 | public void setVariableLocal(String variableName, Object value) {
ExecutionEntity execution = getExecutionFromContext();
if(execution != null) {
execution.setVariableLocal(variableName, value);
execution.getVariableLocal(variableName);
} else {
getScopedAssociation().setVariableLocal(variableName, value);
}
}
protected ExecutionEntity getExecutionFromContext() {
if(Context.getCommandContext() != null) {
BpmnExecutionContext executionContext = Context.getBpmnExecutionContext();
if(executionContext != null) {
return executionContext.getExecution();
}
}
return null;
}
public Task getTask() {
ensureCommandContextNotActive();
return getScopedAssociation().getTask();
}
public void setTask(Task task) {
ensureCommandContextNotActive();
getScopedAssociation().setTask(task);
}
public VariableMap getCachedVariables() {
ensureCommandContextNotActive(); | return getScopedAssociation().getCachedVariables();
}
public VariableMap getCachedLocalVariables() {
ensureCommandContextNotActive();
return getScopedAssociation().getCachedVariablesLocal();
}
public void flushVariableCache() {
ensureCommandContextNotActive();
getScopedAssociation().flushVariableCache();
}
protected void ensureCommandContextNotActive() {
if(Context.getCommandContext() != null) {
throw new ProcessEngineCdiException("Cannot work with scoped associations inside command context.");
}
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\context\DefaultContextAssociationManager.java | 1 |
请完成以下Java代码 | public void setOnNew (final boolean OnNew)
{
set_Value (COLUMNNAME_OnNew, OnNew);
}
@Override
public boolean isOnNew()
{
return get_ValueAsBoolean(COLUMNNAME_OnNew);
}
@Override
public void setOnUpdate (final boolean OnUpdate)
{
set_Value (COLUMNNAME_OnUpdate, OnUpdate);
}
@Override
public boolean isOnUpdate()
{
return get_ValueAsBoolean(COLUMNNAME_OnUpdate);
}
@Override
public void setSource_Table_ID (final int Source_Table_ID)
{
if (Source_Table_ID < 1)
set_Value (COLUMNNAME_Source_Table_ID, null); | else
set_Value (COLUMNNAME_Source_Table_ID, Source_Table_ID);
}
@Override
public int getSource_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_Source_Table_ID);
}
@Override
public void setTargetRecordMappingSQL (final java.lang.String TargetRecordMappingSQL)
{
set_Value (COLUMNNAME_TargetRecordMappingSQL, TargetRecordMappingSQL);
}
@Override
public java.lang.String getTargetRecordMappingSQL()
{
return get_ValueAsString(COLUMNNAME_TargetRecordMappingSQL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_BusinessRule_Trigger.java | 1 |
请完成以下Java代码 | public void propertyChange (PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
// metas: request focus (2009_0027_G131)
if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS))
requestFocus();
// metas end
} // propertyChange
/**
* Action Listener Interface - NOP
* @param listener listener
*/
@Override
public void addActionListener(ActionListener listener)
{
} // addActionListener
/**************************************************************************
* Key Listener Interface
* @param e event
*/
@Override
public void keyTyped(KeyEvent e) {}
@Override
public void keyPressed(KeyEvent e) {}
/**
* Key Released
* if Escape restore old Text.
* @param e event
*/
@Override
public void keyReleased(KeyEvent e)
{ | // ESC
if (e.getKeyCode() == KeyEvent.VK_ESCAPE)
setText(m_initialText);
m_setting = true;
try
{
fireVetoableChange(m_columnName, m_oldText, getText());
}
catch (PropertyVetoException pve) {}
m_setting = false;
} // keyReleased
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField field model
*/
@Override
public void setField (org.compiere.model.GridField mField)
{
m_mField = mField;
EditorContextPopupMenu.onGridFieldSet(this);
} // setField
@Override
public GridField getField() {
return m_mField;
}
// metas: begin
@Override
public boolean isAutoCommit()
{
return true;
}
// metas: end
} // VText | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VText.java | 1 |
请完成以下Java代码 | public String getActiveInfo(final int AD_Table_ID, final int Record_ID)
{
final ImmutableList<I_AD_WF_Activity> activities = getActiveActivities(AD_Table_ID, Record_ID);
if (activities.isEmpty())
{
return null;
}
return activities.stream()
.map(this::toStringX)
.collect(Collectors.joining("\n"));
}
private String toStringX(final I_AD_WF_Activity activity)
{
final StringBuilder sb = new StringBuilder();
sb.append(WFState.ofCode(activity.getWFState())).append(": ").append(getActivityName(activity).getDefaultValue());
final UserId userId = UserId.ofRepoIdOrNullIfSystem(activity.getAD_User_ID());
if (userId != null)
{
final IUserDAO userDAO = Services.get(IUserDAO.class);
final String userFullname = userDAO.retrieveUserFullName(userId);
sb.append(" (").append(userFullname).append(")");
}
return sb.toString();
}
private ITranslatableString getActivityName(@NonNull final I_AD_WF_Activity activity)
{
final IADWorkflowDAO workflowDAO = Services.get(IADWorkflowDAO.class);
final WorkflowId workflowId = WorkflowId.ofRepoId(activity.getAD_Workflow_ID());
final WFNodeId wfNodeId = WFNodeId.ofRepoId(activity.getAD_WF_Node_ID());
return workflowDAO.getWFNodeName(workflowId, wfNodeId);
}
private ImmutableList<I_AD_WF_Activity> getActiveActivities(final int AD_Table_ID, final int Record_ID)
{
return queryBL.createQueryBuilderOutOfTrx(I_AD_WF_Activity.class) | .addEqualsFilter(I_AD_WF_Activity.COLUMNNAME_AD_Table_ID, AD_Table_ID)
.addEqualsFilter(I_AD_WF_Activity.COLUMNNAME_AD_Table_ID, Record_ID)
.addEqualsFilter(I_AD_WF_Activity.COLUMNNAME_Processed, false)
.orderBy(I_AD_WF_Activity.COLUMNNAME_AD_WF_Activity_ID)
.create()
.listImmutable(I_AD_WF_Activity.class);
}
public List<WFProcessId> getActiveProcessIds(final TableRecordReference documentRef)
{
return queryBL.createQueryBuilderOutOfTrx(I_AD_WF_Process.class)
.addEqualsFilter(I_AD_WF_Process.COLUMNNAME_AD_Table_ID, documentRef.getAD_Table_ID())
.addEqualsFilter(I_AD_WF_Process.COLUMNNAME_Record_ID, documentRef.getRecord_ID())
.addEqualsFilter(I_AD_WF_Process.COLUMNNAME_Processed, false)
.create()
.listDistinct(I_AD_WF_Process.COLUMNNAME_AD_WF_Process_ID, WFProcessId.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workflow\execution\WFProcessRepository.java | 1 |
请完成以下Java代码 | public boolean getIsSalesDefaultOr(final boolean defaultValue)
{
return salesDefault.orElse(defaultValue);
}
public boolean getIsSalesOr(final boolean defaultValue)
{
return sales.orElse(defaultValue);
}
public boolean getIsPurchaseDefaultOr(final boolean defaultValue)
{
return purchaseDefault.orElse(defaultValue);
}
public boolean getIsPurchaseOr(final boolean defaultValue)
{
return purchase.orElse(defaultValue);
}
public void setDefaultContact(final boolean defaultContact)
{
this.defaultContact = Optional.of(defaultContact);
} | public void setBillToDefault(final boolean billToDefault)
{
this.billToDefault = Optional.of(billToDefault);
}
public void setShipToDefault(final boolean shipToDefault)
{
this.shipToDefault = Optional.of(shipToDefault);
}
public void setPurchaseDefault(final boolean purchaseDefault)
{
this.purchaseDefault = Optional.of(purchaseDefault);
}
public void setSalesDefault(final boolean salesDefault)
{
this.salesDefault = Optional.of(salesDefault);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerContactType.java | 1 |
请完成以下Java代码 | public class Meter implements IMeter
{
private AtomicLong invokeCount = new AtomicLong(0);
private BigDecimal invokeRate = BigDecimal.ZERO;
private AtomicLong millisLastInvoke = new AtomicLong(0);
private AtomicLong gauge = new AtomicLong(0);
private BigDecimal intervalLastInvoke = null;
@Override
public void plusOne()
{
gauge.addAndGet(1);
onInvoke();
}
@Override
public void minusOne()
{
gauge.addAndGet(-1);
onInvoke();
}
private void onInvoke()
{
final long millisNow = SystemTime.millis();
intervalLastInvoke = new BigDecimal(millisNow - millisLastInvoke.get());
millisLastInvoke.set(millisNow);
invokeCount.addAndGet(1);
updateInvokeRate();
}
private void updateInvokeRate()
{
// getting local copies to ensure that the values we work with aren't changed by other threads
// while this method executes
final BigDecimal intervalLastInvokeLocal = this.intervalLastInvoke;
final long invokeCountLocal = invokeCount.get();
if (invokeCountLocal < 2)
{
// need at least two 'plusOne()' invocations to get a rate | invokeRate = BigDecimal.ZERO;
}
else if (intervalLastInvokeLocal.signum() == 0)
{
// omit division by zero
invokeRate = new BigDecimal(Long.MAX_VALUE);
}
else
{
invokeRate = new BigDecimal("1000")
.setScale(2, BigDecimal.ROUND_HALF_UP)
.divide(intervalLastInvokeLocal, RoundingMode.HALF_UP)
.abs(); // be tolerant against intervalLastChange < 0
}
}
@Override
public long getInvokeCount()
{
return invokeCount.get();
}
@Override
public BigDecimal getInvokeRate()
{
return invokeRate;
}
@Override
public long getGauge()
{
return gauge.get();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\api\impl\Meter.java | 1 |
请完成以下Java代码 | public class FormInfo implements Serializable {
private static final long serialVersionUID = 1L;
protected String id;
protected String name;
protected String description;
protected String key;
protected int version;
protected FormModel formModel;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getKey() {
return key;
}
public void setKey(String key) { | this.key = key;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public FormModel getFormModel() {
return formModel;
}
public void setFormModel(FormModel formModel) {
this.formModel = formModel;
}
} | repos\flowable-engine-main\modules\flowable-form-api\src\main\java\org\flowable\form\api\FormInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void deleteHistoricIdentityLinksByScopeDefinitionIdAndType(String scopeDefinitionId, String scopeType) {
Map<String, String> parameters = new HashMap<>();
parameters.put("scopeDefinitionId", scopeDefinitionId);
parameters.put("scopeType", scopeType);
getDbSqlSession().delete("deleteHistoricIdentityLinksByScopeDefinitionIdAndScopeType", parameters, HistoricIdentityLinkEntityImpl.class);
}
@Override
public void bulkDeleteHistoricIdentityLinksForProcessInstanceIds(Collection<String> processInstanceIds) {
getDbSqlSession().delete("bulkDeleteHistoricIdentityLinksForProcessInstanceIds", createSafeInValuesList(processInstanceIds), HistoricIdentityLinkEntityImpl.class);
}
@Override
public void bulkDeleteHistoricIdentityLinksForTaskIds(Collection<String> taskIds) {
getDbSqlSession().delete("bulkDeleteHistoricIdentityLinksForTaskIds", createSafeInValuesList(taskIds), HistoricIdentityLinkEntityImpl.class);
}
@Override
public void bulkDeleteHistoricIdentityLinksForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("scopeIds", createSafeInValuesList(scopeIds));
parameters.put("scopeType", scopeType);
getDbSqlSession().delete("bulkDeleteHistoricIdentityLinksForScopeIdsAndScopeType", parameters, HistoricIdentityLinkEntityImpl.class);
}
@Override
public void deleteHistoricProcessIdentityLinksForNonExistingInstances() {
getDbSqlSession().delete("bulkDeleteHistoricProcessIdentityLinks", null, HistoricIdentityLinkEntityImpl.class);
} | @Override
public void deleteHistoricCaseIdentityLinksForNonExistingInstances() {
getDbSqlSession().delete("bulkDeleteHistoricCaseIdentityLinks", null, HistoricIdentityLinkEntityImpl.class);
}
@Override
public void deleteHistoricTaskIdentityLinksForNonExistingInstances() {
getDbSqlSession().delete("bulkDeleteHistoricTaskIdentityLinks", null, HistoricIdentityLinkEntityImpl.class);
}
@Override
protected IdGenerator getIdGenerator() {
return identityLinkServiceConfiguration.getIdGenerator();
}
} | repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\data\impl\MybatisHistoricIdentityLinkDataManager.java | 2 |
请完成以下Java代码 | public String getDeploymentId() {
return deploymentId;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getCategory() {
return category;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() { | return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getDecisionKey() {
return decisionKey;
}
public String getDecisionKeyLike() {
return decisionKeyLike;
}
} | repos\flowable-engine-main\modules\flowable-dmn-engine\src\main\java\org\flowable\dmn\engine\impl\DmnDeploymentQueryImpl.java | 1 |
请完成以下Java代码 | public boolean load(ByteArray byteArray)
{
idStringMap.clear();
stringIdMap.clear();
int size = byteArray.nextInt();
for (int i = 0; i < size; i++)
{
String tag = byteArray.nextUTF();
idStringMap.add(tag);
stringIdMap.put(tag, i);
}
lock();
return true;
}
public void load(DataInputStream in) throws IOException
{
idStringMap.clear();
stringIdMap.clear();
int size = in.readInt();
for (int i = 0; i < size; i++)
{
String tag = in.readUTF();
idStringMap.add(tag); | stringIdMap.put(tag, i);
}
lock();
}
public Collection<String> tags()
{
return idStringMap;
}
public boolean contains(String tag)
{
return idStringMap.contains(tag);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\tagset\TagSet.java | 1 |
请完成以下Java代码 | public void setResponseCode (int ResponseCode)
{
set_Value (COLUMNNAME_ResponseCode, Integer.valueOf(ResponseCode));
}
/** Get Antwort .
@return Antwort */
@Override
public int getResponseCode ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ResponseCode);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Antwort-Text.
@param ResponseText
Anfrage-Antworttext
*/
@Override
public void setResponseText (java.lang.String ResponseText)
{
set_Value (COLUMNNAME_ResponseText, ResponseText);
}
/** Get Antwort-Text.
@return Anfrage-Antworttext
*/
@Override
public java.lang.String getResponseText ()
{
return (java.lang.String)get_Value(COLUMNNAME_ResponseText);
}
/** Set TransaktionsID Client.
@param TransactionIDClient TransaktionsID Client */
@Override
public void setTransactionIDClient (java.lang.String TransactionIDClient)
{
set_ValueNoCheck (COLUMNNAME_TransactionIDClient, TransactionIDClient);
}
/** Get TransaktionsID Client.
@return TransaktionsID Client */
@Override | public java.lang.String getTransactionIDClient ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionIDClient);
}
/** Set TransaktionsID Server.
@param TransactionIDServer TransaktionsID Server */
@Override
public void setTransactionIDServer (java.lang.String TransactionIDServer)
{
set_ValueNoCheck (COLUMNNAME_TransactionIDServer, TransactionIDServer);
}
/** Get TransaktionsID Server.
@return TransaktionsID Server */
@Override
public java.lang.String getTransactionIDServer ()
{
return (java.lang.String)get_Value(COLUMNNAME_TransactionIDServer);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Log.java | 1 |
请完成以下Java代码 | public void close()
{
if (!hasChanges())
{
return;
}
//
// Create the summary record for our particular DateAcct
final I_Fact_Acct_Summary factAcctSummary = getCreateFactAcctSummary();
final IQueryFilter<I_Fact_Acct_Summary> currentYearFilter = new EqualsQueryFilter<>(I_Fact_Acct_Summary.COLUMN_C_Year_ID, factAcctSummary.getC_Year_ID());
//
// Update all summary records which are >= particular DateAcct
factAcctLogDAO.retrieveCurrentAndNextMatchingFactAcctSummaryQuery(ctx, key)
.create()
.updateDirectly()
//
// Amounts: from beginning to Date
.addAddValueToColumn(I_Fact_Acct_Summary.COLUMNNAME_AmtAcctDr, amtAcctDr_ToAdd)
.addAddValueToColumn(I_Fact_Acct_Summary.COLUMNNAME_AmtAcctCr, amtAcctCr_ToAdd)
.addAddValueToColumn(I_Fact_Acct_Summary.COLUMNNAME_Qty, qty_ToAdd)
//
// Amounts: Year to Date
.addAddValueToColumn(I_Fact_Acct_Summary.COLUMNNAME_AmtAcctDr_YTD, amtAcctDr_ToAdd, currentYearFilter)
.addAddValueToColumn(I_Fact_Acct_Summary.COLUMNNAME_AmtAcctCr_YTD, amtAcctCr_ToAdd, currentYearFilter)
//
.execute();
//
// Reset the amounts because we processed them
resetAmounts();
} | }
private static final class FactAcctSummaryKeyBuilder implements IAggregationKeyBuilder<I_Fact_Acct_Log>
{
public static final FactAcctSummaryKeyBuilder instance = new FactAcctSummaryKeyBuilder();
private FactAcctSummaryKeyBuilder()
{
super();
}
@Override
public String buildKey(final I_Fact_Acct_Log item)
{
return FactAcctSummaryKey.of(item).asString();
}
@Override
public List<String> getDependsOnColumnNames()
{
throw new UnsupportedOperationException();
}
@Override
public boolean isSame(final I_Fact_Acct_Log item1, final I_Fact_Acct_Log item2)
{
throw new UnsupportedOperationException();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\aggregation\legacy\impl\LegacyFactAcctLogProcessor.java | 1 |
请完成以下Java代码 | public int getDisplaySeqNo()
{
return 0;
}
@Override
public boolean isReadonlyUI()
{
return false;
}
@Override
public boolean isDisplayedUI()
{
return true;
}
@Override
public boolean isMandatory()
{
return false;
}
@Override
public boolean isNew()
{
return isGeneratedAttribute;
}
@Override
protected void setInternalValueDate(Date value)
{
this.valueDate = value;
}
@Override
protected Date getInternalValueDate()
{ | return valueDate;
}
@Override
protected void setInternalValueDateInitial(Date value)
{
this.valueInitialDate = value;
}
@Override
protected Date getInternalValueDateInitial()
{
return valueInitialDate;
}
@Override
public boolean isOnlyIfInProductAttributeSet()
{
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\PlainAttributeValue.java | 1 |
请完成以下Java代码 | public HUPPOrderIssueProducer considerIssueMethodForQtyToIssueCalculation(final boolean considerIssueMethodForQtyToIssueCalculation)
{
this.considerIssueMethodForQtyToIssueCalculation = considerIssueMethodForQtyToIssueCalculation;
return this;
}
public HUPPOrderIssueProducer processCandidates(@NonNull final ProcessIssueCandidatesPolicy processCandidatesPolicy)
{
this.processCandidatesPolicy = processCandidatesPolicy;
return this;
}
private boolean isProcessCandidates()
{
final ProcessIssueCandidatesPolicy processCandidatesPolicy = this.processCandidatesPolicy;
if (ProcessIssueCandidatesPolicy.NEVER.equals(processCandidatesPolicy))
{
return false;
}
else if (ProcessIssueCandidatesPolicy.ALWAYS.equals(processCandidatesPolicy))
{
return true;
}
else if (ProcessIssueCandidatesPolicy.IF_ORDER_PLANNING_STATUS_IS_COMPLETE.equals(processCandidatesPolicy))
{
final I_PP_Order ppOrder = getPpOrder();
final PPOrderPlanningStatus orderPlanningStatus = PPOrderPlanningStatus.ofCode(ppOrder.getPlanningStatus());
return PPOrderPlanningStatus.COMPLETE.equals(orderPlanningStatus);
}
else | {
throw new AdempiereException("Unknown processCandidatesPolicy: " + processCandidatesPolicy);
}
}
public HUPPOrderIssueProducer changeHUStatusToIssued(final boolean changeHUStatusToIssued)
{
this.changeHUStatusToIssued = changeHUStatusToIssued;
return this;
}
public HUPPOrderIssueProducer generatedBy(final IssueCandidateGeneratedBy generatedBy)
{
this.generatedBy = generatedBy;
return this;
}
public HUPPOrderIssueProducer failIfIssueOnlyForReceived(final boolean fail)
{
this.failIfIssueOnlyForReceived = fail;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\HUPPOrderIssueProducer.java | 1 |
请完成以下Java代码 | public class WebEnv
{
/**
* Base Directory links e.g. <b>http://localhost:8080/</b>
*
* NOTE: to configure this, check the "serverRoot" project
*/
private static final String DIR_BASE = "";
/** Image Sub-Directory under BASE */
private static final String DIR_IMAGE = "images";
/** Stylesheet Name */
private static final String STYLE_STD = "css/standard.css";
public static final String IMAGE_PARAM_Width = "width";
/** Small Logo. */
public static final String LOGO = "logo.png"; // put ONLY the filename here
/**************************************************************************
* Get Base Directory entry.
* <br>
* /adempiere/
* @param entry file entry or path
* @return url to entry in base directory
*/
static String getBaseDirectory (final String... entries)
{
final StringBuilder sb = new StringBuilder (DIR_BASE);
for (final String entry : entries)
{
if (Check.isEmpty(entry, true))
{
continue; | }
if (sb.length() > 0 && !entry.startsWith("/"))
{
sb.append("/");
}
sb.append(entry);
}
return sb.toString();
} // getBaseDirectory
/**
* Get Logo Path.
*
* @param width optional image width
* @return url to logo
*/
public static String getLogoURL(final int width)
{
String logoURL = getBaseDirectory(DIR_IMAGE, LOGO);
return logoURL + "?" + IMAGE_PARAM_Width + "=" + width;
} // getLogoPath
/**
* Get Stylesheet Path.
* <p>
* /adempiere/standard.css
* @return url of Stylesheet
*/
public static String getStylesheetURL()
{
return getBaseDirectory(STYLE_STD);
} // getStylesheetURL
} // WEnv | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\WebEnv.java | 1 |
请完成以下Java代码 | public int getC_JobCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_JobCategory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{ | return (String)get_Value(COLUMNNAME_Help);
}
/** Set 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_C_JobCategory.java | 1 |
请完成以下Java代码 | public void run() {
FlowElement currentFlowElement = getCurrentFlowElement(execution);
if (currentFlowElement instanceof FlowNode) {
continueThroughMultiInstanceFlowNode((FlowNode) currentFlowElement);
} else {
throw new RuntimeException(
"Programmatic error: no valid multi instance flow node, type: " + currentFlowElement + ". Halting."
);
}
}
protected void continueThroughMultiInstanceFlowNode(FlowNode flowNode) {
if (!flowNode.isAsynchronous()) {
executeSynchronous(flowNode);
} else {
executeAsynchronous(flowNode);
}
}
protected void executeSynchronous(FlowNode flowNode) {
// Execution listener
if (CollectionUtil.isNotEmpty(flowNode.getExecutionListeners())) {
executeExecutionListeners(flowNode, ExecutionListener.EVENTNAME_START);
}
commandContext.getHistoryManager().recordActivityStart(execution);
// Execute actual behavior
ActivityBehavior activityBehavior = (ActivityBehavior) flowNode.getBehavior();
if (activityBehavior != null) {
logger.debug(
"Executing activityBehavior {} on activity '{}' with execution {}",
activityBehavior.getClass(),
flowNode.getId(),
execution.getId()
); | if (
Context.getProcessEngineConfiguration() != null &&
Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()
) {
Context.getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(
ActivitiEventBuilder.createActivityEvent(
ActivitiEventType.ACTIVITY_STARTED,
execution,
flowNode
)
);
}
try {
activityBehavior.execute(execution);
} catch (BpmnError error) {
// re-throw business fault so that it can be caught by an Error Intermediate Event or Error Event Sub-Process in the process
ErrorPropagation.propagateError(error, execution);
} catch (RuntimeException e) {
if (LogMDC.isMDCEnabled()) {
LogMDC.putMDCExecution(execution);
}
throw e;
}
} else {
logger.debug("No activityBehavior on activity '{}' with execution {}", flowNode.getId(), execution.getId());
}
}
protected void executeAsynchronous(FlowNode flowNode) {
JobEntity job = commandContext.getJobManager().createAsyncJob(execution, flowNode.isExclusive());
commandContext.getJobManager().scheduleAsyncJob(job);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\agenda\ContinueMultiInstanceOperation.java | 1 |
请完成以下Java代码 | public void updateQtyTU(final I_C_Invoice_Line_Alloc invoiceLineAlloc)
{
final IProductBL productBL = Services.get(IProductBL.class);
//
// Get Invoice Line
if (invoiceLineAlloc.getC_InvoiceLine_ID() <= 0)
{
return; // shouldn't happen, but it's not really our business
}
final I_C_InvoiceLine invoiceLine = InterfaceWrapperHelper.create(invoiceLineAlloc.getC_InvoiceLine(), I_C_InvoiceLine.class);
final boolean isFreightCost = productBL
.getProductType(ProductId.ofRepoId(invoiceLine.getM_Product_ID()))
.isFreightCost();
if (isFreightCost)
{
// the freight cost doesn't need any Qty TU
invoiceLine.setQtyEnteredTU(BigDecimal.ZERO);
save(invoiceLine);
return;
}
// 08469
final BigDecimal qtyTUs;
final I_M_InOutLine iol = InterfaceWrapperHelper.create(invoiceLine.getM_InOutLine(), I_M_InOutLine.class);
if (iol != null)
{
qtyTUs = iol.getQtyEnteredTU();
}
//
// Update Invoice Line
else
{
qtyTUs = calculateQtyTUsFromInvoiceCandidates(invoiceLine);
}
invoiceLine.setQtyEnteredTU(qtyTUs);
save(invoiceLine); | }
private final BigDecimal calculateQtyTUsFromInvoiceCandidates(final I_C_InvoiceLine invoiceLine)
{
BigDecimal qtyEnteredTU = BigDecimal.ZERO;
final IInvoiceCandDAO invoiceCandDAO = Services.get(IInvoiceCandDAO.class);
final List<I_C_Invoice_Candidate> icForIl = invoiceCandDAO.retrieveIcForIl(invoiceLine);
for (final I_C_Invoice_Candidate ic : icForIl)
{
final de.metas.handlingunits.model.I_C_Invoice_Candidate icExt = InterfaceWrapperHelper.create(ic, de.metas.handlingunits.model.I_C_Invoice_Candidate.class);
final BigDecimal icQtyEnteredTU = icExt.getQtyEnteredTU();
if (icQtyEnteredTU != null) // safety
{
qtyEnteredTU = qtyEnteredTU.add(icQtyEnteredTU);
}
}
return qtyEnteredTU;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\C_Invoice_Line_Alloc.java | 1 |
请完成以下Java代码 | public void setIsAllowOnSales (final boolean IsAllowOnSales)
{
set_Value (COLUMNNAME_IsAllowOnSales, IsAllowOnSales);
}
@Override
public boolean isAllowOnSales()
{
return get_ValueAsBoolean(COLUMNNAME_IsAllowOnSales);
}
@Override
public I_M_CostElement getM_CostElement()
{
return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class);
}
@Override
public void setM_CostElement(final I_M_CostElement M_CostElement)
{
set_ValueFromPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class, M_CostElement);
}
@Override
public void setM_CostElement_ID (final int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_Value (COLUMNNAME_M_CostElement_ID, null);
else
set_Value (COLUMNNAME_M_CostElement_ID, M_CostElement_ID);
}
@Override
public int getM_CostElement_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostElement_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID() | {
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName (final String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue (final String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Cost_Type.java | 1 |
请完成以下Java代码 | public List<Object> getContent() {
if (content == null) {
content = new ArrayList<Object>();
}
return this.content;
}
/**
* Gets the value of the target property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTarget() {
return target;
}
/**
* Sets the value of the target property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTarget(String value) {
this.target = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
} | /**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets a map that contains attributes that aren't bound to any typed property on this class.
*
* <p>
* the map is keyed by the name of the attribute and
* the value is the string value of the attribute.
*
* the map returned by this method is live, and you can add new attribute
* by updating the map directly. Because of this design, there's no setter.
*
*
* @return
* always non-null
*/
public Map<QName, String> getOtherAttributes() {
return otherAttributes;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EncryptionPropertyType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getUploadDate() {
return uploadDate;
}
public void setUploadDate(String uploadDate) {
this.uploadDate = uploadDate;
}
public Attachment metadata(AttachmentMetadata metadata) {
this.metadata = metadata;
return this;
}
/**
* Get metadata
* @return metadata
**/
@Schema(description = "")
public AttachmentMetadata getMetadata() {
return metadata;
}
public void setMetadata(AttachmentMetadata metadata) {
this.metadata = metadata;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Attachment attachment = (Attachment) o;
return Objects.equals(this._id, attachment._id) &&
Objects.equals(this.filename, attachment.filename) &&
Objects.equals(this.contentType, attachment.contentType) &&
Objects.equals(this.uploadDate, attachment.uploadDate) &&
Objects.equals(this.metadata, attachment.metadata);
}
@Override
public int hashCode() { | return Objects.hash(_id, filename, contentType, uploadDate, metadata);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Attachment {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" filename: ").append(toIndentedString(filename)).append("\n");
sb.append(" contentType: ").append(toIndentedString(contentType)).append("\n");
sb.append(" uploadDate: ").append(toIndentedString(uploadDate)).append("\n");
sb.append(" metadata: ").append(toIndentedString(metadata)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-document-api\src\main\java\io\swagger\client\model\Attachment.java | 2 |
请完成以下Java代码 | public abstract class AbstractPrintingQueueSource implements IPrintingQueueSource
{
private String name;
@Override
public String getName()
{
return name;
}
@Override
public void setName(String name)
{
this.name = name;
} | @Override
public boolean isPrinted(@NonNull final I_C_Printing_Queue item)
{
final boolean printed = item.isProcessed();
return printed;
}
@Override
public void markPrinted(@NonNull final I_C_Printing_Queue item)
{
item.setProcessed(true);
InterfaceWrapperHelper.save(item);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\AbstractPrintingQueueSource.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static <T extends Collection<InetSocketAddress>> T collect(@NonNull T collection,
@NonNull Collection<InetSocketAddress> socketAddressesToCollect) {
CollectionUtils.nullSafeCollection(socketAddressesToCollect).stream()
.filter(Objects::nonNull)
.forEach(collection::add);
return collection;
}
}
protected static class PoolConnectionEndpoint extends ConnectionEndpoint {
protected static PoolConnectionEndpoint from(@NonNull ConnectionEndpoint connectionEndpoint) {
return new PoolConnectionEndpoint(connectionEndpoint.getHost(), connectionEndpoint.getPort());
}
private Pool pool;
PoolConnectionEndpoint(@NonNull String host, int port) {
super(host, port);
}
public Optional<Pool> getPool() {
return Optional.ofNullable(this.pool);
}
public @NonNull PoolConnectionEndpoint with(@Nullable Pool pool) {
this.pool = pool;
return this;
}
/**
* @inheritDoc
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof PoolConnectionEndpoint)) {
return false;
}
PoolConnectionEndpoint that = (PoolConnectionEndpoint) obj; | return super.equals(that)
&& this.getPool().equals(that.getPool());
}
/**
* @inheritDoc
*/
@Override
public int hashCode() {
int hashValue = super.hashCode();
hashValue = 37 * hashValue + ObjectUtils.nullSafeHashCode(getPool());
return hashValue;
}
/**
* @inheritDoc
*/
@Override
public String toString() {
return String.format("ConnectionEndpoint [%1$s] from Pool [%2$s]",
super.toString(), getPool().map(Pool::getName).orElse(""));
}
}
@SuppressWarnings("unused")
protected static class SocketCreationException extends RuntimeException {
protected SocketCreationException() { }
protected SocketCreationException(String message) {
super(message);
}
protected SocketCreationException(Throwable cause) {
super(cause);
}
protected SocketCreationException(String message, Throwable cause) {
super(message, cause);
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterAwareConfiguration.java | 2 |
请完成以下Java代码 | public boolean isCopyPasteActionAllowed(final CopyPasteActionType actionType)
{
if (activeCopyPasteSupport == null)
{
return false;
}
return activeCopyPasteSupport.isCopyPasteActionAllowed(actionType);
}
private class CopyPasteActionProxy extends AbstractAction
{
private static final long serialVersionUID = 1L;
private final CopyPasteActionType actionType;
public CopyPasteActionProxy(final CopyPasteActionType actionType)
{
super();
this.actionType = actionType;
}
@Override
public void actionPerformed(final ActionEvent e)
{
final ICopyPasteSupportEditor copyPasteSupport = getActiveCopyPasteEditor();
if (copyPasteSupport == null)
{
return;
}
copyPasteSupport.executeCopyPasteAction(actionType);
}
private final ICopyPasteSupportEditor getActiveCopyPasteEditor()
{
return activeCopyPasteSupport;
}
}
/**
* Action implementation which forwards a given {@link CopyPasteActionType} to {@link ICopyPasteSupportEditor}.
*
* To be used only when the component does not already have a registered handler for this action type.
*
* @author tsa
*
*/
private static class CopyPasteAction extends AbstractAction
{
private static final Action getCreateAction(final ICopyPasteSupportEditor copyPasteSupport, final CopyPasteActionType actionType) | {
Action action = copyPasteSupport.getCopyPasteAction(actionType);
if (action == null)
{
action = new CopyPasteAction(copyPasteSupport, actionType);
}
copyPasteSupport.putCopyPasteAction(actionType, action, actionType.getKeyStroke());
return action;
}
private static final long serialVersionUID = 1L;
private final ICopyPasteSupportEditor copyPasteSupport;
private final CopyPasteActionType actionType;
public CopyPasteAction(final ICopyPasteSupportEditor copyPasteSupport, final CopyPasteActionType actionType)
{
super();
this.copyPasteSupport = copyPasteSupport;
this.actionType = actionType;
}
@Override
public void actionPerformed(final ActionEvent e)
{
copyPasteSupport.executeCopyPasteAction(actionType);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLookupCopyPasteSupportEditor.java | 1 |
请完成以下Java代码 | private Object[] determineInstancedParameters(final Method mappedMethod, final Throwable exception) {
final Parameter[] parameters = mappedMethod.getParameters();
final Object[] instancedParams = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
final Class<?> parameterClass = convertToClass(parameters[i]);
if (parameterClass.isAssignableFrom(exception.getClass())) {
instancedParams[i] = exception;
break;
}
}
return instancedParams;
}
private Class<?> convertToClass(final Parameter parameter) {
final Type paramType = parameter.getParameterizedType();
if (paramType instanceof Class) {
return (Class<?>) paramType;
} | throw new IllegalStateException("Parameter type of method has to be from Class, it was: " + paramType);
}
private Object invokeMappedMethodSafely(
final Method mappedMethod,
final Object instanceOfMappedMethod,
final Object[] instancedParams) throws Throwable {
try {
return mappedMethod.invoke(instanceOfMappedMethod, instancedParams);
} catch (InvocationTargetException | IllegalAccessException e) {
throw e.getCause(); // throw the exception thrown by implementation
}
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\advice\GrpcAdviceExceptionHandler.java | 1 |
请完成以下Java代码 | public String getTextValue() {
return text;
}
public void setTextValue(String textValue) {
this.text = textValue;
}
public String getTextValue2() {
return text2;
}
public void setTextValue2(String textValue2) {
this.text2 = textValue2;
}
public Long getLongValue() {
return longValue;
}
public void setLongValue(Long longValue) { | this.longValue = longValue;
}
public Double getDoubleValue() {
return doubleValue;
}
public void setDoubleValue(Double doubleValue) {
this.doubleValue = doubleValue;
}
public byte[] getByteArrayValue() {
return byteArrayValue;
}
public void setByteArrayValue(byte[] bytes) {
this.byteArrayValue = bytes;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\ValueFieldsImpl.java | 1 |
请完成以下Java代码 | public DateSequenceGeneratorBuilder byMonths(final int months, final int dayOfMonth)
{
return incrementor(CalendarIncrementors.eachNthMonth(months, dayOfMonth));
}
public DateSequenceGeneratorBuilder frequency(@NonNull final Frequency frequency)
{
incrementor(createCalendarIncrementor(frequency));
exploder(createDateSequenceExploder(frequency));
return this;
}
private static ICalendarIncrementor createCalendarIncrementor(final Frequency frequency)
{
if (frequency.isWeekly())
{
return CalendarIncrementors.eachNthWeek(frequency.getEveryNthWeek(), DayOfWeek.MONDAY);
}
else if (frequency.isMonthly())
{
return CalendarIncrementors.eachNthMonth(frequency.getEveryNthMonth(), 1); // every given month, 1st day
}
else
{
throw new IllegalArgumentException("Frequency type not supported for " + frequency);
}
}
private static IDateSequenceExploder createDateSequenceExploder(final Frequency frequency)
{ | if (frequency.isWeekly())
{
if (frequency.isOnlySomeDaysOfTheWeek())
{
return DaysOfWeekExploder.of(frequency.getOnlyDaysOfWeek());
}
else
{
return DaysOfWeekExploder.ALL_DAYS_OF_WEEK;
}
}
else if (frequency.isMonthly())
{
return DaysOfMonthExploder.of(frequency.getOnlyDaysOfMonth());
}
else
{
throw new IllegalArgumentException("Frequency type not supported for " + frequency);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\generator\DateSequenceGenerator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Duration getMaxAcquireTime() {
return this.maxAcquireTime;
}
public void setMaxAcquireTime(@Nullable Duration maxAcquireTime) {
this.maxAcquireTime = maxAcquireTime;
}
public int getAcquireRetry() {
return this.acquireRetry;
}
public void setAcquireRetry(int acquireRetry) {
this.acquireRetry = acquireRetry;
}
public @Nullable Duration getMaxCreateConnectionTime() {
return this.maxCreateConnectionTime;
}
public void setMaxCreateConnectionTime(@Nullable Duration maxCreateConnectionTime) {
this.maxCreateConnectionTime = maxCreateConnectionTime;
}
public int getInitialSize() {
return this.initialSize;
}
public void setInitialSize(int initialSize) {
this.initialSize = initialSize;
}
public int getMaxSize() {
return this.maxSize;
}
public void setMaxSize(int maxSize) {
this.maxSize = maxSize;
}
public @Nullable String getValidationQuery() {
return this.validationQuery;
} | public void setValidationQuery(@Nullable String validationQuery) {
this.validationQuery = validationQuery;
}
public ValidationDepth getValidationDepth() {
return this.validationDepth;
}
public void setValidationDepth(ValidationDepth validationDepth) {
this.validationDepth = validationDepth;
}
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\autoconfigure\R2dbcProperties.java | 2 |
请完成以下Java代码 | public Optional<TreeNode> getTreeNode(@NonNull final ElementValueId elementValueId, @NonNull final AdTreeId chartOfAccountsTreeId)
{
final I_AD_TreeNode treeNodeRecord = retrieveTreeNodeRecord(elementValueId, chartOfAccountsTreeId);
return treeNodeRecord != null
? Optional.of(toTreeNode(treeNodeRecord))
: Optional.empty();
}
public void recreateTree(@NonNull final List<TreeNode> treeNodes)
{
final AdTreeId chartOfAccountsTreeId = extractSingleChartOfAccountsTreeId(treeNodes);
deleteByTreeId(chartOfAccountsTreeId);
treeNodes.forEach(this::createNew);
}
private static AdTreeId extractSingleChartOfAccountsTreeId(final @NonNull List<TreeNode> treeNodes)
{
final ImmutableSet<AdTreeId> chartOfAccountsTreeIds = treeNodes.stream()
.map(TreeNode::getChartOfAccountsTreeId)
.collect(ImmutableSet.toImmutableSet()); | return CollectionUtils.singleElement(chartOfAccountsTreeIds);
}
private void deleteByTreeId(final AdTreeId chartOfAccountsTreeId)
{
queryBL.createQueryBuilder(I_AD_TreeNode.class)
.addEqualsFilter(I_AD_TreeNode.COLUMNNAME_AD_Tree_ID, chartOfAccountsTreeId)
.create()
.deleteDirectly();
}
public ImmutableSet<TreeNode> getByTreeId(final AdTreeId chartOfAccountsTreeId)
{
return queryBL.createQueryBuilder(I_AD_TreeNode.class)
.addEqualsFilter(I_AD_TreeNode.COLUMNNAME_AD_Tree_ID, chartOfAccountsTreeId)
.create()
.stream()
.map(TreeNodeRepository::toTreeNode)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\treenode\TreeNodeRepository.java | 1 |
请完成以下Java代码 | private @Nullable Class<?> findExistingLoadedClass(String name) {
Class<?> resultClass = findLoadedClass0(name);
resultClass = (resultClass != null || JreCompat.isGraalAvailable()) ? resultClass : findLoadedClass(name);
return resultClass;
}
private @Nullable Class<?> doLoadClass(String name) {
if ((this.delegate || filter(name, true))) {
Class<?> result = loadFromParent(name);
return (result != null) ? result : findClassIgnoringNotFound(name);
}
Class<?> result = findClassIgnoringNotFound(name);
return (result != null) ? result : loadFromParent(name);
}
private Class<?> resolveIfNecessary(Class<?> resultClass, boolean resolve) {
if (resolve) {
resolveClass(resultClass);
}
return (resultClass);
}
@Override
protected void addURL(URL url) {
// Ignore URLs added by the Tomcat 8 implementation (see gh-919)
if (logger.isTraceEnabled()) {
logger.trace("Ignoring request to add " + url + " to the tomcat classloader");
}
}
private @Nullable Class<?> loadFromParent(String name) { | if (this.parent == null) {
return null;
}
try {
return Class.forName(name, false, this.parent);
}
catch (ClassNotFoundException ex) {
return null;
}
}
private @Nullable Class<?> findClassIgnoringNotFound(String name) {
try {
return findClass(name);
}
catch (ClassNotFoundException ex) {
return null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\TomcatEmbeddedWebappClassLoader.java | 1 |
请完成以下Java代码 | public class PurchaseCandidates2PurchaseViewFactory extends PurchaseViewFactoryTemplate
{
public static final String WINDOW_ID_STRING = "purchaseCandidates2po";
public static final WindowId WINDOW_ID = WindowId.fromJson(WINDOW_ID_STRING);
// services
private final PurchaseCandidateRepository purchaseCandidatesRepo;
public PurchaseCandidates2PurchaseViewFactory(
@NonNull final PurchaseDemandWithCandidatesService purchaseDemandWithCandidatesService,
@NonNull final AvailabilityCheckService availabilityCheckService,
@NonNull final PurchaseCandidateRepository purchaseCandidatesRepo,
@NonNull final PurchaseRowFactory purchaseRowFactory)
{
super(WINDOW_ID,
WEBUI_PurchaseCandidates_PurchaseView_Launcher.class, // launcherProcessClass
purchaseDemandWithCandidatesService,
availabilityCheckService,
purchaseRowFactory);
this.purchaseCandidatesRepo = purchaseCandidatesRepo;
}
@Override
protected List<PurchaseDemand> getDemands(@NonNull final CreateViewRequest request)
{
final Set<PurchaseCandidateId> purchaseCandidateIds = PurchaseCandidateId.ofRepoIds(request.getFilterOnlyIds());
Check.assumeNotEmpty(purchaseCandidateIds, "purchaseCandidateIds is not empty");
final List<PurchaseCandidate> purchaseCandidates = purchaseCandidatesRepo.getAllByIds(purchaseCandidateIds);
Check.assumeNotEmpty(purchaseCandidates, "purchaseCandidates is not empty");
return PurchaseCandidateAggregator.aggregate(purchaseCandidates)
.stream()
.map(aggregate -> toPurchaseDemand(aggregate))
.collect(ImmutableList.toImmutableList());
} | private static PurchaseDemand toPurchaseDemand(@NonNull final PurchaseCandidateAggregate aggregate)
{
return PurchaseDemand.builder()
.existingPurchaseCandidateIds(aggregate.getPurchaseCandidateIds())
//
.orgId(aggregate.getOrgId())
.warehouseId(aggregate.getWarehouseId())
//
.productId(aggregate.getProductId())
.attributeSetInstanceId(aggregate.getAttributeSetInstanceId())
//
.qtyToDeliver(aggregate.getQtyToDeliver())
//
.salesPreparationDate(aggregate.getDatePromised())
//
.build();
}
@Override
protected void onViewClosedByUser(@NonNull final PurchaseView purchaseView)
{
final List<PurchaseRow> rows = purchaseView.getRows();
PurchaseRowsSaver.builder()
.purchaseCandidatesRepo(purchaseCandidatesRepo)
.build()
.save(rows);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\view\PurchaseCandidates2PurchaseViewFactory.java | 1 |
请完成以下Java代码 | private static class RowsLoader
{
private final BPartnerProductStatsService bpartnerProductStatsService;
private final MoneyService moneyService;
private final LookupDataSource bpartnerLookup;
private final LookupDataSource productLookup;
private final DocumentIdIntSequence nextRowIdSequence = DocumentIdIntSequence.newInstance();
private final BPartnerId excludeBPartnerId;
private final Set<ProductId> productIds;
private final CurrencyId currencyId;
@Builder
private RowsLoader(
@NonNull final BPartnerProductStatsService bpartnerProductStatsService,
@NonNull final MoneyService moneyService,
@NonNull final LookupDataSourceFactory lookupDataSourceFactory,
//
@Nullable final BPartnerId excludeBPartnerId,
@NonNull final Set<ProductId> productIds,
@Nullable CurrencyId curencyId)
{
Check.assumeNotEmpty(productIds, "productIds is not empty");
this.bpartnerProductStatsService = bpartnerProductStatsService;
this.moneyService = moneyService;
this.bpartnerLookup = lookupDataSourceFactory.searchInTableLookup(I_C_BPartner.Table_Name);
this.productLookup = lookupDataSourceFactory.searchInTableLookup(I_M_Product.Table_Name);
this.excludeBPartnerId = excludeBPartnerId;
this.productIds = ImmutableSet.copyOf(productIds);
this.currencyId = curencyId;
}
public ProductsProposalRowsData load()
{
final List<ProductsProposalRow> rows = bpartnerProductStatsService.getByProductIds(productIds, currencyId)
.stream()
// .filter(stats -> excludeBPartnerId == null || !BPartnerId.equals(stats.getBpartnerId(), excludeBPartnerId))
.map(this::toProductsProposalRowOrNull)
.filter(Objects::nonNull)
.sorted(Comparator.comparing(ProductsProposalRow::getProductName)
.thenComparing(Comparator.comparing(ProductsProposalRow::getLastSalesInvoiceDate)).reversed())
.collect(ImmutableList.toImmutableList()); | return ProductsProposalRowsData.builder()
.nextRowIdSequence(nextRowIdSequence)
.rows(rows)
.soTrx(SOTrx.SALES)
.currencyId(currencyId)
.build();
}
private ProductsProposalRow toProductsProposalRowOrNull(@NonNull final BPartnerProductStats stats)
{
final LastInvoiceInfo lastSalesInvoice = stats.getLastSalesInvoice();
if (lastSalesInvoice == null)
{
return null;
}
return ProductsProposalRow.builder()
.id(nextRowIdSequence.nextDocumentId())
.bpartner(bpartnerLookup.findById(stats.getBpartnerId()))
.product(productLookup.findById(stats.getProductId()))
.price(ProductProposalPrice.builder()
.priceListPrice(moneyService.toAmount(lastSalesInvoice.getPrice()))
.build())
.lastShipmentDays(stats.getLastShipmentInDays())
.lastSalesInvoiceDate(lastSalesInvoice.getInvoiceDate())
.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\OtherSalePricesProductsProposalViewFactory.java | 1 |
请完成以下Java代码 | public static MQuery getQuery(
ProjectType projectType,
MGoalRestriction[] restrictions,
String MeasureDisplay, Timestamp date, int C_Phase_ID,
final IUserRolePermissions role)
{
String dateColumn = "Created";
String orgColumn = "AD_Org_ID";
String bpColumn = "C_BPartner_ID";
String pColumn = null;
//
MQuery query = new MQuery("C_Project");
query.addRangeRestriction("C_ProjectType_ID", "=", projectType.getId().getRepoId());
//
String where = null;
if (C_Phase_ID != 0)
where = "C_Phase_ID=" + C_Phase_ID;
else
{
String trunc = "D";
if (MGoal.MEASUREDISPLAY_Year.equals(MeasureDisplay))
trunc = "Y"; | else if (MGoal.MEASUREDISPLAY_Quarter.equals(MeasureDisplay))
trunc = "Q";
else if (MGoal.MEASUREDISPLAY_Month.equals(MeasureDisplay))
trunc = "MM";
else if (MGoal.MEASUREDISPLAY_Week.equals(MeasureDisplay))
trunc = "W";
// else if (MGoal.MEASUREDISPLAY_Day.equals(MeasureDisplay))
// trunc = "D";
where = "TRUNC(" + dateColumn + ",'" + trunc
+ "')=TRUNC(" + DB.TO_DATE(date) + ",'" + trunc + "')";
}
String sql = MMeasureCalc.addRestrictions(where + " AND Processed<>'Y' ",
true, restrictions, role,
"C_Project", orgColumn, bpColumn, pColumn);
query.addRestriction(sql);
query.setRecordCount(1);
return query;
} // getQuery
} // MMeasure | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MMeasure.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrgData
{
public static final OrgData ofAD_Org_ID(final Properties ctx)
{
final OrgId adOrgId = Env.getOrgId(ctx);
return new OrgData(adOrgId);
}
private final OrgId adOrgId;
private transient String orgName; // lazy
private OrgData(final OrgId adOrgId)
{
this.adOrgId = adOrgId;
}
public String getName() | {
String orgName = this.orgName;
if (orgName == null)
{
orgName = this.orgName = Services.get(IOrgDAO.class).retrieveOrgName(adOrgId);
}
return orgName;
}
public InputStream getLogo()
{
// TODO: refactor from de.metas.adempiere.report.jasper.OrgLogoLocalFileLoader
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\OrgData.java | 2 |
请完成以下Java代码 | public void setM_Inventory_ID (int M_Inventory_ID)
{
if (M_Inventory_ID < 1)
set_Value (COLUMNNAME_M_Inventory_ID, null);
else
set_Value (COLUMNNAME_M_Inventory_ID, Integer.valueOf(M_Inventory_ID));
}
/** Get Inventur.
@return Parameters for a Physical Inventory
*/
@Override
public int getM_Inventory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Inventory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override | public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutConfirm.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonExternalSystemRetriever
{
private final IOrgDAO orgDAO = Services.get(IOrgDAO.class);
@NonNull
public JsonExternalSystemInfo retrieveExternalSystemInfo(@NonNull final ExternalSystemParentConfig parentConfig)
{
final IExternalSystemChildConfig childConfig = parentConfig.getChildConfig();
final String orgCode = orgDAO.retrieveOrgValue(parentConfig.getOrgId());
return JsonExternalSystemInfo.builder()
.externalSystemConfigId(JsonMetasfreshId.of(parentConfig.getId().getRepoId()))
.externalSystemName(JsonExternalSystemName.of(parentConfig.getType().getValue()))
.externalSystemChildConfigValue(childConfig.getValue())
.orgCode(orgCode)
.parameters(getParameters(parentConfig))
.build();
}
@NonNull
private static Map<String, String> getParameters(@NonNull final ExternalSystemParentConfig config)
{
if (config.getType().isGRSSignum())
{ | final ExternalSystemGRSSignumConfig grsConfig = ExternalSystemGRSSignumConfig.cast(config.getChildConfig());
return getGRSSignumParameters(grsConfig);
}
throw new AdempiereException("Unsupported externalSystemConfigType=" + config.getType());
}
@NonNull
private static Map<String, String> getGRSSignumParameters(@NonNull final ExternalSystemGRSSignumConfig grsSignumConfig)
{
final Map<String, String> parameters = new HashMap<>();
if (grsSignumConfig.isCreateBPartnerFolders())
{
parameters.put(PARAM_BasePathForExportDirectories, grsSignumConfig.getBasePathForExportDirectories());
}
return ImmutableMap.copyOf(parameters);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\externlasystem\JsonExternalSystemRetriever.java | 2 |
请完成以下Java代码 | public void setBackground (Color color)
{
m_text.setBackground(color);
btnConnection.setBackground(color);
} // setBackground
/**
* Set Editor to value
* @param value value of the editor
*/
@Override
public void setValue (final Object value)
{
if (value instanceof CConnection)
{
m_value = (CConnection)value;
}
else
{
m_value = null;
}
setDisplay();
} // setValue
/**
* Return Editor value
* @return current value
*/
@Override
public CConnection getValue()
{
return m_value;
} // getValue
/**
* Return Display Value
* @return displayed String value
*/
@Override
public String getDisplay()
{
if (m_value == null)
return "";
return m_value.getDbHost();
} // getDisplay
/**
* Update Display with Connection info
*/
public void setDisplay()
{
m_text.setText(getDisplay());
final boolean isDatabaseOK = m_value != null && m_value.isDatabaseOK();
// Mark the text field as error if both AppsServer and DB connections are not established
setBackground(!isDatabaseOK);
// Mark the connection indicator button as error if any of AppsServer or DB connection is not established.
btnConnection.setBackground(isDatabaseOK ? AdempierePLAF.getFieldBackground_Normal() : AdempierePLAF.getFieldBackground_Error());
}
/**
* Add Action Listener
*/
public synchronized void addActionListener(final ActionListener l)
{
listenerList.add(ActionListener.class, l);
} // addActionListener
/**
* Fire Action Performed
*/
private void fireActionPerformed()
{
ActionEvent e = null;
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
for (int i = 0; i < listeners.length; i++)
{
if (e == null)
e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "actionPerformed");
listeners[i].actionPerformed(e); | }
} // fireActionPerformed
private void actionEditConnection()
{
if (!isEnabled() || !m_rw)
{
return;
}
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try
{
final CConnection connection = getValue();
final CConnectionDialog dialog = new CConnectionDialog(connection);
if (dialog.isCancel())
{
return;
}
final CConnection connectionNew = dialog.getConnection();
setValue(connectionNew);
DB.setDBTarget(connectionNew);
fireActionPerformed();
}
finally
{
setCursor(Cursor.getDefaultCursor());
}
}
/**
* MouseListener
*/
private class CConnectionEditor_MouseListener extends MouseAdapter
{
/** Mouse Clicked - Open connection editor */
@Override
public void mouseClicked(final MouseEvent e)
{
if (m_active)
return;
m_active = true;
try
{
actionEditConnection();
}
finally
{
m_active = false;
}
}
private boolean m_active = false;
}
} // CConnectionEditor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\CConnectionEditor.java | 1 |
请完成以下Java代码 | private Optional<FAOpenItemTrxInfo> computeTrxInfoFromPayment(final FAOpenItemTrxInfoComputeRequest request)
{
final PaymentId paymentId = PaymentId.ofRepoId(request.getRecordId());
final AccountConceptualName accountConceptualName = request.getAccountConceptualName();
if (accountConceptualName == null)
{
return Optional.empty();
}
else if (accountConceptualName.isAnyOf(V_Prepayment, C_Prepayment))
{
return Optional.of(FAOpenItemTrxInfo.opening(FAOpenItemKey.payment(paymentId, accountConceptualName)));
}
else
{
return Optional.empty();
}
}
@Override
public void onGLJournalLineCompleted(final SAPGLJournalLine line) {updateDocumentAllocatedAndPaidFlags(line);}
@Override
public void onGLJournalLineReactivated(final SAPGLJournalLine line) {updateDocumentAllocatedAndPaidFlags(line);}
private void updateDocumentAllocatedAndPaidFlags(final SAPGLJournalLine line)
{
final FAOpenItemTrxInfo openItemTrxInfo = line.getOpenItemTrxInfo();
if (openItemTrxInfo == null)
{
// shall not happen
return;
}
final AccountConceptualName accountConceptualName = openItemTrxInfo.getAccountConceptualName(); | if (accountConceptualName == null)
{
return;
}
if (accountConceptualName.isAnyOf(V_Liability, C_Receivable))
{
openItemTrxInfo.getKey().getInvoiceId().ifPresent(invoiceBL::scheduleUpdateIsPaid);
}
else if (accountConceptualName.isAnyOf(V_Prepayment, C_Prepayment))
{
openItemTrxInfo.getKey().getPaymentId().ifPresent(paymentBL::scheduleUpdateIsAllocated);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\open_items\handlers\BPartnerOIHandler.java | 1 |
请完成以下Java代码 | public Integer generateRandomWithThreadLocalRandomFromZero(int max) {
int randomWithThreadLocalRandomFromZero = ThreadLocalRandom.current()
.nextInt(max);
return randomWithThreadLocalRandomFromZero;
}
public Integer generateRandomWithSplittableRandom(int min, int max) {
SplittableRandom splittableRandom = new SplittableRandom();
int randomWithSplittableRandom = splittableRandom.nextInt(min, max);
return randomWithSplittableRandom;
}
public IntStream generateRandomWithSplittableRandomLimitedIntStreamWithinARange(int min, int max, long streamSize) {
SplittableRandom splittableRandom = new SplittableRandom();
IntStream limitedIntStreamWithinARangeWithSplittableRandom = splittableRandom.ints(streamSize, min, max);
return limitedIntStreamWithinARangeWithSplittableRandom;
}
public Integer generateRandomWithSecureRandom() {
SecureRandom secureRandom = new SecureRandom();
int randomWithSecureRandom = secureRandom.nextInt();
return randomWithSecureRandom;
} | public Integer generateRandomWithSecureRandomWithinARange(int min, int max) {
SecureRandom secureRandom = new SecureRandom();
int randomWithSecureRandomWithinARange = secureRandom.nextInt(max - min) + min;
return randomWithSecureRandomWithinARange;
}
public Integer generateRandomWithRandomDataGenerator(int min, int max) {
RandomDataGenerator randomDataGenerator = new RandomDataGenerator();
int randomWithRandomDataGenerator = randomDataGenerator.nextInt(min, max);
return randomWithRandomDataGenerator;
}
public Integer generateRandomWithXoRoShiRo128PlusRandom(int min, int max) {
XoRoShiRo128PlusRandom xoroRandom = new XoRoShiRo128PlusRandom();
int randomWithXoRoShiRo128PlusRandom = xoroRandom.nextInt(max - min) + min;
return randomWithXoRoShiRo128PlusRandom;
}
} | repos\tutorials-master\core-java-modules\core-java-numbers-3\src\main\java\com\baeldung\randomnumbers\RandomNumbersGenerator.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.