instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public frameset setRows(String rows)
{
addAttribute("rows",rows);
return(this);
}
/**
Sets the cols="" attribute
@param cols Sets the cols="" attribute
*/
public frameset setCols(int cols)
{
setCols(Integer.toString(cols));
return(this);
}
/**
Sets the cols="" attribute
@param cols Sets the cols="" attribute
*/
public frameset setCols(String cols)
{
addAttribute("cols",cols);
return(this);
}
/**
Sets the lang="" and xml:lang="" attributes
@param lang the lang="" and xml:lang="" attributes
*/
public Element setLang(String lang)
{
addAttribute("lang",lang);
addAttribute("xml:lang",lang);
return this;
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public frameset addElement(String hashcode,Element element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param hashcode name of element for hash table
@param element Adds an Element to the element.
*/
public frameset addElement(String hashcode,String element)
{
addElementToRegistry(hashcode,element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public frameset addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element. | @param element Adds an Element to the element.
*/
public frameset addElement(String element)
{
addElementToRegistry(element);
return(this);
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public frameset removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
/**
The onload event occurs when the user agent finishes loading a window
or all frames within a frameset. This attribute may be used with body
and frameset elements.
@param The script
*/
public void setOnLoad(String script)
{
addAttribute ( "onload", script );
}
/**
The onunload event occurs when the user agent removes a document from a
window or frame. This attribute may be used with body and frameset
elements.
@param The script
*/
public void setOnUnload(String script)
{
addAttribute ( "onunload", script );
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\frameset.java | 1 |
请完成以下Java代码 | public I_M_Attribute retrieveADRAttribute(final org.compiere.model.I_C_BPartner bpartner)
{
final int adClientId = bpartner.getAD_Client_ID();
final int adOrgId = bpartner.getAD_Org_ID();
return retrieveADRAttribute(adClientId, adOrgId);
}
@Override
public I_M_Attribute retrieveADRAttribute(Properties ctx)
{
final int adClientId = Env.getAD_Client_ID(ctx);
final int adOrgId = Env.getAD_Org_ID(ctx);
return retrieveADRAttribute(adClientId, adOrgId);
}
private I_M_Attribute retrieveADRAttribute(int adClientId, int adOrgId)
{
final AttributeId adrAttributeId = retrieveADRAttributeId(adClientId, adOrgId);
if (adrAttributeId == null)
{
return null;
}
return Services.get(IAttributeDAO.class).getAttributeRecordById(adrAttributeId);
}
@Override | public AttributeListValue retrieveADRAttributeValue(final Properties ctx, @NonNull final I_C_BPartner partner, boolean isSOTrx)
{
final String adrRegionValue = Services.get(IADRAttributeBL.class).getADRForBPartner(partner, isSOTrx);
if (Check.isEmpty(adrRegionValue, true))
{
return null;
}
final I_M_Attribute adrAttribute = retrieveADRAttribute(partner);
if (adrAttribute == null)
{
return null;
}
return Services.get(IAttributeDAO.class).retrieveAttributeValueOrNull(adrAttribute, adrRegionValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\ADRAttributeDAO.java | 1 |
请完成以下Java代码 | public void collectDocumentSaveStatusChanged(final DocumentPath documentPath, final DocumentSaveStatus documentSaveStatus)
{
// do nothing
}
@Override
public void collectDeleted(final DocumentPath documentPath)
{
// do nothing
}
@Override
public void collectStaleDetailId(final DocumentPath rootDocumentPath, final DetailId detailId)
{
// do nothing
}
@Override
public void collectAllowNew(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowNew)
{ | // do nothing
}
@Override
public void collectAllowDelete(final DocumentPath rootDocumentPath, final DetailId detailId, final LogicExpressionResult allowDelete)
{
// do nothing
}
@Override
public void collectEvent(final IDocumentFieldChangedEvent event)
{
// do nothing
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\NullDocumentChangesCollector.java | 1 |
请完成以下Java代码 | public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getUsersAccess() { | return usersAccess;
}
public void setUsersAccess(String usersAccess) {
this.usersAccess = usersAccess;
}
public String getGroupsAccess() {
return groupsAccess;
}
public void setGroupsAccess(String groupsAccess) {
this.groupsAccess = groupsAccess;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\deployer\BaseAppModel.java | 1 |
请完成以下Java代码 | protected TablePermission noPermission()
{
return TablePermission.NONE;
}
public final boolean hasAccess(final int adTableId, final Access access)
{
final TableResource resource = TableResource.ofAD_Table_ID(adTableId);
return hasAccess(resource, access);
}
public boolean isCanReport(final int AD_Table_ID)
{
return hasAccess(AD_Table_ID, Access.REPORT);
} | public boolean isCanExport(final int AD_Table_ID)
{
return hasAccess(AD_Table_ID, Access.EXPORT);
}
public static class Builder extends PermissionsBuilder<TablePermission, TablePermissions>
{
@Override
protected TablePermissions createPermissionsInstance()
{
return new TablePermissions(this);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TablePermissions.java | 1 |
请完成以下Java代码 | public void setPrintName (java.lang.String PrintName)
{
set_Value (COLUMNNAME_PrintName, PrintName);
}
/** Get Drucktext.
@return The label text to be printed on a document or correspondence.
*/
@Override
public java.lang.String getPrintName ()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintName);
}
/** Set Browse name.
@param WEBUI_NameBrowse Browse name */
@Override
public void setWEBUI_NameBrowse (java.lang.String WEBUI_NameBrowse)
{
set_Value (COLUMNNAME_WEBUI_NameBrowse, WEBUI_NameBrowse);
}
/** Get Browse name.
@return Browse name */
@Override
public java.lang.String getWEBUI_NameBrowse ()
{
return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameBrowse);
}
/** Set New record name.
@param WEBUI_NameNew New record name */
@Override
public void setWEBUI_NameNew (java.lang.String WEBUI_NameNew)
{
set_Value (COLUMNNAME_WEBUI_NameNew, WEBUI_NameNew);
}
/** Get New record name.
@return New record name */
@Override
public java.lang.String getWEBUI_NameNew ()
{
return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNew);
}
/** Set New record name (breadcrumb). | @param WEBUI_NameNewBreadcrumb New record name (breadcrumb) */
@Override
public void setWEBUI_NameNewBreadcrumb (java.lang.String WEBUI_NameNewBreadcrumb)
{
set_Value (COLUMNNAME_WEBUI_NameNewBreadcrumb, WEBUI_NameNewBreadcrumb);
}
/** Get New record name (breadcrumb).
@return New record name (breadcrumb) */
@Override
public java.lang.String getWEBUI_NameNewBreadcrumb ()
{
return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNewBreadcrumb);
}
/**
* WidgetSize AD_Reference_ID=540724
* Reference name: WidgetSize_WEBUI
*/
public static final int WIDGETSIZE_AD_Reference_ID=540724;
/** Small = S */
public static final String WIDGETSIZE_Small = "S";
/** Medium = M */
public static final String WIDGETSIZE_Medium = "M";
/** Large = L */
public static final String WIDGETSIZE_Large = "L";
/** Set Widget size.
@param WidgetSize Widget size */
@Override
public void setWidgetSize (java.lang.String WidgetSize)
{
set_Value (COLUMNNAME_WidgetSize, WidgetSize);
}
/** Get Widget size.
@return Widget size */
@Override
public java.lang.String getWidgetSize ()
{
return (java.lang.String)get_Value(COLUMNNAME_WidgetSize);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Element.java | 1 |
请完成以下Java代码 | public Object getAsJsonObject(
@NonNull final String fieldName,
@NonNull final JSONOptions jsonOpts)
{
final Object valueObj = map.get(fieldName);
if (JSONNullValue.isNull(valueObj))
{
return null;
}
else if (valueObj instanceof ITranslatableString)
{
return ((ITranslatableString)valueObj).translate(jsonOpts.getAdLanguage());
}
else
{
return Values.valueToJsonObject(valueObj, jsonOpts);
}
}
public int getAsInt(@NonNull final String fieldName, final int defaultValueIfNotFoundOrError)
{
final Object valueObj = map.get(fieldName);
if (JSONNullValue.toNullIfInstance(valueObj) == null)
{
return defaultValueIfNotFoundOrError;
}
else if (valueObj instanceof Number)
{
return ((Number)valueObj).intValue();
}
else if (valueObj instanceof LookupValue)
{
return ((LookupValue)valueObj).getIdAsInt();
}
else if (valueObj instanceof JSONLookupValue)
{
return ((JSONLookupValue)valueObj).getKeyAsInt();
}
else
{ | return NumberUtils.asInt(valueObj, defaultValueIfNotFoundOrError);
}
}
public BigDecimal getAsBigDecimal(@NonNull final String fieldName, final BigDecimal defaultValueIfNotFoundOrError)
{
final Object valueObj = map.get(fieldName);
if (JSONNullValue.isNull(valueObj))
{
return defaultValueIfNotFoundOrError;
}
else
{
return NumberUtils.asBigDecimal(valueObj, defaultValueIfNotFoundOrError);
}
}
public boolean getAsBoolean(@NonNull final String fieldName, final boolean defaultValueIfNotFoundOrError)
{
final Object valueObj = map.get(fieldName);
return StringUtils.toBoolean(valueObj, defaultValueIfNotFoundOrError);
}
public boolean isEmpty(@NonNull final String fieldName)
{
final Object valueObj = map.get(fieldName);
return valueObj == null || JSONNullValue.isNull(valueObj) || valueObj.toString().isEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowFieldNameAndJsonValues.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class ClientRequests {
/**
* Name of the observation for client requests.
*/
private String name = "http.client.requests";
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
}
public static class Server {
private final ServerRequests requests = new ServerRequests();
public ServerRequests getRequests() {
return this.requests;
}
public static class ServerRequests {
/**
* Name of the observation for server requests.
*/
private String name = "http.server.requests"; | public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-observation\src\main\java\org\springframework\boot\micrometer\observation\autoconfigure\ObservationProperties.java | 2 |
请完成以下Java代码 | public ObjectIdentity getObjectIdentity() {
throw new UnsupportedOperationException("Stub only");
}
@Override
public Sid getOwner() {
throw new UnsupportedOperationException("Stub only");
}
@Override
public Acl getParentAcl() {
throw new UnsupportedOperationException("Stub only");
}
@Override
public boolean isEntriesInheriting() {
throw new UnsupportedOperationException("Stub only");
} | @Override
public boolean isGranted(List<Permission> permission, List<Sid> sids, boolean administrativeMode)
throws NotFoundException, UnloadedSidException {
throw new UnsupportedOperationException("Stub only");
}
@Override
public boolean isSidLoaded(List<Sid> sids) {
throw new UnsupportedOperationException("Stub only");
}
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\jdbc\BasicLookupStrategy.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DeploymentBuilder disableSchemaValidation() {
this.isBpmn20XsdValidationEnabled = false;
return this;
}
public DeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
public DeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true;
return this;
}
public DeploymentBuilder activateProcessDefinitionsOn(Date date) {
this.processDefinitionsActivationDate = date;
return this;
}
@Override
public DeploymentBuilder deploymentProperty(String propertyKey, Object propertyValue) {
deploymentProperties.put(propertyKey, propertyValue);
return this;
}
public Deployment deploy() {
return repositoryService.deploy(this);
}
// getters and setters
// //////////////////////////////////////////////////////
public DeploymentEntity getDeployment() {
return deployment;
} | public boolean isProcessValidationEnabled() {
return isProcessValidationEnabled;
}
public boolean isBpmn20XsdValidationEnabled() {
return isBpmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
public Date getProcessDefinitionsActivationDate() {
return processDefinitionsActivationDate;
}
public Map<String, Object> getDeploymentProperties() {
return deploymentProperties;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\repository\DeploymentBuilderImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static <T> BaseResult<T> buildWithParam(ResponseParam param) {
return new BaseResult<>(param.getCode(), param.getMsg(), null);
}
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
public static class ResponseParam {
private int code;
private String msg;
private ResponseParam(int code, String msg) {
this.code = code;
this.msg = msg;
}
public static ResponseParam buildParam(int code, String msg) {
return new ResponseParam(code, msg);
} | public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\config\BaseResult.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setQueueCapacity(int queueCapacity) {
AsyncExecutor.queueCapacity = queueCapacity;
}
/**
* 自定义线程池,用法 @Async
* @return Executor
*/
@Override
public Executor getAsyncExecutor() {
// 自定义工厂
ThreadFactory factory = r -> new Thread(r, "el-async-" + new AtomicInteger(1).getAndIncrement());
// 自定义线程池
return new ThreadPoolExecutor(corePoolSize, maxPoolSize, keepAliveSeconds,
TimeUnit.SECONDS, new ArrayBlockingQueue<>(queueCapacity), factory,
new ThreadPoolExecutor.CallerRunsPolicy());
}
/**
* 自定义线程池,用法,注入到类中使用 | * private ThreadPoolTaskExecutor taskExecutor;
* @return ThreadPoolTaskExecutor
*/
@Bean("taskAsync")
public ThreadPoolTaskExecutor taskAsync() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(4);
executor.setQueueCapacity(20);
executor.setKeepAliveSeconds(60);
executor.setThreadNamePrefix("el-task-");
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\AsyncExecutor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SpringContextUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
/**
* 实现ApplicationContextAware接口的context注入函数, 将其存入静态变量.
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) {
SpringContextUtils.applicationContext = applicationContext; // NOSONAR
}
/**
* 取得存储在静态变量中的ApplicationContext.
*/
public static ApplicationContext getApplicationContext() {
checkApplicationContext();
return applicationContext;
}
/**
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型.
*/
@SuppressWarnings("unchecked")
public static <T> T getBean(String name) {
checkApplicationContext();
return (T) applicationContext.getBean(name);
}
/**
* 从静态变量ApplicationContext中取得Bean, 自动转型为所赋值对象的类型. | */
public static <T> T getBean(Class<T> clazz) {
checkApplicationContext();
return (T) applicationContext.getBean(clazz);
}
/**
* 清除applicationContext静态变量.
*/
public static void cleanApplicationContext() {
applicationContext = null;
}
private static void checkApplicationContext() {
if (applicationContext == null) {
throw new IllegalStateException("applicaitonContext未注入,请在applicationContext.xml中定义SpringContextHolder");
}
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\utils\SpringContextUtils.java | 2 |
请完成以下Java代码 | public class SaveGroupCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected IdmEngineConfiguration idmEngineConfiguration;
protected Group group;
public SaveGroupCmd(Group group, IdmEngineConfiguration idmEngineConfiguration) {
this.group = group;
this.idmEngineConfiguration = idmEngineConfiguration;
}
@Override
public Void execute(CommandContext commandContext) {
if (group == null) {
throw new FlowableIllegalArgumentException("group is null");
} | if (idmEngineConfiguration.getGroupEntityManager().isNewGroup(group)) {
if (group instanceof GroupEntity) {
idmEngineConfiguration.getGroupEntityManager().insert((GroupEntity) group);
} else {
CommandContextUtil.getDbSqlSession(commandContext).insert((Entity) group, idmEngineConfiguration.getIdGenerator());
}
} else {
if (group instanceof GroupEntity) {
idmEngineConfiguration.getGroupEntityManager().update((GroupEntity) group);
} else {
CommandContextUtil.getDbSqlSession(commandContext).update((Entity) group);
}
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\cmd\SaveGroupCmd.java | 1 |
请完成以下Java代码 | private int createPDFData(@NonNull final OutputStream out)
{
try (final PrintingDataToPDFWriter printingDataToPDFWriter = new PrintingDataToPDFWriter(out))
{
int documentCurrentPage = 0;
for (final Map<ArrayKey, I_C_Print_PackageInfo> currentMap : printPackageInfos)
{
for (final I_C_Print_PackageInfo printPackageInfo : currentMap.values())
{
logger.debug("Adding {}", printPackageInfo);
final List<PrintItemPart> printItemParts = mapArchiveParts.get(printPackageInfo);
if (printItemParts == null || printItemParts.isEmpty())
{
logger.info("Skipping {} because there are not archive parts", printPackageInfo);
continue;
}
int pagesAdded = 0;
for (final PrintItemPart printItemPart : printItemParts)
{
pagesAdded += printingDataToPDFWriter.addArchivePartToPDF(printItemPart.getPrintingData(), printItemPart.getPrintingSegment());
}
if (pagesAdded == 0)
{
logger.info("Skipping {} because no pages were added", printPackageInfo);
}
final int pageFrom = documentCurrentPage + 1;
final int pageTo = pageFrom + pagesAdded - 1;
logger.debug("Added {}: PageFrom={}, PageTo={}", printPackageInfo, pageFrom, pageTo);
printPackageInfo.setPageFrom(pageFrom); | printPackageInfo.setPageTo(pageTo);
documentCurrentPage = pageTo;
}
}
if (documentCurrentPage == 0)
{
logger.info("No pages were added");
}
return documentCurrentPage;
}
}
@Value
private static class PrintItemPart
{
@NonNull PrintingData printingData;
@NonNull PrintingSegment printingSegment;
@NonNull I_C_Print_Job_Line printJobLineRecord;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintJobLinesAggregator.java | 1 |
请完成以下Java代码 | public class SslCredentialsConfig {
private boolean enabled = true;
private SslCredentialsType type;
private PemSslCredentials pem;
private KeystoreSslCredentials keystore;
private SslCredentials credentials;
private final String name;
private final boolean trustsOnly;
public SslCredentialsConfig(String name, boolean trustsOnly) {
this.name = name;
this.trustsOnly = trustsOnly;
}
@PostConstruct
public void init() {
if (this.enabled) {
log.info("{}: Initializing SSL credentials.", name);
if (SslCredentialsType.PEM.equals(type) && pem.canUse()) {
this.credentials = this.pem; | } else if (keystore.canUse()) {
if (SslCredentialsType.PEM.equals(type)) {
log.warn("{}: Specified PEM configuration is not valid. Using SSL keystore configuration as fallback.", name);
}
this.credentials = this.keystore;
} else {
throw new RuntimeException(name + ": Invalid SSL credentials configuration. None of the PEM or KEYSTORE configurations can be used!");
}
try {
this.credentials.init(this.trustsOnly);
} catch (Exception e) {
throw new RuntimeException(name + ": Failed to init SSL credentials configuration.", e);
}
} else {
log.info("{}: Skipping initialization of disabled SSL credentials.", name);
}
}
} | repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\config\ssl\SslCredentialsConfig.java | 1 |
请完成以下Java代码 | public XMLGregorianCalendar getGueltigAb() {
return gueltigAb;
}
/**
* Sets the value of the gueltigAb property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setGueltigAb(XMLGregorianCalendar value) {
this.gueltigAb = 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.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VertragsdatenAntwort.java | 1 |
请完成以下Java代码 | public void deleteRefundInvoiceCandidates(@NonNull final I_C_Flatrate_Term flatrateTerm)
{
if (isNoRefundTerm(flatrateTerm))
{
return; // this MI only deals with "refund" terms
}
Services.get(IInvoiceCandDAO.class).deleteAllReferencingInvoiceCandidates(flatrateTerm);
}
@DocValidate(timings = ModelValidator.TIMING_AFTER_COMPLETE)
public void invalidateMatchingInvoiceCandidatesAfterCommit(@NonNull final I_C_Flatrate_Term flatrateTerm)
{
if (isNoRefundTerm(flatrateTerm))
{
return; // this MI only deals with "refund" terms
}
final IQuery<I_C_Invoice_Candidate> query = createInvoiceCandidatesToInvalidQuery(flatrateTerm);
Services.get(ITrxManager.class)
.getCurrentTrxListenerManagerOrAutoCommit()
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerHandlingMethod(trx -> Services.get(IInvoiceCandDAO.class).invalidateCandsFor(query));
}
private IQuery<I_C_Invoice_Candidate> createInvoiceCandidatesToInvalidQuery(
@NonNull final I_C_Flatrate_Term flatrateTerm)
{
final IQueryFilter<I_C_Invoice_Candidate> dateToInvoiceEffectiveFilter = invoiceCandidateRepository
.createDateToInvoiceEffectiveFilter(
flatrateTerm.getStartDate(), | flatrateTerm.getEndDate());
return Services.get(IQueryBL.class)
.createQueryBuilder(I_C_Invoice_Candidate.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_Invoice_Candidate.COLUMN_Processed, false)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_M_Product_ID, flatrateTerm.getM_Product_ID())
.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Bill_BPartner_ID, flatrateTerm.getBill_BPartner_ID())
.filter(dateToInvoiceEffectiveFilter)
.create();
}
private boolean isNoRefundTerm(@NonNull final I_C_Flatrate_Term flatrateTerm)
{
return !X_C_Flatrate_Term.TYPE_CONDITIONS_Refund.equals(flatrateTerm.getType_Conditions());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\interceptor\C_Flatrate_Term.java | 1 |
请完成以下Java代码 | public Flux<String> statefulImutableGenerate() {
return Flux.generate(() -> 1, (state, sink) -> {
sink.next("2 + " + state + " = " + (2 + state));
if (state == 101)
sink.complete();
return state + 1;
});
}
public Flux<String> statefulMutableGenerate() {
return Flux.generate(AtomicInteger::new, (state, sink) -> {
int i = state.getAndIncrement();
sink.next("2 + " + i + " = " + (2 + i));
if (i == 101)
sink.complete(); | return state;
});
}
public Flux<String> handle() {
return Flux.just(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
.handle((i, sink) -> {
String animal = "Elephant nr " + i;
if (i % 2 == 0) {
sink.next(animal);
}
});
}
} | repos\tutorials-master\spring-reactive-modules\reactor-core\src\main\java\com\baeldung\reactor\ProgrammaticSequences.java | 1 |
请完成以下Java代码 | public String getCalledProcessInstanceId() {
return calledProcessInstanceId;
}
@Override
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Date getTime() {
return getStartTime();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ActivityInstanceEntity[id=").append(id)
.append(", activityId=").append(activityId); | if (activityName != null) {
sb.append(", activityName=").append(activityName);
}
sb.append(", executionId=").append(executionId)
.append(", definitionId=").append(processDefinitionId);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ActivityInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public class Demo02Message implements Serializable {
public static final String QUEUE = "QUEUE_DEMO_02";
public static final String EXCHANGE = "EXCHANGE_DEMO_02";
public static final String ROUTING_KEY = "#.yu.nai";
/**
* 编号
*/
private Integer id;
public Demo02Message setId(Integer id) {
this.id = id; | return this;
}
public Integer getId() {
return id;
}
@Override
public String toString() {
return "Demo02Message{" +
"id=" + id +
'}';
}
} | repos\SpringBoot-Labs-master\lab-04-rabbitmq\lab-04-rabbitmq-demo\src\main\java\cn\iocoder\springboot\lab04\rabbitmqdemo\message\Demo02Message.java | 1 |
请完成以下Java代码 | public Integer getId() {
return id;
}
public UserDO setId(Integer id) {
this.id = id;
return this;
}
public String getUsername() {
return username;
}
public UserDO setUsername(String username) {
this.username = username;
return this;
}
public String getPassword() {
return password;
} | public UserDO setPassword(String password) {
this.password = password;
return this;
}
public Date getCreateTime() {
return createTime;
}
public UserDO setCreateTime(Date createTime) {
this.createTime = createTime;
return this;
}
} | repos\SpringBoot-Labs-master\lab-12-mybatis\lab-12-mybatis-annotation\src\main\java\cn\iocoder\springboot\lab12\mybatis\dataobject\UserDO.java | 1 |
请完成以下Java代码 | public Class<?> getType(ELContext context) {
return null;
}
/**
* Answer <code>true</code>.
*/
@Override
public boolean isReadOnly(ELContext context) {
return true;
}
/**
* Throw an exception.
*/ | @Override
public void setValue(ELContext context, Object value) {
throw new ELException(LocalMessages.get("error.value.set.rvalue", "<object value expression>"));
}
@Override
public String toString() {
return "ValueExpression(" + object + ")";
}
@Override
public Class<?> getExpectedType() {
return type;
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\ObjectValueExpression.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Converter<List<DegradeRuleEntity>, String> degradeRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<DegradeRuleEntity>> degradeRuleEntityDecoder() {
return s -> JSON.parseArray(s, DegradeRuleEntity.class);
}
/**
* 热点参数 规则
* @return
*/
@Bean
public Converter<List<ParamFlowRuleCorrectEntity>, String> paramFlowRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<ParamFlowRuleCorrectEntity>> paramFlowRuleEntityDecoder() {
return s -> JSON.parseArray(s, ParamFlowRuleCorrectEntity.class);
}
/**
* 系统规则
* @return
*/
@Bean
public Converter<List<SystemRuleEntity>, String> systemRuleRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<SystemRuleEntity>> systemRuleRuleEntityDecoder() {
return s -> JSON.parseArray(s, SystemRuleEntity.class);
}
/**
* 授权规则
* @return
*/
@Bean
public Converter<List<AuthorityRuleCorrectEntity>, String> authorityRuleRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<AuthorityRuleCorrectEntity>> authorityRuleRuleEntityDecoder() {
return s -> JSON.parseArray(s, AuthorityRuleCorrectEntity.class);
}
/** | * 网关API
*
* @return
* @throws Exception
*/
@Bean
public Converter<List<ApiDefinitionEntity>, String> apiDefinitionEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<ApiDefinitionEntity>> apiDefinitionEntityDecoder() {
return s -> JSON.parseArray(s, ApiDefinitionEntity.class);
}
/**
* 网关flowRule
*
* @return
* @throws Exception
*/
@Bean
public Converter<List<GatewayFlowRuleEntity>, String> gatewayFlowRuleEntityEncoder() {
return JSON::toJSONString;
}
@Bean
public Converter<String, List<GatewayFlowRuleEntity>> gatewayFlowRuleEntityDecoder() {
return s -> JSON.parseArray(s, GatewayFlowRuleEntity.class);
}
@Bean
public ConfigService nacosConfigService() throws Exception {
Properties properties=new Properties();
properties.put(PropertyKeyConst.SERVER_ADDR,nacosConfigProperties.getServerAddr());
if(StringUtils.isNotBlank(nacosConfigProperties.getUsername())){
properties.put(PropertyKeyConst.USERNAME,nacosConfigProperties.getUsername());
}
if(StringUtils.isNotBlank(nacosConfigProperties.getPassword())){
properties.put(PropertyKeyConst.PASSWORD,nacosConfigProperties.getPassword());
}
if(StringUtils.isNotBlank(nacosConfigProperties.getNamespace())){
properties.put(PropertyKeyConst.NAMESPACE,nacosConfigProperties.getNamespace());
}
return ConfigFactory.createConfigService(properties);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\rule\nacos\SentinelConfig.java | 2 |
请完成以下Java代码 | public void consume(final I_AD_UI_Section uiSection, final I_AD_Tab parent)
{
logger.debug("Generated in memory {} for {}", uiSection, parent);
final AdTabId adTabId = AdTabId.ofRepoId(parent.getAD_Tab_ID());
adTabId2sections.put(adTabId, uiSection);
}
@Override
public List<I_AD_UI_Section> getUISections(final AdTabId adTabId)
{
// Generate the UI elements if needed
if (!adTabId2sections.containsKey(adTabId))
{
final WindowUIElementsGenerator generator = WindowUIElementsGenerator.forConsumer(this);
final I_AD_Tab adTab = Services.get(IADWindowDAO.class).getTabByIdInTrx(adTabId);
final boolean primaryTab = adTab.getTabLevel() == 0;
if (primaryTab)
{
generator.migratePrimaryTab(adTab);
}
else
{
generator.migrateDetailTab(adTab);
}
}
return adTabId2sections.get(adTabId);
}
@Override
public void consume(final I_AD_UI_Column uiColumn, final I_AD_UI_Section parent)
{
logger.debug("Generated in memory {} for {}", uiColumn, parent);
section2columns.put(parent, uiColumn);
}
@Override
public List<I_AD_UI_Column> getUIColumns(final I_AD_UI_Section uiSection)
{
return section2columns.get(uiSection);
}
@Override
public void consume(final I_AD_UI_ElementGroup uiElementGroup, final I_AD_UI_Column parent)
{
logger.debug("Generated in memory {} for {}", uiElementGroup, parent);
column2elementGroups.put(parent, uiElementGroup);
}
@Override
public List<I_AD_UI_ElementGroup> getUIElementGroups(final I_AD_UI_Column uiColumn)
{
return column2elementGroups.get(uiColumn);
}
@Override
public void consume(final I_AD_UI_Element uiElement, final I_AD_UI_ElementGroup parent)
{
logger.debug("Generated in memory {} for {}", uiElement, parent);
elementGroup2elements.put(parent, uiElement); | }
@Override
public List<I_AD_UI_Element> getUIElements(final I_AD_UI_ElementGroup uiElementGroup)
{
return elementGroup2elements.get(uiElementGroup);
}
@Override
public List<I_AD_UI_Element> getUIElementsOfType(@NonNull final AdTabId adTabId, @NonNull final LayoutElementType layoutElementType)
{
return elementGroup2elements.values().stream()
.filter(uiElement -> layoutElementType.getCode().equals(uiElement.getAD_UI_ElementType()))
.collect(ImmutableList.toImmutableList());
}
@Override
public void consume(final I_AD_UI_ElementField uiElementField, final I_AD_UI_Element parent)
{
logger.debug("Generated in memory {} for {}", uiElementField, parent);
element2elementFields.put(parent, uiElementField);
}
@Override
public List<I_AD_UI_ElementField> getUIElementFields(final I_AD_UI_Element uiElement)
{
return element2elementFields.get(uiElement);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\InMemoryUIElementsProvider.java | 1 |
请完成以下Java代码 | default String getLocale() {
return this.getClaimAsString(StandardClaimNames.LOCALE);
}
/**
* Returns the user's preferred phone number {@code (phone_number)}.
* @return the user's preferred phone number
*/
default String getPhoneNumber() {
return this.getClaimAsString(StandardClaimNames.PHONE_NUMBER);
}
/**
* Returns {@code true} if the user's phone number has been verified
* {@code (phone_number_verified)}, otherwise {@code false}.
* @return {@code true} if the user's phone number has been verified, otherwise
* {@code false}
*/
default Boolean getPhoneNumberVerified() {
return this.getClaimAsBoolean(StandardClaimNames.PHONE_NUMBER_VERIFIED);
} | /**
* Returns the user's preferred postal address {@code (address)}.
* @return the user's preferred postal address
*/
default AddressStandardClaim getAddress() {
Map<String, Object> addressFields = this.getClaimAsMap(StandardClaimNames.ADDRESS);
return (!CollectionUtils.isEmpty(addressFields) ? new DefaultAddressStandardClaim.Builder(addressFields).build()
: new DefaultAddressStandardClaim.Builder().build());
}
/**
* Returns the time the user's information was last updated {@code (updated_at)}.
* @return the time the user's information was last updated
*/
default Instant getUpdatedAt() {
return this.getClaimAsInstant(StandardClaimNames.UPDATED_AT);
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\oidc\StandardClaimAccessor.java | 1 |
请完成以下Java代码 | public ResponseEntity<Object> createRole(@Validated @RequestBody Role resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
getLevels(resources.getLevel());
roleService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改角色")
@ApiOperation("修改角色")
@PutMapping
@PreAuthorize("@el.check('roles:edit')")
public ResponseEntity<Object> updateRole(@Validated(Role.Update.class) @RequestBody Role resources){
getLevels(resources.getLevel());
roleService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("修改角色菜单")
@ApiOperation("修改角色菜单")
@PutMapping(value = "/menu")
@PreAuthorize("@el.check('roles:edit')")
public ResponseEntity<Object> updateRoleMenu(@RequestBody Role resources){
RoleDto role = roleService.findById(resources.getId());
getLevels(role.getLevel());
roleService.updateMenu(resources,role);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除角色")
@ApiOperation("删除角色")
@DeleteMapping | @PreAuthorize("@el.check('roles:del')")
public ResponseEntity<Object> deleteRole(@RequestBody Set<Long> ids){
for (Long id : ids) {
RoleDto role = roleService.findById(id);
getLevels(role.getLevel());
}
// 验证是否被用户关联
roleService.verification(ids);
roleService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
/**
* 获取用户的角色级别
* @return /
*/
private int getLevels(Integer level){
List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
int min = Collections.min(levels);
if(level != null){
if(level < min){
throw new BadRequestException("权限不足,你的角色级别:" + min + ",低于操作的角色级别:" + level);
}
}
return min;
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\RoleController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InOutPackageRepository
{
private final IInOutDAO inOutDAO = Services.get(IInOutDAO.class);
@NonNull
public ImmutableList<I_M_Package> createM_Packages(@NonNull final List<CreatePackagesRequest> packagesRequestList)
{
return packagesRequestList.stream().map(this::createM_Package).collect(ImmutableList.toImmutableList());
}
private I_M_Package createM_Package(@NonNull final CreatePackagesRequest createPackageRequest)
{
final I_M_InOut inOut = inOutDAO.getById(createPackageRequest.getInOutId());
final I_M_Package mPackage = newInstance(I_M_Package.class);
mPackage.setM_Shipper_ID(createPackageRequest.getShipperId().getRepoId());
mPackage.setAD_Org_ID(inOut.getAD_Org_ID());
mPackage.setProcessed(createPackageRequest.isProcessed());
mPackage.setShipDate(null); | mPackage.setC_BPartner_ID(inOut.getC_BPartner_ID());
mPackage.setC_BPartner_Location_ID(inOut.getC_BPartner_Location_ID());
mPackage.setM_InOut_ID(inOut.getM_InOut_ID());
mPackage.setPOReference(inOut.getPOReference());
mPackage.setTrackingInfo(createPackageRequest.getTrackingCode());
mPackage.setPackageWeight(createPackageRequest.getWeightInKg());
mPackage.setTrackingURL(createPackageRequest.getTrackingURL());
final PackageDimensions packageDimensions = createPackageRequest.getPackageDimensions();
mPackage.setLengthInCm(packageDimensions.getLengthInCM());
mPackage.setHeightInCm(packageDimensions.getHeightInCM());
mPackage.setWidthInCm(packageDimensions.getWidthInCM());
InterfaceWrapperHelper.save(mPackage);
return mPackage;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipping\InOutPackageRepository.java | 2 |
请完成以下Java代码 | private final String buildStringTrl(final String adLanguage)
{
if (Language.isBaseLanguage(adLanguage))
{
return stringBaseLang;
}
return stringTrlPattern.replace(adLanguageParamName, adLanguage);
}
}
private static final class ConstantTranslatableParameterizedString extends TranslatableParameterizedString
{
private final String adLanguageParamName;
private final String stringBaseLang;
private final String stringTrl;
private ConstantTranslatableParameterizedString(final String adLanguageParamName, final String stringBaseLang, final String stringTrl)
{
this.adLanguageParamName = adLanguageParamName;
this.stringBaseLang = stringBaseLang;
this.stringTrl = stringTrl;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("adLanguageParamName", adLanguageParamName)
.add("stringBaseLang", stringBaseLang)
.add("stringTrl", stringTrl)
.toString();
}
@Override
public String getAD_LanguageParamName()
{
return adLanguageParamName;
}
@Override
public String getStringBaseLanguage()
{
return stringBaseLang;
}
@Override
public String getStringTrlPattern()
{
return stringTrl;
}
@Override
public String translate(final String adLanguage)
{
if (Language.isBaseLanguage(adLanguage))
{
return stringBaseLang;
}
else
{
return stringTrl;
}
}
}
private static final class NoTranslatableParameterizedString extends TranslatableParameterizedString
{
private final String adLanguageParamName;
private final String string;
private NoTranslatableParameterizedString(final String adLanguageParamName, final String string) | {
super();
this.adLanguageParamName = adLanguageParamName;
this.string = string;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("adLanguageParamName", adLanguageParamName)
.add("string", string)
.toString();
}
@Override
public String getAD_LanguageParamName()
{
return adLanguageParamName;
}
@Override
public String getStringBaseLanguage()
{
return string;
}
@Override
public String getStringTrlPattern()
{
return string;
}
@Override
public String translate()
{
return string;
}
@Override
public String translate(final String adLanguage)
{
return string;
}
@Override
public NoTranslatableParameterizedString transform(final Function<String, String> mappingFunction)
{
final String stringTransformed = mappingFunction.apply(string);
if (Objects.equals(string, stringTransformed))
{
return this;
}
return new NoTranslatableParameterizedString(adLanguageParamName, stringTransformed);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\TranslatableParameterizedString.java | 1 |
请完成以下Java代码 | public static <T> R success() {
return new R<>(ResultCode.OK, true);
}
public static <T> R message(String message) {
return new R<>(ResultCode.OK.getCode(), message, true, null);
}
public static <T> R success(T data) {
return new R<>(ResultCode.OK, true, data);
}
public static <T> R fail() {
return new R<>(ResultCode.ERROR, false);
}
public static <T> R fail(IResultCode resultCode) { | return new R<>(resultCode, false);
}
public static <T> R fail(Integer code, String message) {
return new R<>(code, message, false, null);
}
public static <T> R fail(IResultCode resultCode, T data) {
return new R<>(resultCode, false, data);
}
public static <T> R fail(Integer code, String message, T data) {
return new R<>(code, message, false, data);
}
} | repos\spring-boot-demo-master\demo-codegen\src\main\java\com\xkcoding\codegen\common\R.java | 1 |
请完成以下Java代码 | public void onError(Throwable t) {
ctx.getResponse().status(500);
}
@Override
public void onComplete() {
ctx.getResponse().status(202);
}
});
});
}
@Bean
public Action<Chain> download() {
return chain -> chain.get("download", ctx -> {
ctx.getResponse().sendStream(new RandomBytesPublisher(1024,512));
});
}
@Bean
public Action<Chain> downloadChunks() {
return chain -> chain.get("downloadChunks", ctx -> {
ctx.render(ResponseChunks.bufferChunks("application/octetstream",
new RandomBytesPublisher(1024,512)));
});
}
@Bean
public ServerConfig ratpackServerConfig() {
return ServerConfig
.builder()
.findBaseDir("public")
.build();
}
public static void main(String[] args) {
SpringApplication.run(EmbedRatpackStreamsApp.class, args);
}
public static class RandomBytesPublisher implements Publisher<ByteBuf> {
private int bufCount;
private int bufSize;
private Random rnd = new Random();
RandomBytesPublisher(int bufCount, int bufSize) {
this.bufCount = bufCount;
this.bufSize = bufSize; | }
@Override
public void subscribe(Subscriber<? super ByteBuf> s) {
s.onSubscribe(new Subscription() {
private boolean cancelled = false;
private boolean recurse;
private long requested = 0;
@Override
public void request(long n) {
if ( bufCount == 0 ) {
s.onComplete();
return;
}
requested += n;
if ( recurse ) {
return;
}
recurse = true;
try {
while ( requested-- > 0 && !cancelled && bufCount-- > 0 ) {
byte[] data = new byte[bufSize];
rnd.nextBytes(data);
ByteBuf buf = Unpooled.wrappedBuffer(data);
s.onNext(buf);
}
}
finally {
recurse = false;
}
}
@Override
public void cancel() {
cancelled = true;
}
});
}
}
} | repos\tutorials-master\web-modules\ratpack\src\main\java\com\baeldung\spring\EmbedRatpackStreamsApp.java | 1 |
请完成以下Java代码 | public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Root Entry.
@param Root_ID Root Entry */
@Override
public void setRoot_ID (int Root_ID)
{
if (Root_ID < 1)
set_Value (COLUMNNAME_Root_ID, null);
else
set_Value (COLUMNNAME_Root_ID, Integer.valueOf(Root_ID));
}
/** Get Root Entry.
@return Root Entry */
@Override
public int getRoot_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Root_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom) | {
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Record_Access.java | 1 |
请完成以下Java代码 | protected static String getBatchIdFromHandlerCfg(String handlerCfg) {
try {
JsonNode cfgAsJson = getObjectMapper().readTree(handlerCfg);
if (cfgAsJson.has(CFG_LABEL_BATCH_ID)) {
return cfgAsJson.get(CFG_LABEL_BATCH_ID).asString();
}
return null;
} catch (JacksonException e) {
return null;
}
}
protected static String getBatchPartIdFromHandlerCfg(String handlerCfg) {
try {
JsonNode cfgAsJson = getObjectMapper().readTree(handlerCfg);
if (cfgAsJson.has(CFG_LABEL_BATCH_PART_ID)) {
return cfgAsJson.get(CFG_LABEL_BATCH_PART_ID).asString();
}
return null;
} catch (JacksonException e) {
return null;
}
}
public static String getHandlerCfgForBatchId(String batchId) {
ObjectNode handlerCfg = getObjectMapper().createObjectNode();
handlerCfg.put(CFG_LABEL_BATCH_ID, batchId);
return handlerCfg.toString(); | }
public static String getHandlerCfgForBatchPartId(String batchPartId) {
ObjectNode handlerCfg = getObjectMapper().createObjectNode();
handlerCfg.put(CFG_LABEL_BATCH_PART_ID, batchPartId);
return handlerCfg.toString();
}
protected static ObjectMapper getObjectMapper() {
if (CommandContextUtil.getCommandContext() != null) {
return CommandContextUtil.getCmmnEngineConfiguration().getObjectMapper();
} else {
return JsonMapper.shared();
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\job\AbstractCaseInstanceMigrationJobHandler.java | 1 |
请完成以下Java代码 | public void incrementTotal(int amount) {
totalCounter.add(amount);
}
@Override
public void incrementSuccessful(int amount) {
successfulCounter.add(amount);
}
@Override
public void incrementFailed(int amount) {
failedCounter.add(amount);
}
@Override
public int getTotal() {
return totalCounter.get();
}
@Override | public int getSuccessful() {
return successfulCounter.get();
}
@Override
public int getFailed() {
return failedCounter.get();
}
@Override
public void reset() {
totalCounter.clear();
successfulCounter.clear();
failedCounter.clear();
}
} | repos\thingsboard-master\common\stats\src\main\java\org\thingsboard\server\common\stats\DefaultMessagesStats.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getShortDescription() {
return this.shortDescription;
}
public void setShortDescription(String shortDescription) {
this.shortDescription = shortDescription;
}
/**
* The type where this source is defined. This can be identical to the
* {@link #getType() type} if the source is self-defined.
* @return the source type
*/
public String getSourceType() {
return this.sourceType;
}
void setSourceType(String sourceType) {
this.sourceType = sourceType;
}
/**
* The method name that defines this source, if any.
* @return the source method | */
public String getSourceMethod() {
return this.sourceMethod;
}
void setSourceMethod(String sourceMethod) {
this.sourceMethod = sourceMethod;
}
/**
* Return the properties defined by this source.
* @return the properties
*/
public Map<String, ConfigurationMetadataProperty> getProperties() {
return this.properties;
}
} | repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-metadata\src\main\java\org\springframework\boot\configurationmetadata\ConfigurationMetadataSource.java | 2 |
请完成以下Java代码 | public I_M_Product getM_Product()
{
final ProductId productId = ProductId.ofRepoId(ppOrder.getM_Product_ID());
return productDAO.getById(productId);
}
@Override
public BigDecimal getQty()
{
return getQuantities(getUomId())
.getQtyReceived()
.toBigDecimal();
}
private PPOrderQuantities getQuantities(final UomId targetUOMId)
{
return ppOrderBOMBL.getQuantities(ppOrder, targetUOMId);
}
@Override
public I_C_UOM getC_UOM()
{
return uomDAO.getById(getUomId());
}
@NonNull
public UomId getUomId()
{
return UomId.ofRepoId(ppOrder.getC_UOM_ID());
}
@Override
public ProductionMaterialType getType()
{
return ProductionMaterialType.PRODUCED;
}
@Override
public void setQM_QtyDeliveredPercOfRaw(final BigDecimal qtyDeliveredPercOfRaw)
{
ppOrder.setQM_QtyDeliveredPercOfRaw(qtyDeliveredPercOfRaw);
}
@Override
public BigDecimal getQM_QtyDeliveredPercOfRaw()
{
return ppOrder.getQM_QtyDeliveredPercOfRaw();
}
@Override
public void setQM_QtyDeliveredAvg(final BigDecimal qtyDeliveredAvg)
{
ppOrder.setQM_QtyDeliveredAvg(qtyDeliveredAvg);
}
@Override
public BigDecimal getQM_QtyDeliveredAvg()
{
return ppOrder.getQM_QtyDeliveredAvg();
}
@Override
public Object getModel() | {
return ppOrder;
}
@Override
public String getVariantGroup()
{
return null;
}
@Override
public BOMComponentType getComponentType()
{
return null;
}
@Override
public IHandlingUnitsInfo getHandlingUnitsInfo()
{
if (!_handlingUnitsInfoLoaded)
{
_handlingUnitsInfo = handlingUnitsInfoFactory.createFromModel(ppOrder);
_handlingUnitsInfoLoaded = true;
}
return _handlingUnitsInfo;
}
@Override
public I_M_Product getMainComponentProduct()
{
// there is no substitute for a produced material
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderProductionMaterial.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Set<String> getRoleCodeByOperatorId(Long operatorId) {
// 得到操作员和角色列表
List<PmsOperatorRole> rpList = pmsOperatorRoleDao.listByOperatorId(operatorId);
Set<String> roleCodeSet = new HashSet<String>();
for (PmsOperatorRole rp : rpList) {
Long roleId = rp.getRoleId();
PmsRole role = pmsRoleDao.getById(roleId);
if (role == null) {
continue;
}
roleCodeSet.add(role.getRoleCode());
}
return roleCodeSet;
}
/**
* 根据角色ID统计有多少个操作员关联到此角色.
*
* @param roleId
* .
* @return count.
*/
public int countOperatorByRoleId(Long roleId) {
List<PmsOperatorRole> operatorList = pmsOperatorRoleDao.listByRoleId(roleId);
if (operatorList == null || operatorList.isEmpty()) {
return 0;
} else {
return operatorList.size();
}
}
/**
* 根据操作员ID获得所有操作员-角色关联列表
*/
public List<PmsOperatorRole> listOperatorRoleByOperatorId(Long operatorId) {
return pmsOperatorRoleDao.listByOperatorId(operatorId);
}
/**
* 保存操作員信息及其关联的角色.
*
* @param pmsOperator
* .
* @param OperatorRoleStr
* .
*/
public void saveOperator(PmsOperator pmsOperator, String OperatorRoleStr) {
// 保存操作员信息
pmsOperatorDao.insert(pmsOperator);
// 保存角色关联信息
if (StringUtils.isNotBlank(OperatorRoleStr) && OperatorRoleStr.length() > 0) {
saveOrUpdateOperatorRole(pmsOperator.getId(), OperatorRoleStr);
}
}
/**
* 根据角色ID查询用户
*
* @param roleId
* @return
*/
public List<PmsOperator> listOperatorByRoleId(Long roleId) {
return pmsOperatorDao.listByRoleId(roleId);
}
/**
* 修改操作員信息及其关联的角色.
* | * @param pmsOperator
* .
* @param OperatorRoleStr
* .
*/
public void updateOperator(PmsOperator pmsOperator, String OperatorRoleStr) {
pmsOperatorDao.update(pmsOperator);
// 更新角色信息
saveOrUpdateOperatorRole(pmsOperator.getId(), OperatorRoleStr);
}
/**
* 保存用户和角色之间的关联关系
*/
private void saveOrUpdateOperatorRole(Long operatorId, String roleIdsStr) {
// 删除原来的角色与操作员关联
List<PmsOperatorRole> listPmsOperatorRoles = pmsOperatorRoleDao.listByOperatorId(operatorId);
Map<Long, PmsOperatorRole> delMap = new HashMap<Long, PmsOperatorRole>();
for (PmsOperatorRole pmsOperatorRole : listPmsOperatorRoles) {
delMap.put(pmsOperatorRole.getRoleId(), pmsOperatorRole);
}
if (StringUtils.isNotBlank(roleIdsStr)) {
// 创建新的关联
String[] roleIds = roleIdsStr.split(",");
for (int i = 0; i < roleIds.length; i++) {
Long roleId = Long.valueOf(roleIds[i]);
if (delMap.get(roleId) == null) {
PmsOperatorRole pmsOperatorRole = new PmsOperatorRole();
pmsOperatorRole.setOperatorId(operatorId);
pmsOperatorRole.setRoleId(roleId);
pmsOperatorRoleDao.insert(pmsOperatorRole);
} else {
delMap.remove(roleId);
}
}
}
Iterator<Long> iterator = delMap.keySet().iterator();
while (iterator.hasNext()) {
Long roleId = iterator.next();
pmsOperatorRoleDao.deleteByRoleIdAndOperatorId(roleId, operatorId);
}
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsOperatorRoleServiceImpl.java | 2 |
请完成以下Java代码 | public void setOrderedData(final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setOrderedData(ic);
}
@Override
public void setDeliveredData(final I_C_Invoice_Candidate ic)
{
final IInvoiceCandidateHandler handler = createInvoiceCandidateHandler(ic);
handler.setDeliveredData(ic);
}
@Override
public void invalidateCandidatesFor(final Object model)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(model);
final String tableName = InterfaceWrapperHelper.getModelTableName(model);
final List<IInvoiceCandidateHandler> handlersForTable = retrieveImplementationsForTable(ctx, tableName);
for (final IInvoiceCandidateHandler handler : handlersForTable)
{
final OnInvalidateForModelAction onInvalidateForModelAction = handler.getOnInvalidateForModelAction();
switch (onInvalidateForModelAction)
{
case RECREATE_ASYNC:
scheduleCreateMissingCandidatesFor(model, handler);
break;
case REVALIDATE:
handler.invalidateCandidatesFor(model);
break;
default:
// nothing
logger.warn("Got no OnInvalidateForModelAction for " + model + ". Doing nothing.");
break;
}
}
}
@Override
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 void setEventData (final @Nullable java.lang.String EventData)
{
set_Value (COLUMNNAME_EventData, EventData);
}
@Override
public java.lang.String getEventData()
{
return get_ValueAsString(COLUMNNAME_EventData);
}
@Override
public void setEventName (final java.lang.String EventName)
{
set_Value (COLUMNNAME_EventName, EventName);
}
@Override
public java.lang.String getEventName()
{
return get_ValueAsString(COLUMNNAME_EventName);
}
@Override
public void setExternalId (final java.lang.String ExternalId)
{
set_Value (COLUMNNAME_ExternalId, ExternalId);
}
@Override
public java.lang.String getExternalId()
{
return get_ValueAsString(COLUMNNAME_ExternalId);
}
@Override
public void setTimestamp (final java.sql.Timestamp Timestamp)
{
set_Value (COLUMNNAME_Timestamp, Timestamp);
}
@Override
public java.sql.Timestamp getTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_Timestamp);
}
@Override
public void setUI_ApplicationId (final @Nullable java.lang.String UI_ApplicationId)
{
set_Value (COLUMNNAME_UI_ApplicationId, UI_ApplicationId);
}
@Override
public java.lang.String getUI_ApplicationId()
{
return get_ValueAsString(COLUMNNAME_UI_ApplicationId);
}
@Override
public void setUI_DeviceId (final @Nullable java.lang.String UI_DeviceId)
{
set_Value (COLUMNNAME_UI_DeviceId, UI_DeviceId);
}
@Override
public java.lang.String getUI_DeviceId()
{
return get_ValueAsString(COLUMNNAME_UI_DeviceId);
}
@Override
public void setUI_TabId (final @Nullable java.lang.String UI_TabId)
{
set_Value (COLUMNNAME_UI_TabId, UI_TabId);
}
@Override
public java.lang.String getUI_TabId()
{
return get_ValueAsString(COLUMNNAME_UI_TabId);
}
@Override
public void setUI_Trace_ID (final int UI_Trace_ID)
{
if (UI_Trace_ID < 1)
set_ValueNoCheck (COLUMNNAME_UI_Trace_ID, null);
else
set_ValueNoCheck (COLUMNNAME_UI_Trace_ID, UI_Trace_ID);
}
@Override | public int getUI_Trace_ID()
{
return get_ValueAsInt(COLUMNNAME_UI_Trace_ID);
}
@Override
public void setURL (final @Nullable java.lang.String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
@Override
public java.lang.String getURL()
{
return get_ValueAsString(COLUMNNAME_URL);
}
@Override
public void setUserAgent (final @Nullable java.lang.String UserAgent)
{
set_Value (COLUMNNAME_UserAgent, UserAgent);
}
@Override
public java.lang.String getUserAgent()
{
return get_ValueAsString(COLUMNNAME_UserAgent);
}
@Override
public void setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_UI_Trace.java | 1 |
请完成以下Java代码 | public static EventResourceEntityManager getResourceEntityManager() {
return getResourceEntityManager(getCommandContext());
}
public static EventResourceEntityManager getResourceEntityManager(CommandContext commandContext) {
return getEventRegistryConfiguration(commandContext).getResourceEntityManager();
}
public static EventDeploymentEntityManager getDeploymentEntityManager() {
return getDeploymentEntityManager(getCommandContext());
}
public static EventDeploymentEntityManager getDeploymentEntityManager(CommandContext commandContext) {
return getEventRegistryConfiguration(commandContext).getDeploymentEntityManager();
}
public static EventDefinitionEntityManager getEventDefinitionEntityManager() {
return getEventDefinitionEntityManager(getCommandContext());
}
public static EventDefinitionEntityManager getEventDefinitionEntityManager(CommandContext commandContext) {
return getEventRegistryConfiguration(commandContext).getEventDefinitionEntityManager();
}
public static ChannelDefinitionEntityManager getChannelDefinitionEntityManager() {
return getChannelDefinitionEntityManager(getCommandContext());
}
public static ChannelDefinitionEntityManager getChannelDefinitionEntityManager(CommandContext commandContext) { | return getEventRegistryConfiguration(commandContext).getChannelDefinitionEntityManager();
}
public static TableDataManager getTableDataManager() {
return getTableDataManager(getCommandContext());
}
public static TableDataManager getTableDataManager(CommandContext commandContext) {
return getEventRegistryConfiguration(commandContext).getTableDataManager();
}
public static CommandContext getCommandContext() {
return Context.getCommandContext();
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\util\CommandContextUtil.java | 1 |
请完成以下Java代码 | public Result processWorkPackage(@NonNull final I_C_Queue_WorkPackage workPackage, @Nullable final String localTrxName)
{
final UserId userId = UserId.ofRepoId(CoalesceUtil.firstGreaterThanZero(
workPackage.getAD_User_InCharge_ID(),
workPackage.getAD_User_ID())); // if both are <=0 we end up with UserId.SYSTEM which is OK
ddOrderCandidateService.process(getProcessRequest(userId));
return Result.SUCCESS;
}
private DDOrderCandidateProcessRequest getProcessRequest(@NonNull final UserId userId)
{
final DDOrderCandidateEnqueueRequest enqueueRequest = DDOrderCandidateEnqueueService.extractRequest(getParameters());
final PInstanceId selectionId = enqueueRequest.getSelectionId();
final List<DDOrderCandidate> candidates = ddOrderCandidateService.getBySelectionId(selectionId);
logCandidatesToProcess(candidates, selectionId);
return DDOrderCandidateProcessRequest.builder()
.userId(userId)
.candidates(candidates)
.build();
} | /**
* There is a weird problem when running this remotely via a cucumber-test..
*/
private static void logCandidatesToProcess(@NonNull final List<DDOrderCandidate> candidates, @NonNull final PInstanceId selectionId)
{
final List<String> ids = new ArrayList<>();
for (int i = 0; i < candidates.size() && i < 10; i++)
{
ids.add(Integer.toString(candidates.get(i).getIdNotNull().getRepoId()));
}
Loggables.withLogger(logger, Level.INFO)
.addLog("Retrieved {} DDOrderCandidates for SelectionId={}; The first (max 10) selection IDs are: {}",
candidates.size(), selectionId, String.join(",", ids));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddordercandidate\async\GenerateDDOrderFromDDOrderCandidate.java | 1 |
请完成以下Java代码 | public void setAD_WF_Activity_ID (final int AD_WF_Activity_ID)
{
if (AD_WF_Activity_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_Activity_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_Activity_ID, AD_WF_Activity_ID);
}
@Override
public int getAD_WF_Activity_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_Activity_ID);
}
@Override
public void setAD_WF_ActivityResult_ID (final int AD_WF_ActivityResult_ID)
{
if (AD_WF_ActivityResult_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_WF_ActivityResult_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_WF_ActivityResult_ID, AD_WF_ActivityResult_ID);
}
@Override
public int getAD_WF_ActivityResult_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_WF_ActivityResult_ID);
}
@Override
public void setAttributeName (final java.lang.String AttributeName)
{
set_Value (COLUMNNAME_AttributeName, AttributeName);
}
@Override
public java.lang.String getAttributeName()
{
return get_ValueAsString(COLUMNNAME_AttributeName);
}
@Override
public void setAttributeValue (final java.lang.String AttributeValue)
{
set_Value (COLUMNNAME_AttributeValue, AttributeValue);
}
@Override
public java.lang.String getAttributeValue()
{
return get_ValueAsString(COLUMNNAME_AttributeValue);
} | @Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setHelp (final java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_ActivityResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void init(B builder) {
}
@Override
public void configure(B builder) {
}
/**
* Gets the {@link SecurityBuilder}. Cannot be null.
* @return the {@link SecurityBuilder}
* @throws IllegalStateException if {@link SecurityBuilder} is null
*/
protected final B getBuilder() {
Assert.state(this.securityBuilder != null, "securityBuilder cannot be null");
return this.securityBuilder;
}
/**
* Performs post processing of an object. The default is to delegate to the
* {@link ObjectPostProcessor}.
* @param object the Object to post process
* @return the possibly modified Object to use
*/
@SuppressWarnings("unchecked")
protected <T> T postProcess(T object) {
return (T) this.objectPostProcessor.postProcess(object);
}
/**
* Adds an {@link ObjectPostProcessor} to be used for this
* {@link SecurityConfigurerAdapter}. The default implementation does nothing to the
* object.
* @param objectPostProcessor the {@link ObjectPostProcessor} to use
*/
public void addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
this.objectPostProcessor.addObjectPostProcessor(objectPostProcessor);
}
/**
* Sets the {@link SecurityBuilder} to be used. This is automatically set when using
* {@link AbstractConfiguredSecurityBuilder#with(SecurityConfigurerAdapter, Customizer)}
* @param builder the {@link SecurityBuilder} to set
*/
public void setBuilder(B builder) {
this.securityBuilder = builder;
}
/**
* An {@link ObjectPostProcessor} that delegates work to numerous
* {@link ObjectPostProcessor} implementations.
* | * @author Rob Winch
*/
private static final class CompositeObjectPostProcessor implements ObjectPostProcessor<Object> {
private List<ObjectPostProcessor<?>> postProcessors = new ArrayList<>();
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object postProcess(Object object) {
for (ObjectPostProcessor opp : this.postProcessors) {
Class<?> oppClass = opp.getClass();
Class<?> oppType = GenericTypeResolver.resolveTypeArgument(oppClass, ObjectPostProcessor.class);
if (oppType == null || oppType.isAssignableFrom(object.getClass())) {
object = opp.postProcess(object);
}
}
return object;
}
/**
* Adds an {@link ObjectPostProcessor} to use
* @param objectPostProcessor the {@link ObjectPostProcessor} to add
* @return true if the {@link ObjectPostProcessor} was added, else false
*/
private boolean addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
boolean result = this.postProcessors.add(objectPostProcessor);
this.postProcessors.sort(AnnotationAwareOrderComparator.INSTANCE);
return result;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\SecurityConfigurerAdapter.java | 2 |
请完成以下Java代码 | public ChartOfAccounts getById(@NonNull final ChartOfAccountsId chartOfAccountsId)
{
final ChartOfAccounts chartOfAccounts = byId.get(chartOfAccountsId);
if (chartOfAccounts == null)
{
throw new AdempiereException("No Chart of Accounts found for " + chartOfAccountsId);
}
return chartOfAccounts;
}
public List<ChartOfAccounts> getByIds(@NonNull final Set<ChartOfAccountsId> chartOfAccountsIds)
{
return chartOfAccountsIds.stream()
.map(this::getById)
.collect(ImmutableList.toImmutableList());
}
public Optional<ChartOfAccounts> getByName(@NonNull final String chartOfAccountsName, @NonNull final ClientId clientId, @NonNull final OrgId orgId)
{
return list.stream()
.filter(matchByName(chartOfAccountsName, clientId, orgId))
.findFirst();
} | private static Predicate<ChartOfAccounts> matchByName(@NonNull final String chartOfAccountsName, @NonNull final ClientId clientId, @NonNull final OrgId orgId)
{
return chartOfAccounts ->
Objects.equals(chartOfAccounts.getName(), chartOfAccountsName)
&& ClientId.equals(chartOfAccounts.getClientId(), clientId)
&& OrgId.equals(chartOfAccounts.getOrgId(), orgId);
}
public Optional<ChartOfAccounts> getByTreeId(@NonNull final AdTreeId treeId)
{
return list.stream()
.filter(coa -> AdTreeId.equals(coa.getTreeId(), treeId))
.findFirst();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\elementvalue\ChartOfAccountsMap.java | 1 |
请完成以下Java代码 | public void setDateDoc (Timestamp DateDoc)
{
set_Value (COLUMNNAME_DateDoc, DateDoc);
}
/** Get Document Date.
@return Date of the Document
*/
public Timestamp getDateDoc ()
{
return (Timestamp)get_Value(COLUMNNAME_DateDoc);
}
/** 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 Processed.
@param Processed
The document has been processed | */
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Depreciation_Forecast.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ReturnT<String> logKill(int id){
// base check
XxlJobLog log = xxlJobLogDao.load(id);
XxlJobInfo jobInfo = xxlJobInfoDao.loadById(log.getJobId());
if (jobInfo==null) {
return new ReturnT<String>(500, I18nUtil.getString("jobinfo_glue_jobid_unvalid"));
}
if (ReturnT.SUCCESS_CODE != log.getTriggerCode()) {
return new ReturnT<String>(500, I18nUtil.getString("joblog_kill_log_limit"));
}
// request of kill
ReturnT<String> runResult = null;
try {
ExecutorBiz executorBiz = XxlJobScheduler.getExecutorBiz(log.getExecutorAddress());
runResult = executorBiz.kill(new KillParam(jobInfo.getId()));
} catch (Exception e) {
logger.error(e.getMessage(), e);
runResult = new ReturnT<String>(500, e.getMessage());
}
if (ReturnT.SUCCESS_CODE == runResult.getCode()) {
log.setHandleCode(ReturnT.FAIL_CODE);
log.setHandleMsg( I18nUtil.getString("joblog_kill_log_byman")+":" + (runResult.getMsg()!=null?runResult.getMsg():""));
log.setHandleTime(new Date());
XxlJobCompleter.updateHandleInfoAndFinish(log);
return new ReturnT<String>(runResult.getMsg());
} else {
return new ReturnT<String>(500, runResult.getMsg());
}
}
@RequestMapping("/clearLog")
@ResponseBody
public ReturnT<String> clearLog(int jobGroup, int jobId, int type){
Date clearBeforeTime = null;
int clearBeforeNum = 0; | if (type == 1) {
clearBeforeTime = DateUtil.addMonths(new Date(), -1); // 清理一个月之前日志数据
} else if (type == 2) {
clearBeforeTime = DateUtil.addMonths(new Date(), -3); // 清理三个月之前日志数据
} else if (type == 3) {
clearBeforeTime = DateUtil.addMonths(new Date(), -6); // 清理六个月之前日志数据
} else if (type == 4) {
clearBeforeTime = DateUtil.addYears(new Date(), -1); // 清理一年之前日志数据
} else if (type == 5) {
clearBeforeNum = 1000; // 清理一千条以前日志数据
} else if (type == 6) {
clearBeforeNum = 10000; // 清理一万条以前日志数据
} else if (type == 7) {
clearBeforeNum = 30000; // 清理三万条以前日志数据
} else if (type == 8) {
clearBeforeNum = 100000; // 清理十万条以前日志数据
} else if (type == 9) {
clearBeforeNum = 0; // 清理所有日志数据
} else {
return new ReturnT<String>(ReturnT.FAIL_CODE, I18nUtil.getString("joblog_clean_type_unvalid"));
}
List<Long> logIds = null;
do {
logIds = xxlJobLogDao.findClearLogIds(jobGroup, jobId, clearBeforeTime, clearBeforeNum, 1000);
if (logIds!=null && logIds.size()>0) {
xxlJobLogDao.clearLog(logIds);
}
} while (logIds!=null && logIds.size()>0);
return ReturnT.SUCCESS;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\JobLogController.java | 2 |
请完成以下Java代码 | public class KafkaProducer {
private final Producer<String, String> producer;
public KafkaProducer(Producer<String, String> producer) {
this.producer = producer;
}
public Future<RecordMetadata> send(String key, String value) {
ProducerRecord record = new ProducerRecord("topic_sports_news", key, value);
return producer.send(record);
}
public void flush() {
producer.flush(); | }
public void beginTransaction() {
producer.beginTransaction();
}
public void initTransaction() {
producer.initTransactions();
}
public void commitTransaction() {
producer.commitTransaction();
}
} | repos\tutorials-master\apache-kafka-2\src\main\java\com\baeldung\kafka\producer\KafkaProducer.java | 1 |
请完成以下Java代码 | public boolean isAllowed(String uri, @Nullable Authentication authentication) {
List<WebInvocationPrivilegeEvaluator> privilegeEvaluators = getDelegate(null, uri, null);
if (privilegeEvaluators.isEmpty()) {
return true;
}
for (WebInvocationPrivilegeEvaluator evaluator : privilegeEvaluators) {
boolean isAllowed = evaluator.isAllowed(uri, authentication);
if (!isAllowed) {
return false;
}
}
return true;
}
/**
* Determines whether the user represented by the supplied <tt>Authentication</tt>
* object is allowed to invoke the supplied URI.
* <p>
* Uses the provided URI in the
* {@link org.springframework.security.web.util.matcher.RequestMatcher#matches(HttpServletRequest)}
* for every {@code RequestMatcher} configured. If no {@code RequestMatcher} is
* matched, or if there is not an available {@code WebInvocationPrivilegeEvaluator},
* returns {@code true}.
* @param uri the URI excluding the context path (a default context path setting will
* be used)
* @param contextPath the context path (may be null, in which case a default value
* will be used).
* @param method the HTTP method (or null, for any method)
* @param authentication the <tt>Authentication</tt> instance whose authorities should
* be used in evaluation whether access should be granted.
* @return true if access is allowed, false if denied
*/
@Override
public boolean isAllowed(String contextPath, String uri, @Nullable String method,
@Nullable Authentication authentication) {
List<WebInvocationPrivilegeEvaluator> privilegeEvaluators = getDelegate(contextPath, uri, method);
if (privilegeEvaluators.isEmpty()) {
return true; | }
for (WebInvocationPrivilegeEvaluator evaluator : privilegeEvaluators) {
boolean isAllowed = evaluator.isAllowed(contextPath, uri, method, authentication);
if (!isAllowed) {
return false;
}
}
return true;
}
private List<WebInvocationPrivilegeEvaluator> getDelegate(@Nullable String contextPath, String uri,
@Nullable String method) {
FilterInvocation filterInvocation = new FilterInvocation(contextPath, uri, method, this.servletContext);
HttpServletRequest request = filterInvocation.getHttpRequest();
for (RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> delegate : this.delegates) {
if (delegate.getRequestMatcher().matches(request)) {
return delegate.getEntry();
}
}
return Collections.emptyList();
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.java | 1 |
请完成以下Java代码 | public void setIsXYPosition (boolean IsXYPosition)
{
set_Value (COLUMNNAME_IsXYPosition, Boolean.valueOf(IsXYPosition));
}
/** Get XY Position.
@return The Function is XY position
*/
public boolean isXYPosition ()
{
Object oo = get_Value(COLUMNNAME_IsXYPosition);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/ | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set XY Separator.
@param XYSeparator
The separator between the X and Y function.
*/
public void setXYSeparator (String XYSeparator)
{
set_Value (COLUMNNAME_XYSeparator, XYSeparator);
}
/** Get XY Separator.
@return The separator between the X and Y function.
*/
public String getXYSeparator ()
{
return (String)get_Value(COLUMNNAME_XYSeparator);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_LabelPrinterFunction.java | 1 |
请完成以下Java代码 | default Deserializer<V> getValueDeserializer() {
return null;
}
/**
* Remove a listener.
* @param listener the listener.
* @return true if removed.
* @since 2.5.3
*/
default boolean removeListener(Listener<K, V> listener) {
return false;
}
/**
* Add a listener at a specific index.
* @param index the index (list position).
* @param listener the listener.
* @since 2.5.3
*/
default void addListener(int index, Listener<K, V> listener) {
}
/**
* Add a listener.
* @param listener the listener.
* @since 2.5.3
*/
default void addListener(Listener<K, V> listener) {
}
/**
* Get the current list of listeners.
* @return the listeners.
* @since 2.5.3
*/
default List<Listener<K, V>> getListeners() {
return Collections.emptyList();
}
/**
* Add a post processor.
* @param postProcessor the post processor.
* @since 2.5.3
*/
default void addPostProcessor(ConsumerPostProcessor<K, V> postProcessor) {
}
/**
* Remove a post processor.
* @param postProcessor the post processor.
* @return true if removed.
* @since 2.5.3
*/
default boolean removePostProcessor(ConsumerPostProcessor<K, V> postProcessor) {
return false;
}
/**
* Get the current list of post processors.
* @return the post processor.
* @since 2.5.3
*/
default List<ConsumerPostProcessor<K, V>> getPostProcessors() {
return Collections.emptyList();
} | /**
* Update the consumer configuration map; useful for situations such as
* credential rotation.
* @param updates the configuration properties to update.
* @since 2.7
*/
default void updateConfigs(Map<String, Object> updates) {
}
/**
* Remove the specified key from the configuration map.
* @param configKey the key to remove.
* @since 2.7
*/
default void removeConfig(String configKey) {
}
/**
* Called whenever a consumer is added or removed.
*
* @param <K> the key type.
* @param <V> the value type.
*
* @since 2.5
*
*/
interface Listener<K, V> {
/**
* A new consumer was created.
* @param id the consumer id (factory bean name and client.id separated by a
* period).
* @param consumer the consumer.
*/
default void consumerAdded(String id, Consumer<K, V> consumer) {
}
/**
* An existing consumer was removed.
* @param id the consumer id (factory bean name and client.id separated by a
* period).
* @param consumer the consumer.
*/
default void consumerRemoved(@Nullable String id, Consumer<K, V> consumer) {
}
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\core\ConsumerFactory.java | 1 |
请完成以下Java代码 | public ResponseEntity<Object> createDeploy(@Validated @RequestBody Deploy resources){
deployService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改部署")
@ApiOperation(value = "修改部署")
@PutMapping
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> updateDeploy(@Validated @RequestBody Deploy resources){
deployService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除部署")
@ApiOperation(value = "删除部署")
@DeleteMapping
@PreAuthorize("@el.check('deploy:del')")
public ResponseEntity<Object> deleteDeploy(@RequestBody Set<Long> ids){
deployService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
@Log("上传文件部署")
@ApiOperation(value = "上传文件部署")
@PostMapping(value = "/upload")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> uploadDeploy(@RequestBody MultipartFile file, HttpServletRequest request)throws Exception{
Long id = Long.valueOf(request.getParameter("id"));
String fileName = "";
if(file != null){
fileName = FileUtil.verifyFilename(file.getOriginalFilename());
File deployFile = new File(fileSavePath + fileName);
FileUtil.del(deployFile);
file.transferTo(deployFile);
//文件下一步要根据文件名字来
deployService.deploy(fileSavePath + fileName ,id);
}else{
log.warn("没有找到相对应的文件");
}
Map<String,Object> map = new HashMap<>(2);
map.put("error",0);
map.put("id",fileName);
return new ResponseEntity<>(map,HttpStatus.OK);
}
@Log("系统还原")
@ApiOperation(value = "系统还原")
@PostMapping(value = "/serverReduction")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> serverReduction(@Validated @RequestBody DeployHistory resources){ | String result = deployService.serverReduction(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("服务运行状态")
@ApiOperation(value = "服务运行状态")
@PostMapping(value = "/serverStatus")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> serverStatus(@Validated @RequestBody Deploy resources){
String result = deployService.serverStatus(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("启动服务")
@ApiOperation(value = "启动服务")
@PostMapping(value = "/startServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> startServer(@Validated @RequestBody Deploy resources){
String result = deployService.startServer(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
@Log("停止服务")
@ApiOperation(value = "停止服务")
@PostMapping(value = "/stopServer")
@PreAuthorize("@el.check('deploy:edit')")
public ResponseEntity<Object> stopServer(@Validated @RequestBody Deploy resources){
String result = deployService.stopServer(resources);
return new ResponseEntity<>(result,HttpStatus.OK);
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\maint\rest\DeployController.java | 1 |
请完成以下Spring Boot application配置 | spring:
docker:
compose:
lifecycle-management: start_and_stop
start:
command: up
stop:
command: down
timeout: 10s
kafka:
consumer:
bootstrap-servers: localhost:10000
key-deserializer: org.apache.kafka.common.serialization.StringDeserializer
| value-deserializer: org.apache.kafka.common.serialization.StringDeserializer
properties:
group.protocol: consumer | repos\spring-kafka-main\samples\sample-07\src\main\resources\application.yaml | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<Employees> getAllEmployee(){
return mongoDB.findAll();
}
@GetMapping("/employee/{id}")
public ResponseEntity <Employees> getEmployeeById(@PathVariable(value = "id") String employeeId) throws ResourceNotFoundException{
Employees employees = mongoDB.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id::" + employeeId));
return ResponseEntity.ok().body(employees);
}
@PostMapping("/employees")
public Employees createEmployees(@Valid @RequestBody Employees employees) {
//
employees.setId(sequenceGeneratorService.generateSequence(Employees.SEQUENCE_NAME));
return mongoDB.save(employees);
}
@PutMapping("/employees/{id}")
public ResponseEntity <Employees> updateEmployee(@PathVariable(value = "id") String employeeId, @Valid @RequestBody Employees details) throws ResourceNotFoundException {
//
Employees employees = mongoDB.findById(employeeId)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found this id::" + employeeId)); | employees.setName(details.getName());
employees.setPhone(details.getPhone());
employees.setAge(details.getAge());
employees.setPosition(details.getPosition());
final Employees updatedEmployee = mongoDB.save(employees);
return ResponseEntity.ok(updatedEmployee);
}
@DeleteMapping("/employees/{id}")
public Map<String, Boolean> deleteEmployee(@PathVariable(value = "id") String id) throws ResourceNotFoundException {
//
Employees employees = mongoDB.findById(id)
.orElseThrow(() -> new ResourceNotFoundException("Employee not found for this id::" + id));
mongoDB.delete(employees);
Map<String, Boolean> response = new HashMap<>();
response.put("deleted", Boolean.TRUE);
return response;
}
} | repos\Spring-Boot-Advanced-Projects-main\SpringBoot-MongoDB-NoSQL-CRUD\src\main\java\com\urunov\mongodb\controller\EmployeeController.java | 2 |
请完成以下Java代码 | public class BPartnerEffective
{
@NonNull @Getter BPartnerId id;
@Nullable PaymentTermId paymentTermId;
@Nullable PaymentTermId poPaymentTermId;
@Nullable PricingSystemId pricingSystemId;
@Nullable PricingSystemId poPricingSystemId;
@NonNull InvoiceRule invoiceRule;
@NonNull InvoiceRule poInvoiceRule;
@NonNull PaymentRule paymentRule;
@NonNull PaymentRule poPaymentRule;
@Nullable Incoterms incoterms;
@Nullable Incoterms poIncoterms;
boolean isAutoInvoice;
@Nullable
public PaymentTermId getPaymentTermId(@NonNull final SOTrx soTrx)
{
return soTrx.isSales() ? paymentTermId : poPaymentTermId;
}
@Nullable
public PricingSystemId getPricingSystemId(@NonNull final SOTrx soTrx)
{
return soTrx.isSales() ? pricingSystemId : poPricingSystemId;
}
@NonNull | public PaymentRule getPaymentRule(@NonNull final SOTrx soTrx)
{
return soTrx.isSales() ? paymentRule : poPaymentRule;
}
@NonNull
public InvoiceRule getInvoiceRule(@NonNull final SOTrx soTrx)
{
return soTrx.isSales() ? invoiceRule : poInvoiceRule;
}
public boolean isAutoInvoice(@NonNull final SOTrx soTrx)
{
return soTrx.isSales() && isAutoInvoice;
}
@Nullable
public Incoterms getIncoterms(@NonNull final SOTrx soTrx)
{
return soTrx.isSales() ? incoterms : poIncoterms;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\effective\BPartnerEffective.java | 1 |
请完成以下Java代码 | public boolean hasNext()
{
if (currentRow == null)
{
currentRow = retrieveNextOrNull();
}
return currentRow != null;
}
@Override
public List<Object> next()
{
if (currentRow != null)
{
final List<Object> rowToReturn = currentRow;
currentRow = null;
return rowToReturn;
}
currentRow = retrieveNextOrNull();
if (currentRow == null)
{
throw new NoSuchElementException();
}
return currentRow;
}
@Override
public void remove()
{
throw new UnsupportedOperationException();
}
private List<Object> readLine(ResultSet rs, List<String> sqlFields) throws SQLException
{
final List<Object> values = new ArrayList<Object>();
for (final String columnName : sqlFields)
{
final Object value = rs.getObject(columnName);
values.add(value);
}
return values;
}
private Integer rowsCount = null;
@Override
public int size()
{
if (Check.isEmpty(sqlCount, true))
{
throw new IllegalStateException("Counting is not supported");
}
if (rowsCount == null)
{
logger.info("SQL: {}", sqlCount); | logger.info("SQL Params: {}", sqlParams);
rowsCount = DB.getSQLValueEx(Trx.TRXNAME_None, sqlCount, sqlParams);
logger.info("Rows Count: {}" + rowsCount);
}
return rowsCount;
}
public String getSqlSelect()
{
return sqlSelect;
}
public List<Object> getSqlParams()
{
if (sqlParams == null)
{
return Collections.emptyList();
}
return sqlParams;
}
public String getSqlWhereClause()
{
return sqlWhereClause;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\JdbcExportDataSource.java | 1 |
请完成以下Java代码 | public class MHRAttribute extends X_HR_Attribute
{
private static final long serialVersionUID = 3783311896401143394L;
/**
* @deprecated since 3.5.3a
* Get Concept by Value
* @param ctx
* @param value
* @param C_BPartner_ID
* @param startDate
* @return attribute
*/
@Deprecated
public static MHRAttribute forValue(Properties ctx, String value, int C_BPartner_ID, Timestamp date)
{
if (Check.isEmpty(value, true))
{
return null;
}
int AD_Client_ID = Env.getAD_Client_ID(ctx);
final String whereClause = COLUMNNAME_C_BPartner_ID+"=? AND AD_Client_ID IN (?,?) "
+ " AND " + COLUMNNAME_ValidFrom +"<=?"
+ " AND EXISTS (SELECT 1 FROM HR_Concept c WHERE HR_Attribute.HR_Concept_ID = c.HR_Concept_ID"
+ " AND c.Value=?)";
MHRAttribute att = new Query(ctx, Table_Name, whereClause, null)
.setParameters(new Object[]{C_BPartner_ID, 0, AD_Client_ID, date, value})
.setOnlyActiveRecords(true)
.setOrderBy(COLUMNNAME_ValidFrom + " DESC")
.first();
return att;
}
/**
* Get Concept by Value
* @param ctx
* @param value
* @param C_BPartner_ID
* @param startDate
* @param endDate
* @return attribute
*/
public static MHRAttribute forValue(Properties ctx, String value, int C_BPartner_ID, Timestamp startDate, Timestamp endDate)
{
if (Check.isEmpty(value, true))
{
return null;
}
if (endDate == null)
{
return forValue(ctx, value, C_BPartner_ID, startDate);
}
else | {
int AD_Client_ID = Env.getAD_Client_ID(ctx);
final String whereClause = COLUMNNAME_C_BPartner_ID+"=? AND AD_Client_ID IN (?,?) "
+ " AND " + COLUMNNAME_ValidFrom +"<=? AND " + COLUMNNAME_ValidTo +">=?"
+ " AND EXISTS (SELECT 1 FROM HR_Concept c WHERE HR_Attribute.HR_Concept_ID = c.HR_Concept_ID"
+ " AND c.Value=?)";
MHRAttribute att = new Query(ctx, Table_Name, whereClause, null)
.setParameters(new Object[]{C_BPartner_ID, 0, AD_Client_ID, startDate, endDate, value})
.setOnlyActiveRecords(true)
.setOrderBy(COLUMNNAME_ValidFrom + " DESC")
.first();
return att;
}
}
/**
* @param ctx
* @param HR_Attribute_ID
* @param trxName
*/
public MHRAttribute(Properties ctx, int HR_Attribute_ID, String trxName)
{
super(ctx, HR_Attribute_ID, trxName);
}
/**
* @param ctx
* @param rs
* @param trxName
*/
public MHRAttribute(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
}
@Override
public I_HR_Concept getHR_Concept()
{
return MHRConcept.get(getCtx(), getHR_Concept_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.libero.liberoHR\src\main\java\org\eevolution\model\MHRAttribute.java | 1 |
请完成以下Java代码 | public int accept(Method method) {
if (METHOD.equals(method.getName())) {
return 0;
}
return 1;
}
}
private enum LookupHandlerMethodInterceptor implements MethodInterceptor {
INSTANCE;
@Override
public Object intercept(Object target, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
if (ERROR_PATH.equals(args[0])) {
// by entering this branch we avoid the ZuulHandlerMapping.lookupHandler method to trigger the
// NoSuchMethodError
return null;
}
return methodProxy.invokeSuper(target, args);
}
}
private static final class ZuulPostProcessor implements BeanPostProcessor {
private final RouteLocator routeLocator; | private final ZuulController zuulController;
private final boolean hasErrorController;
ZuulPostProcessor(RouteLocator routeLocator, ZuulController zuulController, ErrorController errorController) {
this.routeLocator = routeLocator;
this.zuulController = zuulController;
this.hasErrorController = (errorController != null);
}
@Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
if (hasErrorController && (bean instanceof ZuulHandlerMapping)) {
Enhancer enhancer = new Enhancer();
enhancer.setSuperclass(ZuulHandlerMapping.class);
enhancer.setCallbackFilter(LookupHandlerCallbackFilter.INSTANCE); // only for lookupHandler
enhancer.setCallbacks(new Callback[] { LookupHandlerMethodInterceptor.INSTANCE, NoOp.INSTANCE });
Constructor<?> ctor = ZuulHandlerMapping.class.getConstructors()[0];
return enhancer.create(ctor.getParameterTypes(), new Object[] { routeLocator, zuulController });
}
return bean;
}
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-zuul\spring-zuul-ui\src\main\java\com\baeldung\spring\cloud\zuul\filter\ZuulConfiguration.java | 1 |
请完成以下Java代码 | public String getAuthorizationUri() {
return this.authorizationUri;
}
/**
* Returns the requested scope(s).
* @return the requested scope(s)
*/
public Set<String> getScopes() {
return this.scopes;
}
/**
* Returns the device code.
* @return the device code
*/
public OAuth2DeviceCode getDeviceCode() {
return this.deviceCode;
} | /**
* Returns the user code.
* @return the user code
*/
public OAuth2UserCode getUserCode() {
return this.userCode;
}
/**
* Returns the additional parameters.
* @return the additional parameters
*/
public Map<String, Object> getAdditionalParameters() {
return this.additionalParameters;
}
} | repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceAuthorizationRequestAuthenticationToken.java | 1 |
请完成以下Java代码 | void addPublicMethod() {
totalMethodCount++;
publicMethodCount++;
}
void addPrivateMethod() {
totalMethodCount++;
privateMethodCount++;
}
void addProtectedMethod() {
totalMethodCount++;
protectedMethodCount++;
}
void addPackagePrivateMethod() {
totalMethodCount++;
packagePrivateMethodCount++;
}
/**
* @return the totalMethodCount
*/
public int getTotalMethodCount() {
return totalMethodCount;
}
/**
* @return the publicMethodCount
*/
public int getPublicMethodCount() {
return publicMethodCount;
}
/**
* @return the protectedMethodCount | */
public int getProtectedMethodCount() {
return protectedMethodCount;
}
/**
* @return the privateMethodCount
*/
public int getPrivateMethodCount() {
return privateMethodCount;
}
/**
* @return the privateMethodCount
*/
public int getPackagePrivateMethodCount() {
return packagePrivateMethodCount;
}
}
} | repos\tutorials-master\libraries-transform\src\main\java\com\baeldung\spoon\ClassReporter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Book {
private String id;
private String isbn;
private String name;
private String author;
private Integer pages;
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 getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn; | }
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getPages() {
return pages;
}
public void setPages(Integer pages) {
this.pages = pages;
}
} | repos\tutorials-master\microservices-modules\helidon\helidon-mp\src\main\java\com\baeldung\microprofile\model\Book.java | 2 |
请完成以下Java代码 | private void markAsMultiplePayments(final I_C_BankStatementLine bankStatementLine)
{
bankStatementLine.setIsReconciled(true);
bankStatementLine.setIsMultiplePaymentOrInvoice(true);
bankStatementLine.setIsMultiplePayment(true);
bankStatementLine.setC_BPartner_ID(-1);
bankStatementLine.setC_Payment_ID(-1);
bankStatementLine.setC_Invoice_ID(-1);
bankStatementDAO.save(bankStatementLine);
}
private void createBankStatementLineRef(
@NonNull final PaymentToLink paymentToLink,
@NonNull final I_C_BankStatementLine bankStatementLine,
final int lineNo)
{
final PaymentId paymentId = paymentToLink.getPaymentId();
final I_C_Payment payment = getPaymentById(paymentId);
final BankStatementLineReference lineRef = bankStatementDAO.createBankStatementLineRef(BankStatementLineRefCreateRequest.builder()
.bankStatementId(BankStatementId.ofRepoId(bankStatementLine.getC_BankStatement_ID()))
.bankStatementLineId(BankStatementLineId.ofRepoId(bankStatementLine.getC_BankStatementLine_ID()))
.processed(bankStatementLine.isProcessed())
//
.orgId(OrgId.ofRepoId(bankStatementLine.getAD_Org_ID()))
//
.lineNo(lineNo)
//
.paymentId(paymentId)
.bpartnerId(BPartnerId.ofRepoId(payment.getC_BPartner_ID()))
.invoiceId(InvoiceId.ofRepoIdOrNull(payment.getC_Invoice_ID()))
//
.trxAmt(moneyService.toMoney(paymentToLink.getStatementLineAmt())) | //
.build());
//
// Mark payment as reconciled
if (doReconcilePayments)
{
paymentBL.markReconciledAndSave(
payment,
PaymentReconcileReference.bankStatementLineRef(lineRef.getId()));
}
//
linkedPayments.add(PaymentLinkResult.builder()
.bankStatementId(lineRef.getBankStatementId())
.bankStatementLineId(lineRef.getBankStatementLineId())
.bankStatementLineRefId(lineRef.getBankStatementLineRefId())
.paymentId(lineRef.getPaymentId())
.statementTrxAmt(lineRef.getTrxAmt())
.paymentMarkedAsReconciled(payment.isReconciled())
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\impl\BankStatementLineMultiPaymentLinkCommand.java | 1 |
请完成以下Java代码 | private void pollNewFiles()
{
log.fine("Polling directory: " + directory);
final File[] files = directory.listFiles();
if (files == null || files.length == 0)
{
return;
}
for (final File file : files)
{
if (!file.isFile())
{
continue;
}
final String ext = Util.getFileExtension(file.getName());
if (!fileExtension.equals(ext))
{
continue;
}
enqueueFile(file);
}
}
private boolean enqueueFile(final File file)
{
log.info("Enqueuing " + file);
PrintPackage printPackage = null;
InputStream printPackageStream = null;
final File dataFile = new File(Util.changeFileExtension(file.getAbsolutePath(), "pdf"));
InputStream printDataStream = null;
try
{
printPackageStream = new FileInputStream(file);
printPackage = beanEncoder.decodeStream(printPackageStream, PrintPackage.class);
printPackageStream.close();
printPackageStream = null;
printDataStream = new FileInputStream(dataFile);
final byte[] data = Util.toByteArray(printDataStream);
printDataStream.close();
printDataStream = new ByteArrayInputStream(data);
file.delete();
dataFile.delete();
}
catch (final Exception e)
{
log.log(Level.WARNING, e.getLocalizedMessage(), e);
return false; | }
finally
{
Util.close(printPackageStream);
Util.close(printDataStream);
}
log.info("Adding package to buffer: " + printPackage);
buffer.addPrintPackage(printPackage, printDataStream);
return true;
}
@Override
public String toString()
{
return "DirectoryPrintConnectionEndpoint [directory=" + directory + ", fileExtension=" + fileExtension + ", beanEncoder=" + beanEncoder + ", buffer=" + buffer + "]";
}
@Override
public LoginResponse login(final LoginRequest loginRequest)
{
throw new UnsupportedOperationException();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\endpoint\DirectoryPrintConnectionEndpoint.java | 1 |
请完成以下Java代码 | public LookupValue complete(final int addressDocIdInt, @Nullable final List<JSONDocumentChangedEvent> events)
{
final DocumentId addressDocId = DocumentId.of(addressDocIdInt);
final Document addressDoc = getAddressDocumentForWriting(addressDocId, NullDocumentChangesCollector.instance);
if (events != null && !events.isEmpty())
{
addressDoc.processValueChanges(events, REASON_ProcessAddressDocumentChanges);
}
final I_C_Location locationRecord = createC_Location(addressDoc);
trxManager
.getCurrentTrxListenerManagerOrAutoCommit()
.newEventListener(TrxEventTiming.AFTER_COMMIT)
.registerHandlingMethod(trx -> removeAddressDocumentById(addressDocId));
final String locationStr = locationBL.mkAddress(locationRecord);
return IntegerLookupValue.of(locationRecord.getC_Location_ID(), locationStr);
} | private I_C_Location createC_Location(final Document locationDoc)
{
final I_C_Location locationRecord = InterfaceWrapperHelper.create(Env.getCtx(), I_C_Location.class, ITrx.TRXNAME_ThreadInherited);
locationDoc.getFieldViews()
.forEach(locationField -> locationField
.getDescriptor()
.getDataBindingNotNull(AddressFieldBinding.class)
.writeValue(locationRecord, locationField));
locationDAO.save(locationRecord);
return locationRecord;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\address\AddressRepository.java | 1 |
请完成以下Java代码 | private void setBytes(byte[] bytes) {
if (id == null) {
if (bytes != null) {
entity = ByteArrayEntity.createAndInsert(name, bytes);
id = entity.getId();
}
} else {
ensureInitialized();
entity.setBytes(bytes);
}
}
public ByteArrayEntity getEntity() {
ensureInitialized();
return entity;
}
public void delete() {
if (!deleted && id != null) {
if (entity != null) {
// if the entity has been loaded already,
// we might as well use the safer optimistic locking delete.
Context.getCommandContext()
.getByteArrayEntityManager()
.deleteByteArray(entity);
} else {
Context.getCommandContext()
.getByteArrayEntityManager()
.deleteByteArrayById(id);
}
entity = null;
id = null;
deleted = true;
} | }
private void ensureInitialized() {
if (id != null && entity == null) {
entity = Context.getCommandContext()
.getByteArrayEntityManager()
.findById(id);
name = entity.getName();
}
}
public boolean isDeleted() {
return deleted;
}
@Override
public String toString() {
return "ByteArrayRef[id=" + id + ", name=" + name + ", entity=" + entity + (deleted ? ", deleted]" : "]");
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ByteArrayRef.java | 1 |
请完成以下Java代码 | protected final I_C_BankStatementLine getSingleSelectedBankStatementLine()
{
final BankStatementLineId lineId = getSingleSelectedBankStatementLineId();
return bankStatementBL.getLineById(lineId);
}
protected final BankStatementLineId getSingleSelectedBankStatementLineId()
{
final Set<Integer> bankStatementLineRepoIds = getSelectedIncludedRecordIds(I_C_BankStatementLine.class);
if (bankStatementLineRepoIds.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
else if (bankStatementLineRepoIds.size() == 1)
{
return BankStatementLineId.ofRepoId(bankStatementLineRepoIds.iterator().next());
}
else
{
throw new AdempiereException("More than one bank statement line selected: " + bankStatementLineRepoIds);
}
}
protected final void openBankStatementReconciliationView(@NonNull final Collection<PaymentId> paymentIds) | {
if (paymentIds.isEmpty())
{
throw new AdempiereException("@NoPayments@");
}
final BankStatementReconciliationView view = bankStatementReconciliationViewFactory.createView(BanksStatementReconciliationViewCreateRequest.builder()
.bankStatementLineId(getSingleSelectedBankStatementLineId())
.paymentIds(paymentIds)
.build());
final ViewId viewId = view.getViewId();
getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.viewId(viewId.toJson())
.target(ViewOpenTarget.ModalOverlay)
.build());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\banking\process\BankStatementBasedProcess.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductAndHUPIItemProductId
{
@NonNull
ProductId productId;
@NonNull
HUPIItemProductId hupiItemProductId;
@NonNull
public static Optional<ProductAndHUPIItemProductId> opt(
@Nullable final ProductId productId,
@NonNull final HUPIItemProductId hupiItemProductId)
{
if (productId == null)
{
return Optional.empty();
}
return Optional.of(new ProductAndHUPIItemProductId(productId, hupiItemProductId));
} | @NonNull
public static Optional<ProductAndHUPIItemProductId> opt(
@Nullable final ProductId productId)
{
if (productId == null)
{
return Optional.empty();
}
return Optional.of(new ProductAndHUPIItemProductId(productId, HUPIItemProductId.VIRTUAL_HU));
}
public static ProductAndHUPIItemProductId of(@NonNull final ProductId productId)
{
return new ProductAndHUPIItemProductId(productId, HUPIItemProductId.VIRTUAL_HU);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\product\ProductAndHUPIItemProductId.java | 2 |
请完成以下Java代码 | private static CostElementAccounts fromRecord(final I_M_CostElement_Acct record)
{
return CostElementAccounts.builder()
.acctSchemaId(AcctSchemaId.ofRepoId(record.getC_AcctSchema_ID()))
.P_CostClearing_Acct(AccountId.ofRepoId(record.getP_CostClearing_Acct()))
.build();
}
@Value(staticConstructor = "of")
private static class CostElementIdAndAcctSchemaId
{
@NonNull CostElementId costTypeId;
@NonNull AcctSchemaId acctSchemaId;
}
private static class CostElementAccountsMap
{
private final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map;
public CostElementAccountsMap(
@NonNull final ImmutableMap<CostElementIdAndAcctSchemaId, CostElementAccounts> map)
{
this.map = map;
} | public CostElementAccounts getAccounts(
@NonNull final CostElementId costElementId,
@NonNull final AcctSchemaId acctSchemaId)
{
final CostElementAccounts accounts = map.get(CostElementIdAndAcctSchemaId.of(costElementId, acctSchemaId));
if (accounts == null)
{
throw new AdempiereException("No accounts found for " + costElementId + " and " + acctSchemaId);
}
return accounts;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\CostElementAccountsRepository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DataScopeController extends BladeController {
private final IDataScopeService dataScopeService;
/**
* 详情
*/
@GetMapping("/detail")
@ApiOperationSupport(order = 1)
@Operation(summary = "详情", description = "传入dataScope")
public R<DataScope> detail(DataScope dataScope) {
DataScope detail = dataScopeService.getOne(Condition.getQueryWrapper(dataScope));
return R.data(detail);
}
/**
* 分页
*/
@GetMapping("/list")
@ApiOperationSupport(order = 2)
@Operation(summary = "分页", description = "传入dataScope")
public R<IPage<DataScopeVO>> list(DataScope dataScope, Query query) {
IPage<DataScope> pages = dataScopeService.page(Condition.getPage(query), Condition.getQueryWrapper(dataScope));
return R.data(DataScopeWrapper.build().pageVO(pages));
}
/**
* 新增
*/
@PostMapping("/save")
@ApiOperationSupport(order = 3)
@Operation(summary = "新增", description = "传入dataScope")
public R save(@Valid @RequestBody DataScope dataScope) {
CacheUtil.clear(SYS_CACHE);
return R.status(dataScopeService.save(dataScope));
} | /**
* 修改
*/
@PostMapping("/update")
@ApiOperationSupport(order = 4)
@Operation(summary = "修改", description = "传入dataScope")
public R update(@Valid @RequestBody DataScope dataScope) {
CacheUtil.clear(SYS_CACHE);
return R.status(dataScopeService.updateById(dataScope));
}
/**
* 新增或修改
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 5)
@Operation(summary = "新增或修改", description = "传入dataScope")
public R submit(@Valid @RequestBody DataScope dataScope) {
CacheUtil.clear(SYS_CACHE);
return R.status(dataScopeService.saveOrUpdate(dataScope));
}
/**
* 删除
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 6)
@Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
CacheUtil.clear(SYS_CACHE);
return R.status(dataScopeService.deleteLogic(Func.toLongList(ids)));
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\DataScopeController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setLabel (final java.lang.String Label)
{
set_ValueNoCheck (COLUMNNAME_Label, Label);
}
@Override
public java.lang.String getLabel()
{
return get_ValueAsString(COLUMNNAME_Label);
}
@Override
public de.metas.serviceprovider.model.I_S_Issue getS_Issue()
{
return get_ValueAsPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class);
}
@Override
public void setS_Issue(final de.metas.serviceprovider.model.I_S_Issue S_Issue)
{
set_ValueFromPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Issue);
}
@Override
public void setS_Issue_ID (final int S_Issue_ID)
{
if (S_Issue_ID < 1)
set_Value (COLUMNNAME_S_Issue_ID, null);
else
set_Value (COLUMNNAME_S_Issue_ID, S_Issue_ID);
}
@Override
public int getS_Issue_ID()
{ | return get_ValueAsInt(COLUMNNAME_S_Issue_ID);
}
@Override
public void setS_IssueLabel_ID (final int S_IssueLabel_ID)
{
if (S_IssueLabel_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_IssueLabel_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_IssueLabel_ID, S_IssueLabel_ID);
}
@Override
public int getS_IssueLabel_ID()
{
return get_ValueAsInt(COLUMNNAME_S_IssueLabel_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_IssueLabel.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ProcessEngine {
/** 受理器Map */
@InjectProcessors({
PlaceOrderProcessor.class,
PayProcessor.class,
ConfirmDeliveryProcessor.class,
ConfirmReceiveProcessor.class,
CancelOrderProcessor.class
})
private Map<ProcessReqEnum, Processor> processorMap;
private final Logger logger = LoggerFactory.getLogger(this.getClass());
/**
* 请求受理函数
* @param orderProcessContext 订单受理上下文(包含:req+rsp)
*/
public void process(OrderProcessContext orderProcessContext) {
// 校验参数
checkParam(orderProcessContext);
// 获取受理器
Processor processor = processorMap.get(orderProcessContext.getOrderProcessReq().getProcessReqEnum());
System.out.println(processorMap);
// 受理
processor.handle(orderProcessContext);
}
/**
* 参数校验
* @param orderProcessContext 订单受理上下文
*/
private void checkParam(OrderProcessContext orderProcessContext) {
// 受理上下文为空
if (orderProcessContext == null) {
throw new CommonSysException(ExpCodeEnum.PROCESSCONTEXT_NULL);
} | // 受理请求为空
if (orderProcessContext.getOrderProcessReq() == null) {
throw new CommonSysException(ExpCodeEnum.PROCESSREQ_NULL);
}
// 受理请求枚举为空
if (orderProcessContext.getOrderProcessReq().getProcessReqEnum() == null) {
throw new CommonSysException(ExpCodeEnum.PROCESSREQ_ENUM_NULL);
}
// orderId为空(除下单外)
if (orderProcessContext.getOrderProcessReq().getOrderId() == null
&& orderProcessContext.getOrderProcessReq().getProcessReqEnum() != ProcessReqEnum.PlaceOrder) {
throw new CommonSysException(ExpCodeEnum.PROCESSREQ_ORDERID_NULL);
}
// userId为空
if (orderProcessContext.getOrderProcessReq().getUserId() == null) {
throw new CommonSysException(ExpCodeEnum.PROCESSREQ_USERID_NULL);
}
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\engine\ProcessEngine.java | 2 |
请完成以下Java代码 | public void sectionTemplate() {
Map<String, Object> students = new LinkedHashMap<String, Object>();
students.put("name", "John");
students.put("name", "Mary");
students.put("name", "Disarray");
this.templateData.put("students", students);
}
public void nestingTemplate() {
List<Address> subData = new ArrayList<>();
subData.add(new Address("Florida,USA"));
subData.add(new Address("Texas,USA"));
this.templateData.put("nested", Includes.ofStream(WordDocumentFromTemplate.class.getClassLoader()
.getResourceAsStream("nested.docx"))
.setRenderModel(subData)
.create()); | }
public void refrenceTags() {
ChartMultiSeriesRenderData chart = Charts.ofMultiSeries("ChartTitle", new String[] { "Title", "English" })
.addSeries("countries", new Double[] { 15.0, 6.0 })
.addSeries("speakers", new Double[] { 223.0, 119.0 })
.create();
this.templateData.put("barChart", chart);
}
public void usingPlugins() {
this.templateData.put("sample", "custom-plugin");
}
} | repos\tutorials-master\apache-poi-3\src\main\java\com\baeldung\wordtemplate\WordDocumentFromTemplate.java | 1 |
请完成以下Java代码 | public class CachesEndpointWebExtension {
private final CachesEndpoint delegate;
public CachesEndpointWebExtension(CachesEndpoint delegate) {
this.delegate = delegate;
}
@ReadOperation
public WebEndpointResponse<CacheEntryDescriptor> cache(@Selector String cache, @Nullable String cacheManager) {
try {
CacheEntryDescriptor entry = this.delegate.cache(cache, cacheManager);
int status = (entry != null) ? WebEndpointResponse.STATUS_OK : WebEndpointResponse.STATUS_NOT_FOUND;
return new WebEndpointResponse<>(entry, status);
}
catch (NonUniqueCacheException ex) {
return new WebEndpointResponse<>(WebEndpointResponse.STATUS_BAD_REQUEST);
} | }
@DeleteOperation
public WebEndpointResponse<Void> clearCache(@Selector String cache, @Nullable String cacheManager) {
try {
boolean cleared = this.delegate.clearCache(cache, cacheManager);
int status = (cleared ? WebEndpointResponse.STATUS_NO_CONTENT : WebEndpointResponse.STATUS_NOT_FOUND);
return new WebEndpointResponse<>(status);
}
catch (NonUniqueCacheException ex) {
return new WebEndpointResponse<>(WebEndpointResponse.STATUS_BAD_REQUEST);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\actuate\endpoint\CachesEndpointWebExtension.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setAutoDialect(Boolean autoDialect) {
setProperty("autoDialect", autoDialect.toString());
}
public Boolean getCloseConn() {
return Boolean.valueOf(getProperty("closeConn"));
}
public void setCloseConn(Boolean closeConn) {
setProperty("closeConn", closeConn.toString());
}
public String getParams() {
return getProperty("params");
}
public void setParams(String params) {
setProperty("params", params);
}
public Boolean getDefaultCount() {
return Boolean.valueOf(getProperty("defaultCount"));
}
public void setDefaultCount(Boolean defaultCount) {
setProperty("defaultCount", defaultCount.toString());
}
public String getDialectAlias() {
return getProperty("dialectAlias");
}
public void setDialectAlias(String dialectAlias) {
setProperty("dialectAlias", dialectAlias);
}
public String getAutoDialectClass() {
return getProperty("autoDialectClass");
}
public void setAutoDialectClass(String autoDialectClass) {
setProperty("autoDialectClass", autoDialectClass);
} | public Boolean getAsyncCount() {
return Boolean.valueOf(getProperty("asyncCount"));
}
public void setAsyncCount(Boolean asyncCount) {
setProperty("asyncCount", asyncCount.toString());
}
public String getCountSqlParser() {
return getProperty("countSqlParser");
}
public void setCountSqlParser(String countSqlParser) {
setProperty("countSqlParser", countSqlParser);
}
public String getOrderBySqlParser() {
return getProperty("orderBySqlParser");
}
public void setOrderBySqlParser(String orderBySqlParser) {
setProperty("orderBySqlParser", orderBySqlParser);
}
public String getSqlServerSqlParser() {
return getProperty("sqlServerSqlParser");
}
public void setSqlServerSqlParser(String sqlServerSqlParser) {
setProperty("sqlServerSqlParser", sqlServerSqlParser);
}
public void setBannerEnabled(Boolean bannerEnabled) {
setProperty("banner",bannerEnabled.toString());
}
public Boolean getBannerEnabled() {
return Boolean.valueOf(getProperty("banner"));
}
} | repos\pagehelper-spring-boot-master\pagehelper-spring-boot-autoconfigure\src\main\java\com\github\pagehelper\autoconfigure\PageHelperProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Blog {
private final ArticleRepository articles;
private final ArticleSlugGenerator slugGenerator;
private final TransactionTemplate transactionTemplate;
private final RetryTemplate retryTemplate = new RetryTemplateBuilder().maxAttempts(5)
.fixedBackoff(Duration.ofMillis(100))
.build();
public Blog(ArticleRepository articleRepository, ArticleSlugGenerator articleSlugGenerator, TransactionTemplate transactionTemplate) {
this.articles = articleRepository;
this.slugGenerator = articleSlugGenerator;
this.transactionTemplate = transactionTemplate;
}
@Transactional
@Retryable(maxAttempts = 3)
public Article publishArticle(Long draftId) {
Article article = articles.findById(draftId)
.orElseThrow();
article.setStatus(Article.Status.PUBLISHED);
article.setSlug(slugGenerator.randomSlug());
return articles.save(article);
}
public Article publishArticle_v2(Long draftId) {
return retryTemplate.execute(retryCtx -> transactionTemplate.execute(txCtx -> {
Article article = articles.findById(draftId)
.orElseThrow(); | article.setStatus(Article.Status.PUBLISHED);
article.setSlug(slugGenerator.randomSlug());
return articles.save(article);
}));
}
public Optional<Article> findById(Long id) {
return articles.findById(id);
}
public Article create(Article article) {
return articles.save(article);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-annotations\src\main\java\com\baeldung\retryable\transactional\Blog.java | 2 |
请完成以下Java代码 | public class PlanningTableImpl extends TableItemImpl implements PlanningTable {
protected static ChildElementCollection<TableItem> tableItemCollection;
protected static ChildElementCollection<ApplicabilityRule> applicabilityRuleCollection;
public PlanningTableImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Collection<TableItem> getTableItems() {
return tableItemCollection.get(this);
}
public Collection<ApplicabilityRule> getApplicabilityRules() {
return applicabilityRuleCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanningTable.class, CMMN_ELEMENT_PLANNING_TABLE)
.namespaceUri(CMMN11_NS)
.extendsType(TableItem.class)
.instanceProvider(new ModelTypeInstanceProvider<PlanningTable>() {
public PlanningTable newInstance(ModelTypeInstanceContext instanceContext) { | return new PlanningTableImpl(instanceContext);
}
});
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
tableItemCollection = sequenceBuilder.elementCollection(TableItem.class)
.build();
applicabilityRuleCollection = sequenceBuilder.elementCollection(ApplicabilityRule.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanningTableImpl.java | 1 |
请完成以下Java代码 | public class HttpConnectorLogger extends ConnectLogger {
public void setHeader(String field, String value) {
logDebug("001", "Set header field '{}' to '{}'", field, value);
}
public void ignoreHeader(String field, String value) {
logInfo("002", "Ignoring header with name '{}' and value '{}'", field, value);
}
public void payloadIgnoredForHttpMethod(String method) {
logInfo("003", "Ignoring payload for HTTP '{}' method", method);
}
public ConnectorResponseException unableToReadResponse(Exception cause) {
return new ConnectorResponseException(exceptionMessage("004", "Unable to read connectorResponse: {}", cause.getMessage()), cause);
}
public ConnectorRequestException requestUrlRequired() {
return new ConnectorRequestException(exceptionMessage("005", "Request url required."));
}
public ConnectorRequestException unknownHttpMethod(String method) {
return new ConnectorRequestException(exceptionMessage("006", "Unknown or unsupported HTTP method '{}'", method));
} | public ConnectorRequestException unableToExecuteRequest(Exception cause) {
return new ConnectorRequestException(exceptionMessage("007", "Unable to execute HTTP request"), cause);
}
public ConnectorRequestException invalidConfigurationOption(String optionName, Exception cause) {
return new ConnectorRequestException(exceptionMessage("008", "Invalid value for request configuration option: {}", optionName), cause);
}
public void ignoreConfig(String field, Object value) {
logInfo("009", "Ignoring request configuration option with name '{}' and value '{}'", field, value);
}
public ConnectorRequestException httpRequestError(int statusCode , String connectorResponse) {
return new ConnectorRequestException(exceptionMessage("010", "HTTP request failed with Status Code: {} ,"
+ " Response: {}", statusCode, connectorResponse));
}
} | repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\HttpConnectorLogger.java | 1 |
请完成以下Java代码 | public void update(Group dbGroup) {
dbGroup.setId(id);
dbGroup.setName(name);
dbGroup.setType(type);
}
public static List<GroupDto> fromGroupList(List<Group> dbGroupList) {
List<GroupDto> resultList = new ArrayList<GroupDto>();
for (Group group : dbGroupList) {
resultList.add(fromGroup(group));
}
return resultList;
}
// Getters / Setters ///////////////////////////
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 getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\GroupDto.java | 1 |
请完成以下Java代码 | public void setVariableLocal(String variableName, Object value) {
if (execution == null && task == null) {
throw new ProcessEngineCdiException("Cannot set a local cached variable: neither a Task nor an Execution is associated.");
}
cachedVariablesLocal.put(variableName, value);
}
public VariableMap getCachedVariablesLocal() {
return cachedVariablesLocal;
}
public void flushVariableCache() {
if(task != null) {
taskService.setVariablesLocal(task.getId(), cachedVariablesLocal);
taskService.setVariables(task.getId(), cachedVariables); | } else if(execution != null) {
runtimeService.setVariablesLocal(execution.getId(), cachedVariablesLocal);
runtimeService.setVariables(execution.getId(), cachedVariables);
} else {
throw new ProcessEngineCdiException("Cannot flush variable cache: neither a Task nor an Execution is associated.");
}
// clear variable cache after flush
cachedVariables.clear();
cachedVariablesLocal.clear();
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\context\ScopedAssociation.java | 1 |
请完成以下Java代码 | public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((requestDate == null) ? 0 : requestDate.hashCode());
result = prime * result + ((nameRequest == null) ? 0 : nameRequest.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
SessionNameRequest other = (SessionNameRequest) obj;
if (requestDate == null) {
if (other.requestDate != null)
return false; | } else if (!requestDate.equals(other.requestDate))
return false;
if (nameRequest == null) {
if (other.nameRequest != null)
return false;
} else if (!nameRequest.equals(other.nameRequest))
return false;
return true;
}
@Override
public String toString() {
return "SessionNameRequest [requestDate=" + requestDate + ", nameRequest=" + nameRequest + "]";
}
} | repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\web\beans\SessionNameRequest.java | 1 |
请完成以下Java代码 | private void dumpUpdateSqls(final String classname)
{
System.out.println("-- Generated with " + getClass() + " by " + System.getProperty("user.name"));
final List<String> updateSqls = createUpdateSqls(classname);
for (final String updateSql : updateSqls)
{
System.out.println(updateSql);
}
}
private List<String> createUpdateSqls(String classname)
{
final List<String> updateSqls = new ArrayList<>();
final Class<?> clazz = loadClass(classname);
final Field[] classFields = clazz.getFields();
for (final Field field : classFields)
{
final String fieldName = field.getName();
if (!fieldName.endsWith(SUFFIX_AD_Reference_ID))
{
continue;
}
final int adReferenceId = getFieldValueAsInt(field);
final String prefix = fieldName.substring(0, fieldName.length() - SUFFIX_AD_Reference_ID.length());
final Map<String, String> name2value = extractNameAndValueForPrefix(prefix, classFields);
updateSqls.add("\n\n-- " + prefix);
updateSqls.addAll(createUpdateSqls(adReferenceId, name2value));
}
return updateSqls;
}
private List<String> createUpdateSqls(int adReferenceId, Map<String, String> name2valuesMap)
{
final List<String> updateSqls = new ArrayList<>(name2valuesMap.size());
for (final Map.Entry<String, String> name2value : name2valuesMap.entrySet())
{
final String name = name2value.getKey();
final String value = name2value.getValue();
final String sql = "UPDATE AD_Ref_List SET ValueName='" + name + "'"
+ " WHERE AD_Reference_ID=" + adReferenceId
+ " AND Value='" + value + "'"
+ ";";
updateSqls.add(sql);
}
return updateSqls;
}
private Map<String, String> extractNameAndValueForPrefix(String prefix, Field[] classFields)
{
final Map<String, String> name2value = new LinkedHashMap<>();
for (final Field field : classFields)
{
final String fieldName = field.getName();
if (!fieldName.startsWith(prefix))
{
continue;
}
if (fieldName.endsWith(SUFFIX_AD_Reference_ID))
{
continue;
} | final String name = fieldName.substring(prefix.length());
final String value = getFieldValueAsString(field);
name2value.put(name, value);
}
return name2value;
}
private final String getFieldValueAsString(final Field field)
{
try
{
return (String)field.get(null);
}
catch (Exception e)
{
throw new RuntimeException("Cannot get value of " + field);
}
}
private final int getFieldValueAsInt(final Field field)
{
try
{
return (int)field.get(null);
}
catch (Exception e)
{
throw new RuntimeException("Cannot get value of " + field);
}
}
private Class<?> loadClass(String classname)
{
final ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
try
{
return classLoader.loadClass(classname);
}
catch (ClassNotFoundException e)
{
throw new RuntimeException("Cannot load class: " + classname, e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\tools\AD_Ref_List_ValueName_UpdateFromClass.java | 1 |
请完成以下Java代码 | public Attribute getByCodeOrNull(final AttributeCode attributeCode)
{
return attributesByCode.get(attributeCode);
}
@NonNull
public Attribute getById(@NonNull final AttributeId id)
{
final Attribute attribute = getByIdOrNull(id);
if (attribute == null)
{
throw new AdempiereException("No Attribute found for ID: " + id);
}
return attribute;
}
@Nullable
public Attribute getByIdOrNull(final @NotNull AttributeId id)
{
return attributesById.get(id);
}
@NonNull
public Set<Attribute> getByIds(@NonNull final Collection<AttributeId> ids)
{
if (ids.isEmpty()) {return ImmutableSet.of();}
return ids.stream()
.distinct()
.map(this::getById)
.collect(ImmutableSet.toImmutableSet());
}
@NonNull
public AttributeId getIdByCode(@NonNull final AttributeCode attributeCode)
{
return getByCode(attributeCode).getAttributeId();
}
public Set<Attribute> getByCodes(final Set<AttributeCode> attributeCodes) | {
if (attributeCodes.isEmpty()) {return ImmutableSet.of();}
return attributeCodes.stream()
.distinct()
.map(this::getByCode)
.collect(ImmutableSet.toImmutableSet());
}
@NonNull
public ImmutableList<AttributeCode> getOrderedAttributeCodesByIds(@NonNull final List<AttributeId> orderedAttributeIds)
{
if (orderedAttributeIds.isEmpty())
{
return ImmutableList.of();
}
return orderedAttributeIds.stream()
.map(this::getById)
.filter(Attribute::isActive)
.map(Attribute::getAttributeCode)
.collect(ImmutableList.toImmutableList());
}
public Stream<Attribute> streamActive()
{
return attributesById.values().stream().filter(Attribute::isActive);
}
public boolean isActiveAttribute(final AttributeId id)
{
final Attribute attribute = getByIdOrNull(id);
return attribute != null && attribute.isActive();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributesMap.java | 1 |
请完成以下Java代码 | private MoneySourceAndAcct calcAmount(
final MoneySourceAndAcct taxAmt,
final MoneySourceAndAcct invoiceGrandTotalAmt,
final Money discountAmt,
final CurrencyPrecision acctPrecision)
{
if (taxAmt.signum() == 0
|| invoiceGrandTotalAmt.signum() == 0
|| discountAmt.signum() == 0)
{
return taxAmt.toZero();
}
final CurrencyPrecision sourcePrecision = services.getCurrencyStandardPrecision(taxAmt.getSourceCurrencyId());
return taxAmt.divide(invoiceGrandTotalAmt, CurrencyPrecision.TEN)
.multiply(discountAmt.toBigDecimal())
.roundIfNeeded(sourcePrecision, acctPrecision);
}
private static MoneySourceAndAcct extractMoneySourceAndAcctDebit(final I_Fact_Acct factAcct, final AcctSchema as)
{
return extractMoneySourceAndAcct(factAcct, as, true);
}
private static MoneySourceAndAcct extractMoneySourceAndAcctCredit(final I_Fact_Acct factAcct, final AcctSchema as)
{
return extractMoneySourceAndAcct(factAcct, as, false);
}
private static MoneySourceAndAcct extractMoneySourceAndAcct(final I_Fact_Acct factAcct, final AcctSchema as, boolean isDebit)
{
final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoId(factAcct.getC_AcctSchema_ID()); | Check.assumeEquals(acctSchemaId, as.getId(), "acctSchema");
final CurrencyId sourceCurrencyId = CurrencyId.ofRepoId(factAcct.getC_Currency_ID());
final CurrencyId acctCurrencyId = as.getCurrencyId();
final Money source;
final Money acct;
if (isDebit)
{
source = Money.of(factAcct.getAmtSourceDr(), sourceCurrencyId);
acct = Money.of(factAcct.getAmtAcctDr(), acctCurrencyId);
}
else
{
source = Money.of(factAcct.getAmtSourceCr(), sourceCurrencyId);
acct = Money.of(factAcct.getAmtAcctCr(), acctCurrencyId);
}
return MoneySourceAndAcct.ofSourceAndAcct(source, acct);
}
} // Doc_AllocationTax | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Doc_AllocationHdr.java | 1 |
请完成以下Java代码 | public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public String[] getActivityInstanceIds() {
return activityInstanceIds;
}
public String[] getActivityIds() {
return activityIds;
}
public String[] getTenantIds() {
return tenantIds;
}
public HistoricDecisionInstanceQuery includeInputs() {
includeInput = true;
return this;
}
@Override
public HistoricDecisionInstanceQuery includeOutputs() {
includeOutputs = true;
return this;
}
public boolean isIncludeInput() {
return includeInput;
}
public boolean isIncludeOutputs() {
return includeOutputs;
}
@Override
public HistoricDecisionInstanceQuery disableBinaryFetching() {
isByteArrayFetchingEnabled = false;
return this;
}
@Override
public HistoricDecisionInstanceQuery disableCustomObjectDeserialization() {
isCustomObjectDeserializationEnabled = false;
return this;
}
public boolean isByteArrayFetchingEnabled() {
return isByteArrayFetchingEnabled;
}
public boolean isCustomObjectDeserializationEnabled() {
return isCustomObjectDeserializationEnabled;
}
public String getRootDecisionInstanceId() {
return rootDecisionInstanceId;
}
public HistoricDecisionInstanceQuery rootDecisionInstanceId(String rootDecisionInstanceId) {
ensureNotNull(NotValidException.class, "rootDecisionInstanceId", rootDecisionInstanceId);
this.rootDecisionInstanceId = rootDecisionInstanceId;
return this;
} | public boolean isRootDecisionInstancesOnly() {
return rootDecisionInstancesOnly;
}
public HistoricDecisionInstanceQuery rootDecisionInstancesOnly() {
this.rootDecisionInstancesOnly = true;
return this;
}
@Override
public HistoricDecisionInstanceQuery decisionRequirementsDefinitionId(String decisionRequirementsDefinitionId) {
ensureNotNull(NotValidException.class, "decisionRequirementsDefinitionId", decisionRequirementsDefinitionId);
this.decisionRequirementsDefinitionId = decisionRequirementsDefinitionId;
return this;
}
@Override
public HistoricDecisionInstanceQuery decisionRequirementsDefinitionKey(String decisionRequirementsDefinitionKey) {
ensureNotNull(NotValidException.class, "decisionRequirementsDefinitionKey", decisionRequirementsDefinitionKey);
this.decisionRequirementsDefinitionKey = decisionRequirementsDefinitionKey;
return this;
}
public String getDecisionRequirementsDefinitionId() {
return decisionRequirementsDefinitionId;
}
public String getDecisionRequirementsDefinitionKey() {
return decisionRequirementsDefinitionKey;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricDecisionInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public Class<? extends SentryPartInstanceEntity> getManagedEntityClass() {
return SentryPartInstanceEntityImpl.class;
}
@Override
public SentryPartInstanceEntity create() {
return new SentryPartInstanceEntityImpl();
}
@Override
public List<SentryPartInstanceEntity> findSentryPartInstancesByCaseInstanceId(String caseInstanceId) {
return getList("selectSentryPartInstanceByCaseInstanceId", caseInstanceId, sentryPartByCaseInstanceIdEntityMatched);
}
@Override
public List<SentryPartInstanceEntity> findSentryPartInstancesByCaseInstanceIdAndNullPlanItemInstanceId(String caseInstanceId) {
return getList("selectSentryPartInstanceByCaseInstanceIdAndNullPlanItemInstanceId", caseInstanceId);
}
@Override
public List<SentryPartInstanceEntity> findSentryPartInstancesByPlanItemInstanceId(String planItemInstanceId) {
return getList("selectSentryPartInstanceByPlanItemInstanceId", planItemInstanceId, sentryPartByPlanItemInstanceIdEntityMatched);
}
@Override
public void deleteByCaseInstanceId(String caseInstanceId) {
bulkDelete("deleteSentryPartInstancesByCaseInstanceId", sentryPartByCaseInstanceIdEntityMatched, caseInstanceId);
}
public static class SentryPartByCaseInstanceIdEntityMatcher extends CachedEntityMatcherAdapter<SentryPartInstanceEntity> {
@Override
public boolean isRetained(SentryPartInstanceEntity sentryPartInstanceEntity, Object param) { | return sentryPartInstanceEntity.getPlanItemInstanceId() == null
&& sentryPartInstanceEntity.getCaseInstanceId().equals(param);
}
}
public static class SentryPartByPlanItemInstanceIdEntityMatcher extends CachedEntityMatcherAdapter<SentryPartInstanceEntity> {
@Override
public boolean isRetained(SentryPartInstanceEntity sentryPartInstanceEntity, Object param) {
return sentryPartInstanceEntity.getPlanItemInstanceId() != null
&& sentryPartInstanceEntity.getPlanItemInstanceId().equals(param);
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisSentryPartInstanceDataManagerImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SentinelAspectConfiguration {
public static final String RESOURCE_NAME = "greeting";
@Bean
public SentinelResourceAspect sentinelResourceAspect() {
return new SentinelResourceAspect();
}
@PostConstruct
public void init() {
initFlowRules();
initDegradeRules();
initSystemProtectionRules();
}
private void initFlowRules() {
List<FlowRule> flowRules = new ArrayList<>();
FlowRule flowRule = new FlowRule();
// Defined resource
flowRule.setResource(RESOURCE_NAME);
flowRule.setGrade(RuleConstant.FLOW_GRADE_QPS);
// number of requests that QPS can pass in a second
flowRule.setCount(1);
flowRules.add(flowRule); | FlowRuleManager.loadRules(flowRules);
}
private void initDegradeRules() {
List<DegradeRule> rules = new ArrayList<DegradeRule>();
DegradeRule rule = new DegradeRule();
rule.setResource(RESOURCE_NAME);
rule.setCount(10);
rule.setTimeWindow(10);
rules.add(rule);
DegradeRuleManager.loadRules(rules);
}
private void initSystemProtectionRules() {
List<SystemRule> rules = new ArrayList<>();
SystemRule rule = new SystemRule();
rule.setHighestSystemLoad(10);
rules.add(rule);
SystemRuleManager.loadRules(rules);
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-sentinel\src\main\java\com\baeldung\spring\cloud\sentinel\config\SentinelAspectConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ApiController {
@Resource
private CompanyService companyService;
@RequestMapping(value = "/isCompany/{company}", method = RequestMethod.GET)
public Integer isCompamy(@PathVariable("company") String company) {
return companyService.isCompany(company);
}
@RequestMapping(value = "/add", method = RequestMethod.GET)
public Integer isCompamy() {
return companyService.add();
}
@RequestMapping(value = "/del", method = RequestMethod.GET)
public Integer del() {
return companyService.del();
} | @RequestMapping(value = "/string/set", method = RequestMethod.GET)
public Integer set() {
String key = "string2";
JSONObject jsonObject = new JSONObject();
jsonObject.put("raw_value", "娃哈哈(北京)");
jsonObject.put("clean_value", "娃哈哈(北京)有限公司");
jsonObject.put("isLabel", 1);
companyService.set(key,jsonObject.toString());
return 1;
}
@RequestMapping(value = "/string/get", method = RequestMethod.GET)
public String get() {
return companyService.get("string2");
}
} | repos\spring-boot-quick-master\quick-redies\src\main\java\com\quick\redis\controller\ApiController.java | 2 |
请完成以下Java代码 | public void onParentResume(CmmnActivityExecution execution) {
ensureNotCaseInstance(execution, "parentResume");
String id = execution.getId();
if (!execution.isSuspended()) {
throw LOG.wrongCaseStateException("parentResume", id, "resume", "suspended", execution.getCurrentState().toString());
}
CmmnActivityExecution parent = execution.getParent();
if (parent != null) {
if (!parent.isActive()) {
throw LOG.resumeInactiveCaseException("parentResume", id);
}
}
resuming(execution);
}
// occur ////////////////////////////////////////////////////////
public void onOccur(CmmnActivityExecution execution) {
String id = execution.getId();
throw LOG.illegalStateTransitionException("occur", id, getTypeName());
}
// sentry ///////////////////////////////////////////////////////////////
public void fireEntryCriteria(CmmnActivityExecution execution) {
boolean manualActivation = evaluateManualActivationRule(execution);
if (manualActivation) { | execution.enable();
} else {
execution.start();
}
}
// manual activation rule //////////////////////////////////////////////
protected boolean evaluateManualActivationRule(CmmnActivityExecution execution) {
boolean manualActivation = false;
CmmnActivity activity = execution.getActivity();
Object manualActivationRule = activity.getProperty(PROPERTY_MANUAL_ACTIVATION_RULE);
if (manualActivationRule != null) {
CaseControlRule rule = (CaseControlRule) manualActivationRule;
manualActivation = rule.evaluate(execution);
}
return manualActivation;
}
// helper ///////////////////////////////////////////////////////////
protected abstract String getTypeName();
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\behavior\StageOrTaskActivityBehavior.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void augmentQueryBuilder(@NonNull final IQueryBuilder<I_MD_Candidate> builder)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_MD_Candidate_StockChange_Detail> stockChangeDetailSubQueryBuilder = queryBL
.createQueryBuilder(I_MD_Candidate_StockChange_Detail.class)
.addOnlyActiveRecordsFilter();
final Integer computedFreshQtyOnHandId = NumberUtils.asInteger(getFreshQuantityOnHandRepoId(), -1);
if (computedFreshQtyOnHandId > 0)
{
stockChangeDetailSubQueryBuilder.addEqualsFilter(I_MD_Candidate_StockChange_Detail.COLUMN_Fresh_QtyOnHand_ID, computedFreshQtyOnHandId);
}
final Integer computedFreshQtyOnHandLineId = NumberUtils.asInteger(getFreshQuantityOnHandLineRepoId(), -1);
if (computedFreshQtyOnHandLineId > 0)
{
stockChangeDetailSubQueryBuilder.addEqualsFilter(I_MD_Candidate_StockChange_Detail.COLUMN_Fresh_QtyOnHand_Line_ID, computedFreshQtyOnHandLineId);
}
final Integer computedInventoryId = NumberUtils.asInteger(getInventoryId(), -1);
if (computedInventoryId > 0)
{
stockChangeDetailSubQueryBuilder.addEqualsFilter(I_MD_Candidate_StockChange_Detail.COLUMN_M_Inventory_ID, computedInventoryId);
}
final Integer computedInventoryLineId = NumberUtils.asInteger(getInventoryLineId(), -1); | if (computedInventoryLineId > 0)
{
stockChangeDetailSubQueryBuilder.addEqualsFilter(I_MD_Candidate_StockChange_Detail.COLUMN_M_InventoryLine_ID, computedInventoryLineId);
}
if (getIsReverted() != null)
{
stockChangeDetailSubQueryBuilder.addEqualsFilter(I_MD_Candidate_StockChange_Detail.COLUMN_IsReverted, getIsReverted());
}
builder.addInSubQueryFilter(I_MD_Candidate.COLUMN_MD_Candidate_ID,
I_MD_Candidate_StockChange_Detail.COLUMN_MD_Candidate_ID,
stockChangeDetailSubQueryBuilder.create());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\query\StockChangeDetailQuery.java | 2 |
请完成以下Java代码 | public class DmnEvaluatedOutputImpl implements DmnEvaluatedOutput {
protected String id;
protected String name;
protected String outputName;
protected TypedValue value;
public DmnEvaluatedOutputImpl(DmnDecisionTableOutputImpl decisionTableOutput, TypedValue value) {
this.id = decisionTableOutput.getId();
this.name = decisionTableOutput.getName();
this.outputName = decisionTableOutput.getOutputName();
this.value = value;
}
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 getOutputName() {
return outputName;
}
public void setOutputName(String outputName) {
this.outputName = outputName;
}
public TypedValue getValue() {
return value;
}
public void setValue(TypedValue value) {
this.value = value;
}
@Override | public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
DmnEvaluatedOutputImpl that = (DmnEvaluatedOutputImpl) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (outputName != null ? !outputName.equals(that.outputName) : that.outputName != null) return false;
return !(value != null ? !value.equals(that.value) : that.value != null);
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (outputName != null ? outputName.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public String toString() {
return "DmnEvaluatedOutputImpl{" +
"id='" + id + '\'' +
", name='" + name + '\'' +
", outputName='" + outputName + '\'' +
", value=" + value +
'}';
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\delegate\DmnEvaluatedOutputImpl.java | 1 |
请完成以下Java代码 | public void createTopicIfNotExists(String topic, String properties, boolean force) {}
@Override
public void destroy() {}
@Override
public void deleteTopic(String topic) {}
});
templateBuilder.requestTemplate(producerTemplate);
templateBuilder.responseTemplate(consumerTemplate);
templateBuilder.maxPendingRequests(transportApiSettings.getMaxPendingRequests());
templateBuilder.maxRequestTimeout(transportApiSettings.getMaxRequestsTimeout());
templateBuilder.pollInterval(transportApiSettings.getResponsePollInterval());
return templateBuilder.build();
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToRuleEngineMsg>> createRuleEngineMsgProducer() {
return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(transportApiSettings.getRequestsTopic()));
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToCoreMsg>> createTbCoreMsgProducer() { | return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getTopic()));
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToCoreNotificationMsg>> createTbCoreNotificationsMsgProducer() {
return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getTopic()));
}
@Override
public TbQueueConsumer<TbProtoQueueMsg<ToTransportMsg>> createTransportNotificationsConsumer() {
return new InMemoryTbQueueConsumer<>(storage, topicService.buildTopicName(transportNotificationSettings.getNotificationsTopic() + "." + serviceInfoProvider.getServiceId()));
}
@Override
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToUsageStatsServiceMsg>> createToUsageStatsServiceMsgProducer() {
return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getUsageStatsTopic()));
}
@Override
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToHousekeeperServiceMsg>> createHousekeeperMsgProducer() {
return new InMemoryTbQueueProducer<>(storage, topicService.buildTopicName(coreSettings.getHousekeeperTopic()));
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\InMemoryTbTransportQueueFactory.java | 1 |
请完成以下Java代码 | public static boolean containsKey(String key)
{
return trie.containsKey(key);
}
/**
* 包含key,且key至少长length
* @param key
* @param length
* @return
*/
public static boolean containsKey(String key, int length)
{
if (!trie.containsKey(key)) return false;
return key.length() >= length;
}
public static Character get(String key)
{
return trie.get(key);
}
public static DoubleArrayTrie<Character>.LongestSearcher getSearcher(char[] charArray)
{
return trie.getLongestSearcher(charArray, 0);
}
/**
* 最长分词
*/
public static class Searcher extends BaseSearcher<Character>
{
/**
* 分词从何处开始,这是一个状态
*/
int begin;
DoubleArrayTrie<Character> trie;
protected Searcher(char[] c, DoubleArrayTrie<Character> trie)
{
super(c); | this.trie = trie;
}
protected Searcher(String text, DoubleArrayTrie<Character> trie)
{
super(text);
this.trie = trie;
}
@Override
public Map.Entry<String, Character> next()
{
// 保证首次调用找到一个词语
Map.Entry<String, Character> result = null;
while (begin < c.length)
{
LinkedList<Map.Entry<String, Character>> entryList = trie.commonPrefixSearchWithValue(c, begin);
if (entryList.size() == 0)
{
++begin;
}
else
{
result = entryList.getLast();
offset = begin;
begin += result.getKey().length();
break;
}
}
if (result == null)
{
return null;
}
return result;
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\nr\JapanesePersonDictionary.java | 1 |
请完成以下Java代码 | public boolean contains(@NonNull final AttributesKey attributesKey)
{
return parts.containsAll(attributesKey.parts);
}
public AttributesKey getIntersection(@NonNull final AttributesKey attributesKey)
{
final HashSet<AttributesKeyPart> ownMutableParts = new HashSet<>(parts);
ownMutableParts.retainAll(attributesKey.parts);
return AttributesKey.ofParts(ownMutableParts);
}
/**
* @return {@code true} if ad least one attributeValueId from the given {@code attributesKey} is included in this instance.
*/
public boolean intersects(@NonNull final AttributesKey attributesKey)
{
return parts.stream().anyMatch(attributesKey.parts::contains);
}
public String getValueByAttributeId(@NonNull final AttributeId attributeId)
{
for (final AttributesKeyPart part : parts)
{
if (part.getType() == AttributeKeyPartType.AttributeIdAndValue
&& AttributeId.equals(part.getAttributeId(), attributeId))
{
return part.getValue();
}
}
throw new AdempiereException("Attribute `" + attributeId + "` was not found in `" + this + "`");
} | public static boolean equals(@Nullable final AttributesKey k1, @Nullable final AttributesKey k2)
{
return Objects.equals(k1, k2);
}
@Override
public int compareTo(@Nullable final AttributesKey o)
{
if (o == null)
{
return 1; // we assume that null is less than not-null
}
return this.getAsString().compareTo(o.getAsString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\AttributesKey.java | 1 |
请完成以下Java代码 | public CustomerHolder searchBy(@PathVariable String name) {
return CustomerHolder.from(this.customerService.findBy(name))
.setCacheMiss(this.customerService.isCacheMiss());
}
// end::rest-api-endpoint[]
@GetMapping("/ping")
public String pingPong() {
return "PONG";
}
@GetMapping("/")
public String home() {
return String.format("%s is running!",
environment.getProperty("spring.application.name", "UNKNOWN"));
}
public static class CustomerHolder {
public static CustomerHolder from(Customer customer) {
return new CustomerHolder(customer);
}
private boolean cacheMiss = true;
private final Customer customer; | protected CustomerHolder(Customer customer) {
Assert.notNull(customer, "Customer must not be null");
this.customer = customer;
}
public CustomerHolder setCacheMiss(boolean cacheMiss) {
this.cacheMiss = cacheMiss;
return this;
}
public boolean isCacheMiss() {
return this.cacheMiss;
}
public Customer getCustomer() {
return customer;
}
}
}
// end::class[] | repos\spring-boot-data-geode-main\spring-geode-samples\caching\multi-site\src\main\java\example\app\caching\multisite\client\web\CustomerController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configure()
{
//@formatter:off
errorHandler(defaultErrorHandler());
onException(Exception.class)
.to(direct(MF_ERROR_ROUTE_ID));
from("timer://runOnce?repeatCount=1")
.routeId(HANDLE_EXTERNAL_SYSTEM_SERVICES_ROUTE_ID)
.log("ExternalSystemRestAPIHandler - Route invoked! Checking with externalsystem-routes to start")
.startupOrder(CamelRoutesStartUpOrder.ONE.getValue())
.process(this::prepareQueryServiceStatusRequests)
.split(body())
.to("{{" + ExternalSystemCamelConstants.MF_GET_SERVICE_STATUS_V2_CAMEL_URI + "}}")
.process(this::filterActiveServices)
.split(body())
.process(this::createEnableServiceRequest)
.to("{{" + ExternalSystemCamelConstants.MF_INVOKE_EXTERNAL_SYSTEM_ACTION_V2_CAMEL_URI + "}}");
//@formatter:on
}
private void prepareQueryServiceStatusRequests(@NonNull final Exchange exchange)
{
final List<RetreiveServiceStatusCamelRequest> retreiveServiceStatusRequests = externalSystemServices.stream()
.map(IExternalSystemService::getExternalSystemTypeCode)
.collect(ImmutableSet.toImmutableSet())
.stream()
.map(type -> RetreiveServiceStatusCamelRequest.builder().type(type).build())
.collect(ImmutableList.toImmutableList());
exchange.getIn().setBody(retreiveServiceStatusRequests);
}
private void filterActiveServices(@NonNull final Exchange exchange)
{
final JsonExternalStatusResponse externalStatusInfoResponse = exchange.getIn().getBody(JsonExternalStatusResponse.class); | exchange.getIn().setBody(externalStatusInfoResponse.getExternalStatusResponses()
.stream()
.filter(response -> response.getExpectedStatus().equals(JsonExternalStatus.Active))
.collect(ImmutableList.toImmutableList()));
}
private void createEnableServiceRequest(@NonNull final Exchange exchange)
{
final JsonExternalStatusResponseItem externalStatusResponse = exchange.getIn().getBody(JsonExternalStatusResponseItem.class);
final Optional<IExternalSystemService> matchedExternalService = externalSystemServices.stream()
.filter(externalService -> externalService.getServiceValue().equals(externalStatusResponse.getServiceValue()))
.findFirst();
if (matchedExternalService.isEmpty())
{
log.warn("*** No Service found for value = " + externalStatusResponse.getServiceValue() + " !");
return;
}
final InvokeExternalSystemActionCamelRequest camelRequest = InvokeExternalSystemActionCamelRequest.builder()
.externalSystemChildValue(externalStatusResponse.getExternalSystemChildValue())
.externalSystemConfigType(externalStatusResponse.getExternalSystemConfigType())
.command(matchedExternalService.get().getEnableCommand())
.build();
exchange.getIn().setBody(camelRequest, InvokeExternalSystemActionCamelRequest.class);
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\restapi\ExternalSystemRestAPIHandler.java | 2 |
请完成以下Java代码 | public class DroolsUtil {
public static final Logger log = LoggerFactory.getLogger(DroolsUtil.class);
/**
* 线程安全单例
*/
private static volatile KieServices kieServices = KieServices.Factory.get();
/**
* KieBase容器,线程安全单例
*/
private static volatile KieContainer kieContainer;
/**
* 加载KieContainer容器
*/
public static KieContainer loadKieContainer() throws RuntimeException {
//通过kmodule.xml 找到规则文件,这个文件默认放在resources/META-INF文件夹
log.info("准备创建 KieContainer");
if (kieContainer == null) {
log.info("首次创建:KieContainer");
// 设置drools的日期格式
System.setProperty("drools.dateformat", "yyyy-MM-dd HH:mm:ss");
//线程安全
synchronized (DroolsUtil.class) {
if (kieContainer == null) {
// 创建Container
kieContainer = kieServices.getKieClasspathContainer();
// 检查规则文件是否有错
Results results = kieContainer.verify();
if (results.hasMessages(Message.Level.ERROR)) {
StringBuffer sb = new StringBuffer();
for (Message mes : results.getMessages()) {
sb.append("解析错误的规则:").append(mes.getPath()).append(" 错误位置:").append(mes.getLine()).append(";");
}
throw new RuntimeException(sb.toString());
}
}
}
}
log.info("KieContainer创建完毕");
return kieContainer;
} | /**
* 根据kiesession 名称创建KieSession ,每次调用都是一个新的KieSession
* @param name kiesession的名称
* @return 一个新的KieSession,每次使用后要销毁
*/
public static KieSession getKieSessionByName(String name) {
if (kieContainer == null) {
kieContainer = loadKieContainer();
}
KieSession kieSession;
try {
kieSession = kieContainer.newKieSession(name);
} catch (Exception e) {
log.error("根据名称:" + name + " 创建kiesession异常");
throw new RuntimeException(e);
}
return kieSession;
}
} | repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\utils\DroolsUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
private final Class<T> clazz;
FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException
{
if (t == null) {
return new byte[0];
} | return JSON.toJSONString(t, JSONWriter.Feature.WriteClassName).getBytes(StandardCharsets.UTF_8);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException
{
if (bytes == null || bytes.length == 0) {
return null;
}
String str = new String(bytes, StandardCharsets.UTF_8);
return JSON.parseObject(str, clazz);
}
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\config\RedisConfiguration.java | 2 |
请完成以下Java代码 | public int getParameterCount()
{
return 0;
}
@Override
public String getLabel(final int index)
{
return null;
}
@Override
public Object getParameterComponent(final int index)
{
return null;
}
@Override
public Object getParameterToComponent(final int index)
{
return null;
}
@Override
public Object getParameterValue(final int index, final boolean returnValueTo)
{
return null;
}
@Override
public String[] getWhereClauses(final List<Object> params)
{
return new String[0];
}
@Override
public String getText()
{
return null;
}
@Override
public void save(final Properties ctx, final int windowNo, final IInfoWindowGridRowBuilders builders)
{
for (final IHUPackingAware record : packingInfos.values())
{
// We need to create a key that depends on both the product and the PIIP.
// Note that we assume that both columns are read-only and therefore won't change!
// Keep in sync with the other controllers in this package!
// It's 1:17am, it has to be rolled out tomorrow and i *won't* make it any nicer tonight.
// Future generations will have to live with this shit or rewrite it.
final int recordId = new HashCodeBuilder()
.append(record.getM_Product_ID())
.append(record.getM_HU_PI_Item_Product_ID())
.toHashCode();
final OrderLineHUPackingGridRowBuilder builder = new OrderLineHUPackingGridRowBuilder();
builder.setSource(record);
builders.addGridTabRowBuilder(recordId, builder);
}
}
/** | * Gets existing {@link IHUPackingAware} record for given row (wrapped as IHUPackingAware) or null.
*
* @param rowIndexModel
* @return {@link IHUPackingAware} or null
*/
private IHUPackingAware getSavedHUPackingAware(final IHUPackingAware rowRecord)
{
final ArrayKey key = mkKey(rowRecord);
return packingInfos.get(key);
}
@Override
public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel)
{
// nothing
}
@Override
public String getProductCombinations()
{
final List<Integer> piItemProductIds = new ArrayList<Integer>();
for (final IHUPackingAware record : packingInfos.values())
{
piItemProductIds.add(record.getM_HU_PI_Item_Product_ID());
}
if (!piItemProductIds.isEmpty() && piItemProductIds != null)
{
final StringBuilder sb = new StringBuilder(piItemProductIds.get(0).toString());
for (int i = 1; i < piItemProductIds.size(); i++)
{
sb.append(", " + piItemProductIds.get(i).toString());
}
return " AND (" + M_HU_PI_Item_Product_table_alias + "." + I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_Product_ID + " IN " + " ( " + sb + " ) "
+ " OR " + M_HU_PI_Item_Product_table_alias + "." + I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_Product_ID + " IS NULL" + ") ";
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductQtyPacksController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getAddress1(final Customer customer) {
return customer.getAddress();
}
/**
* The method returns the customer's address,
but refreshes all the entries in the cache to load new ones.
*
* @param customer the customer
* @return the address
*/
@CacheEvict(value = "addresses", allEntries = true)
public String getAddress2(final Customer customer) {
return customer.getAddress();
}
/**
* The method returns the customer's address,
but not before selectively evicting the cache as per specified paramters.
*
* @param customer the customer
* @return the address
*/
@Caching(evict = { @CacheEvict("addresses"), @CacheEvict(value = "directory", key = "#customer.name") })
public String getAddress3(final Customer customer) {
return customer.getAddress();
}
/**
* The method uses the class level cache to look up for entries. | *
* @param customer the customer
* @return the address
*/
@Cacheable
// parameter not required as we have declared it using @CacheConfig
public String getAddress4(final Customer customer) {
return customer.getAddress();
}
/**
* The method selectively caches the results that meet the predefined criteria.
*
* @param customer the customer
* @return the address
*/
@CachePut(value = "addresses", condition = "#customer.name=='Tom'")
// @CachePut(value = "addresses", unless = "#result.length>64")
public String getAddress5(final Customer customer) {
return customer.getAddress();
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-caching\src\main\java\com\baeldung\caching\example\CustomerDataService.java | 2 |
请完成以下Java代码 | public TUMergeBuilder setSourceHUs(final List<I_M_HU> sourceHUs)
{
this.sourceHUs = sourceHUs;
return this;
}
@Override
public TUMergeBuilder setTargetTU(final I_M_HU targetHU)
{
this.targetHU = targetHU;
return this;
}
@Override
public TUMergeBuilder setCUProductId(final ProductId cuProductId)
{
this.cuProductId = cuProductId;
return this;
}
@Override
public TUMergeBuilder setCUQty(final BigDecimal qty)
{
cuQty = qty;
return this;
}
@Override
public TUMergeBuilder setCUUOM(final I_C_UOM uom)
{
cuUOM = uom;
return this;
}
@Override
public TUMergeBuilder setCUTrxReferencedModel(final Object trxReferencedModel)
{
cuTrxReferencedModel = trxReferencedModel;
return this;
}
@Override
public void mergeTUs()
{
huTrxBL.createHUContextProcessorExecutor(huContextInitial).run((IHUContextProcessor)huContext0 -> {
// Make a copy of the processing context, we will need to modify it
final IMutableHUContext huContext = huContext0.copyAsMutable();
// Register our split HUTrxListener because this "merge" operation is similar with a split
// More, this will allow our listeners to execute on-split operations (e.g. linking the newly created VHU to same document as the source VHU).
huContext.getTrxListeners().addListener(HUSplitBuilderTrxListener.instance);
mergeTUs0(huContext);
return IHUContextProcessor.NULL_RESULT; // we don't care about the result
});
}
private void mergeTUs0(final IHUContext huContext)
{ | final IAllocationRequest allocationRequest = createMergeAllocationRequest(huContext);
//
// Source: Selected handling units
final IAllocationSource source = HUListAllocationSourceDestination.of(sourceHUs);
//
// Destination: Handling unit we want to merge on
final IAllocationDestination destination = HUListAllocationSourceDestination.of(targetHU);
//
// Perform allocation
HULoader.of(source, destination)
.setAllowPartialUnloads(true) // force allow partial unloads when merging
.setAllowPartialLoads(true) // force allow partial loads when merging
.load(allocationRequest); // execute it; we don't care about the result
//
// Destroy HUs which had their storage emptied
for (final I_M_HU sourceHU : sourceHUs)
{
handlingUnitsBL.destroyIfEmptyStorage(huContext, sourceHU);
}
}
/**
* Create an allocation request for the cuQty of the builder
*
* @param huContext
* @param referencedModel referenced model to be used in created request
* @return created request
*/
private IAllocationRequest createMergeAllocationRequest(final IHUContext huContext)
{
final ZonedDateTime date = SystemTime.asZonedDateTime();
return AllocationUtils.createQtyRequest(
huContext,
cuProductId, // Product
Quantity.of(cuQty, cuUOM), // quantity
date, // Date
cuTrxReferencedModel, // Referenced model
false // force allocation
);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\transfer\impl\TUMergeBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GeoLocationConfigRestController
{
static final String ENDPOINT = WebConfig.ENDPOINT_ROOT + "/geolocation/config";
private final GeocodingConfigRepository geocodingConfigRepository;
public GeoLocationConfigRestController(@NonNull final GeocodingConfigRepository geocodingConfigRepository)
{
this.geocodingConfigRepository = geocodingConfigRepository;
}
@GetMapping
public JsonGeoLocationConfig getConfig()
{
if (!geocodingConfigRepository.getGeocodingConfig().isPresent())
{
return JsonGeoLocationConfig.builder().build();
}
final GeocodingConfig geocodingConfig = geocodingConfigRepository.getGeocodingConfig().get();
switch (geocodingConfig.getProviderName())
{
case GOOGLE_MAPS:
return getGoogleMapsConfig(geocodingConfig);
case OPEN_STREET_MAPS:
return getOpenStreetMapsConfig();
default:
return JsonGeoLocationConfig.builder().build();
} | }
@NonNull
private JsonGeoLocationConfig getOpenStreetMapsConfig()
{
return JsonGeoLocationConfig.builder()
.provider(JsonGeoLocationProvider.OpenStreetMaps)
.build();
}
@NonNull
private JsonGeoLocationConfig getGoogleMapsConfig(@NonNull final GeocodingConfig geocodingConfig)
{
final GeocodingConfig.GoogleMapsConfig googleMapsConfig = geocodingConfig.getGoogleMapsConfig();
return JsonGeoLocationConfig.builder()
.provider(JsonGeoLocationProvider.GoogleMaps)
.googleMapsApiKey(googleMapsConfig.getApiKey())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\geo_location\GeoLocationConfigRestController.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.