instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private final void createWeeklyPlanningQtyReportEvents(final I_PMM_WeekReport_Event weekReportEvent)
{
final Timestamp dateWeek = TimeUtil.trunc(weekReportEvent.getWeekDate(), TimeUtil.TRUNC_WEEK);
final Timestamp dateTwoWeeksAgo = TimeUtil.addDays(dateWeek, -2 * 7);
final SyncProductSupply syncProductSupply_TwoWeeksAgo = SyncProductSupply.builder()
.bpartner_uuid(SyncUUIDs.toUUIDString(weekReportEvent.getC_BPartner()))
.product_uuid(SyncUUIDs.toUUIDString(weekReportEvent.getPMM_Product()))
.contractLine_uuid(null) // unknown
.qty(BigDecimal.ZERO)
.weekPlanning(true)
.day(TimeUtil.asLocalDate(dateTwoWeeksAgo))
.build();
Services.get(IServerSyncBL.class).reportProductSupplies(PutProductSuppliesRequest.of(syncProductSupply_TwoWeeksAgo));
}
private void markError(
@NonNull final I_PMM_WeekReport_Event event,
@NonNull final Exception e)
{
event.setProcessed(true); | final AdempiereException metasfreshException = AdempiereException.wrapIfNeeded(e);
final String errorMsg = CoalesceUtil.firstNotEmptyTrimmed(metasfreshException.getLocalizedMessage(), metasfreshException.getMessage());
event.setErrorMsg(errorMsg);
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(metasfreshException);
event.setAD_Issue_ID(issueId.getRepoId());
InterfaceWrapperHelper.save(event);
Loggables.addLog("Event has error with message: {}; event={}", errorMsg, event);
}
public String getProcessSummary()
{
return "@Processed@ #" + countProcessed.get() + ", @Skipped@ #" + countSkipped.get();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\PMMWeekReportEventTrxItemProcessor.java | 1 |
请完成以下Java代码 | public void exceptionWhilePerformingOperationStep(String name, Exception e) {
logError(
"044",
"Exception while performing '{}': {}", name, e.getMessage(), e);
}
public void debugRejectedExecutionException(RejectedExecutionException e) {
logDebug(
"045",
"RejectedExecutionException while scheduling work", e);
}
public void foundTomcatDeploymentDescriptor(String bpmPlatformFileLocation, String fileLocation) {
logInfo(
"046",
"Found Camunda Platform configuration in CATALINA_BASE/CATALINA_HOME conf directory [{}] at '{}'", bpmPlatformFileLocation, fileLocation);
}
public ProcessEngineException invalidDeploymentDescriptorLocation(String bpmPlatformFileLocation, MalformedURLException e) {
throw new ProcessEngineException(exceptionMessage(
"047",
"'{} is not a valid Camunda Platform configuration resource location.", bpmPlatformFileLocation), e);
}
public void camundaBpmPlatformSuccessfullyStarted(String serverInfo) {
logInfo(
"048",
"Camunda Platform sucessfully started at '{}'.", serverInfo); | }
public void camundaBpmPlatformStopped(String serverInfo) {
logInfo(
"049",
"Camunda Platform stopped at '{}'", serverInfo);
}
public void paDeployed(String name) {
logInfo(
"050",
"Process application {} successfully deployed", name);
}
public void paUndeployed(String name) {
logInfo(
"051",
"Process application {} undeployed", name);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\ContainerIntegrationLogger.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void prepareErrorResponse(@NonNull final Exchange exchange)
{
final Exception exception = exchange.getProperty(Exchange.EXCEPTION_CAUGHT, Exception.class);
if (exception == null)
{
exchange.getIn().setBody(null);
exchange.getIn().setHeader(HTTP_RESPONSE_CODE, HttpStatus.INTERNAL_SERVER_ERROR.value());
return;
}
final int httpCode = exception instanceof JsonProcessingException
? HttpStatus.BAD_REQUEST.value()
: HttpStatus.INTERNAL_SERVER_ERROR.value();
final JsonError jsonError = JsonError.ofSingleItem(ErrorBuilderHelper.buildJsonErrorItem(exchange));
exchange.getIn().setBody(jsonError);
exchange.getIn().setHeader(HTTP_RESPONSE_CODE, httpCode);
}
private void prepareSuccessResponse(@NonNull final Exchange exchange)
{
exchange.getIn().setBody(null);
exchange.getIn().setHeader(HTTP_RESPONSE_CODE, HttpStatus.OK.value()
);
}
private void prepareRestAPIContext(@NonNull final Exchange exchange)
{
final JsonExternalSystemRequest request = exchange.getIn().getBody(JsonExternalSystemRequest.class);
final GRSRestAPIContext context = GRSRestAPIContext.builder()
.request(request)
.build();
exchange.setProperty(GRSSignumConstants.ROUTE_PROPERTY_GRS_REST_API_CONTEXT, context);
}
private void prepareExternalStatusCreateRequest(@NonNull final Exchange exchange, @NonNull final JsonExternalStatus externalStatus)
{
final GRSRestAPIContext context = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_GRS_REST_API_CONTEXT, GRSRestAPIContext.class);
final JsonExternalSystemRequest request = context.getRequest();
final JsonStatusRequest jsonStatusRequest = JsonStatusRequest.builder()
.status(externalStatus)
.pInstanceId(request.getAdPInstanceId())
.build();
final ExternalStatusCreateCamelRequest camelRequest = ExternalStatusCreateCamelRequest.builder() | .jsonStatusRequest(jsonStatusRequest)
.externalSystemConfigType(getExternalSystemTypeCode())
.externalSystemChildConfigValue(request.getExternalSystemChildConfigValue())
.serviceValue(getServiceValue())
.build();
exchange.getIn().setBody(camelRequest, JsonExternalSystemRequest.class);
}
private void prepareHttpErrorResponse(@NonNull final Exchange exchange)
{
final JsonError jsonError = ErrorProcessor.processHttpErrorEncounteredResponse(exchange);
exchange.getIn().setBody(jsonError);
}
@Override
public String getServiceValue()
{
return "defaultRestAPIGRS";
}
@Override
public String getExternalSystemTypeCode()
{
return GRSSIGNUM_SYSTEM_NAME;
}
@Override
public String getEnableCommand()
{
return ENABLE_RESOURCE_ROUTE;
}
@Override
public String getDisableCommand()
{
return DISABLE_RESOURCE_ROUTE;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\restapi\GRSRestAPIRouteBuilder.java | 2 |
请完成以下Java代码 | public I_C_JobCategory getC_JobCategory() throws RuntimeException
{
return (I_C_JobCategory)MTable.get(getCtx(), I_C_JobCategory.Table_Name)
.getPO(getC_JobCategory_ID(), get_TrxName()); }
/** Set Position Category.
@param C_JobCategory_ID
Job Position Category
*/
public void setC_JobCategory_ID (int C_JobCategory_ID)
{
if (C_JobCategory_ID < 1)
set_Value (COLUMNNAME_C_JobCategory_ID, null);
else
set_Value (COLUMNNAME_C_JobCategory_ID, Integer.valueOf(C_JobCategory_ID));
}
/** Get Position Category.
@return Job Position Category
*/
public int getC_JobCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_JobCategory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Position.
@param C_Job_ID
Job Position
*/
public void setC_Job_ID (int C_Job_ID)
{
if (C_Job_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Job_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Job_ID, Integer.valueOf(C_Job_ID));
}
/** Get Position.
@return Job Position
*/
public int getC_Job_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Job_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help) | {
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Employee.
@param IsEmployee
Indicates if this Business Partner is an employee
*/
public void setIsEmployee (boolean IsEmployee)
{
set_Value (COLUMNNAME_IsEmployee, Boolean.valueOf(IsEmployee));
}
/** Get Employee.
@return Indicates if this Business Partner is an employee
*/
public boolean isEmployee ()
{
Object oo = get_Value(COLUMNNAME_IsEmployee);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Job.java | 1 |
请完成以下Java代码 | public void afterPropertiesSet() {
Assert.isTrue(!(isConvertAttributeToUpperCase() && isConvertAttributeToLowerCase()),
"Either convertAttributeToUpperCase or convertAttributeToLowerCase can be set to true, but not both");
}
/**
* Map the given list of string attributes one-to-one to Spring Security
* GrantedAuthorities.
*/
@Override
public List<GrantedAuthority> getGrantedAuthorities(Collection<String> attributes) {
List<GrantedAuthority> result = new ArrayList<>(attributes.size());
for (String attribute : attributes) {
result.add(getGrantedAuthority(attribute));
}
return result;
}
/**
* Map the given role one-on-one to a Spring Security GrantedAuthority, optionally
* doing case conversion and/or adding a prefix.
* @param attribute The attribute for which to get a GrantedAuthority
* @return GrantedAuthority representing the given role.
*/
private GrantedAuthority getGrantedAuthority(String attribute) {
if (isConvertAttributeToLowerCase()) {
attribute = attribute.toLowerCase(Locale.ROOT);
}
else if (isConvertAttributeToUpperCase()) {
attribute = attribute.toUpperCase(Locale.ROOT);
}
if (isAddPrefixIfAlreadyExisting() || !attribute.startsWith(getAttributePrefix())) {
return new SimpleGrantedAuthority(getAttributePrefix() + attribute);
}
else {
return new SimpleGrantedAuthority(attribute);
}
}
private boolean isConvertAttributeToLowerCase() {
return this.convertAttributeToLowerCase;
}
public void setConvertAttributeToLowerCase(boolean b) {
this.convertAttributeToLowerCase = b;
}
private boolean isConvertAttributeToUpperCase() { | return this.convertAttributeToUpperCase;
}
public void setConvertAttributeToUpperCase(boolean b) {
this.convertAttributeToUpperCase = b;
}
private String getAttributePrefix() {
return (this.attributePrefix != null) ? this.attributePrefix : "";
}
public void setAttributePrefix(String string) {
this.attributePrefix = string;
}
private boolean isAddPrefixIfAlreadyExisting() {
return this.addPrefixIfAlreadyExisting;
}
public void setAddPrefixIfAlreadyExisting(boolean b) {
this.addPrefixIfAlreadyExisting = b;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\core\authority\mapping\SimpleAttributes2GrantedAuthoritiesMapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setOrder(@NonNull final Order order)
{
this.order = order;
importedExternalHeaderIds.add(order.getOrderId());
}
@NonNull
public Optional<Instant> getNextImportStartingTimestamp()
{
if (nextImportStartingTimestamp == null)
{
return Optional.empty();
}
return Optional.of(nextImportStartingTimestamp.getTimestamp());
}
/**
* Update next import timestamp to the most current one.
*/
public void setNextImportStartingTimestamp(@NonNull final DateAndImportStatus dateAndImportStatus)
{
if (this.nextImportStartingTimestamp == null)
{
this.nextImportStartingTimestamp = dateAndImportStatus;
return; | }
if (this.nextImportStartingTimestamp.isOkToImport())
{
if (dateAndImportStatus.isOkToImport()
&& dateAndImportStatus.getTimestamp().isAfter(this.nextImportStartingTimestamp.getTimestamp()))
{
this.nextImportStartingTimestamp = dateAndImportStatus;
return;
}
if (!dateAndImportStatus.isOkToImport())
{
this.nextImportStartingTimestamp = dateAndImportStatus;
return;
}
}
if (!this.nextImportStartingTimestamp.isOkToImport()
&& !dateAndImportStatus.isOkToImport()
&& dateAndImportStatus.getTimestamp().isBefore(this.nextImportStartingTimestamp.getTimestamp()))
{
this.nextImportStartingTimestamp = dateAndImportStatus;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\de-metas-camel-ebay-camelroutes\src\main\java\de\metas\camel\externalsystems\ebay\EbayImportOrdersRouteContext.java | 2 |
请完成以下Java代码 | public class GetTaskFormCmd implements Command<TaskFormData>, Serializable {
private static final long serialVersionUID = 1L;
protected String taskId;
public GetTaskFormCmd(String taskId) {
this.taskId = taskId;
}
@Override
public TaskFormData execute(CommandContext commandContext) {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
TaskEntity task = processEngineConfiguration.getTaskServiceConfiguration().getTaskService().getTask(taskId);
if (task == null) {
throw new FlowableObjectNotFoundException("No task found for taskId '" + taskId + "'", Task.class);
} | if (task.getProcessDefinitionId() != null && Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, task.getProcessDefinitionId())) {
Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
return compatibilityHandler.getTaskFormData(taskId);
}
FormHandlerHelper formHandlerHelper = processEngineConfiguration.getFormHandlerHelper();
TaskFormHandler taskFormHandler = formHandlerHelper.getTaskFormHandlder(task);
if (taskFormHandler == null) {
throw new FlowableException("No taskFormHandler specified for '" + task + "'");
}
return taskFormHandler.createTaskForm(task);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetTaskFormCmd.java | 1 |
请完成以下Java代码 | public VariableServiceConfiguration getVariableServiceConfiguration() {
return variableServiceConfiguration;
}
public AppEngineConfiguration setVariableServiceConfiguration(VariableServiceConfiguration variableServiceConfiguration) {
this.variableServiceConfiguration = variableServiceConfiguration;
return this;
}
public boolean isSerializableVariableTypeTrackDeserializedObjects() {
return serializableVariableTypeTrackDeserializedObjects;
}
public AppEngineConfiguration setSerializableVariableTypeTrackDeserializedObjects(boolean serializableVariableTypeTrackDeserializedObjects) {
this.serializableVariableTypeTrackDeserializedObjects = serializableVariableTypeTrackDeserializedObjects;
return this;
}
public boolean isJsonVariableTypeTrackObjects() {
return jsonVariableTypeTrackObjects;
}
public AppEngineConfiguration setJsonVariableTypeTrackObjects(boolean jsonVariableTypeTrackObjects) {
this.jsonVariableTypeTrackObjects = jsonVariableTypeTrackObjects;
return this;
}
@Override
public VariableJsonMapper getVariableJsonMapper() {
return variableJsonMapper;
}
@Override
public AppEngineConfiguration setVariableJsonMapper(VariableJsonMapper variableJsonMapper) {
this.variableJsonMapper = variableJsonMapper;
return this;
}
public boolean isDisableIdmEngine() {
return disableIdmEngine;
} | public AppEngineConfiguration setDisableIdmEngine(boolean disableIdmEngine) {
this.disableIdmEngine = disableIdmEngine;
return this;
}
public boolean isDisableEventRegistry() {
return disableEventRegistry;
}
public AppEngineConfiguration setDisableEventRegistry(boolean disableEventRegistry) {
this.disableEventRegistry = disableEventRegistry;
return this;
}
public BusinessCalendarManager getBusinessCalendarManager() {
return businessCalendarManager;
}
public AppEngineConfiguration setBusinessCalendarManager(BusinessCalendarManager businessCalendarManager) {
this.businessCalendarManager = businessCalendarManager;
return this;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\AppEngineConfiguration.java | 1 |
请完成以下Java代码 | public PPOrderWeightingRun getById(@NonNull final PPOrderWeightingRunId id)
{
return ppOrderWeightingRunRepository.getById(id);
}
public void process(final PPOrderWeightingRunId id)
{
ppOrderWeightingRunRepository.updateById(id, PPOrderWeightingRun::process);
}
public void unprocess(final PPOrderWeightingRunId id)
{
ppOrderWeightingRunRepository.updateById(id, PPOrderWeightingRun::unprocess);
}
public SeqNo getNextLineNo(final PPOrderWeightingRunId weightingRunId)
{
return ppOrderWeightingRunRepository.getNextLineNo(weightingRunId);
}
public void updateFromChecks(final Collection<PPOrderWeightingRunId> ids)
{
// NOTE: we usually expect only one element here, so it's OK to iterate
for (final PPOrderWeightingRunId id : ids)
{
ppOrderWeightingRunRepository.updateById(id, PPOrderWeightingRun::updateToleranceExceededFlag);
}
}
public UomId getUomId(final PPOrderWeightingRunId id)
{
return ppOrderWeightingRunRepository.getUomId(id);
}
public PPOrderWeightingRunCheckId addRunCheck( | @NonNull PPOrderWeightingRunId weightingRunId,
@NonNull final BigDecimal weightBD)
{
PPOrderWeightingRun weightingRun = getById(weightingRunId);
final Quantity weight = Quantity.of(weightBD, weightingRun.getUOM());
final SeqNo lineNo = weightingRun.getNextLineNo();
final OrgId orgId = weightingRun.getOrgId();
final PPOrderWeightingRunCheckId weightingRunCheckId = ppOrderWeightingRunRepository.addRunCheck(weightingRunId, lineNo, weight, orgId);
weightingRun = getById(weightingRunId);
weightingRun.updateToleranceExceededFlag();
ppOrderWeightingRunRepository.save(weightingRun);
return weightingRunCheckId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\manufacturing\order\weighting\run\PPOrderWeightingRunService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getHazardousWeight() {
return hazardousWeight;
}
/**
* Sets the value of the hazardousWeight property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setHazardousWeight(BigDecimal value) {
this.hazardousWeight = value;
}
/**
* Gets the value of the netWeight property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getNetWeight() {
return netWeight;
}
/**
* Sets the value of the netWeight property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setNetWeight(BigDecimal value) {
this.netWeight = value;
}
/**
* Gets the value of the factor property.
*
*/
public int getFactor() {
return factor;
}
/**
* Sets the value of the factor property.
*
*/
public void setFactor(int value) {
this.factor = value;
} | /**
* Gets the value of the notOtherwiseSpecified property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNotOtherwiseSpecified() {
return notOtherwiseSpecified;
}
/**
* Sets the value of the notOtherwiseSpecified property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNotOtherwiseSpecified(String value) {
this.notOtherwiseSpecified = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Hazardous.java | 2 |
请完成以下Spring Boot application配置 | #
# The MIT License (MIT)
#
# Copyright (c) 2017 abel533@gmail.com
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DE | ALINGS IN
# THE SOFTWARE.
#
spring.sql.init.schema-locations=import.sql
debug=true
logging.level.root=WARN
logging.level.tk.mybatis.pagehelper.mapper=TRACE
#pagehelper.
pagehelper.autoDialect=true
pagehelper.closeConn=true
#\u6D4B\u8BD5\u5C5E\u6027\u6CE8\u5165
pagehelper.hello=\u4F60\u597D
pagehelper.nihao=Hello
pagehelper.offset-as-page-num=true
pagehelper.count-column=*
pagehelper.async-count=true
pagehelper.orderBySqlParser=tk.mybatis.pagehelper.MyOrderBySqlParser | repos\pagehelper-spring-boot-master\pagehelper-spring-boot-samples\pagehelper-spring-boot-sample-annotation\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public synchronized Object setProperty(String key, String value) {
propertiesConfiguration.setProperty(key, value);
return super.setProperty(key, value);
}
@Override
public String getProperty(String key) {
String val = propertiesConfiguration.getString(key);
super.setProperty(key, val);
return val;
}
@Override
public String getProperty(String key, String defaultValue) {
String val = propertiesConfiguration.getString(key, defaultValue); | super.setProperty(key, val);
return val;
}
@Override
public synchronized void load(Reader reader) throws IOException {
throw new PropertiesException(new OperationNotSupportedException());
}
@Override
public synchronized void load(InputStream inStream) throws IOException {
throw new PropertiesException(new OperationNotSupportedException());
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-properties-2\src\main\java\com\baeldung\properties\reloading\configs\ReloadableProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Duration getTimeInDefaultUnit() {
return timeInDefaultUnit;
}
public void setTimeInDefaultUnit(Duration timeInDefaultUnit) {
this.timeInDefaultUnit = timeInDefaultUnit;
}
public Duration getTimeInNano() {
return timeInNano;
}
public void setTimeInNano(Duration timeInNano) {
this.timeInNano = timeInNano;
}
public Duration getTimeInDays() {
return timeInDays;
}
public void setTimeInDays(Duration timeInDays) {
this.timeInDays = timeInDays;
}
public DataSize getSizeInDefaultUnit() {
return sizeInDefaultUnit;
}
public void setSizeInDefaultUnit(DataSize sizeInDefaultUnit) { | this.sizeInDefaultUnit = sizeInDefaultUnit;
}
public DataSize getSizeInGB() {
return sizeInGB;
}
public void setSizeInGB(DataSize sizeInGB) {
this.sizeInGB = sizeInGB;
}
public DataSize getSizeInTB() {
return sizeInTB;
}
public void setSizeInTB(DataSize sizeInTB) {
this.sizeInTB = sizeInTB;
}
public Employee getEmployee() {
return employee;
}
public void setEmployee(Employee employee) {
this.employee = employee;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-core\src\main\java\com\baeldung\configurationproperties\PropertyConversion.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setPassword(String passWord) {
super.setPassword(passWord);
passwordChanged = true;
}
@JsonIgnore
public boolean isEmailChanged() {
return emailChanged;
}
@JsonIgnore
public boolean isFirstNameChanged() {
return firstNameChanged;
} | @JsonIgnore
public boolean isLastNameChanged() {
return lastNameChanged;
}
@JsonIgnore
public boolean isDisplayNameChanged() {
return displayNameChanged;
}
@JsonIgnore
public boolean isPasswordChanged() {
return passwordChanged;
}
} | repos\flowable-engine-main\modules\flowable-idm-rest\src\main\java\org\flowable\idm\rest\service\api\user\UserRequest.java | 2 |
请完成以下Java代码 | public long findJobCountByQueryCriteria(TimerJobQueryImpl jobQuery) {
return (Long) getDbSqlSession().selectOne("selectTimerJobCountByQueryCriteria", jobQuery);
}
@Override
@SuppressWarnings("unchecked")
public List<TimerJobEntity> findTimerJobsToExecute(Page page) {
Date now = getClock().getCurrentTime();
return getDbSqlSession().selectList("selectTimerJobsToExecute", now, page);
}
@Override
public List<TimerJobEntity> findTimerStartEvents() {
return getDbSqlSession().selectList("selectTimerStartEvents");
}
@Override
@SuppressWarnings("unchecked")
public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionId(
String jobHandlerType,
String processDefinitionId
) {
Map<String, String> params = new HashMap<String, String>(2);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionId", processDefinitionId);
return getDbSqlSession().selectList("selectTimerJobByTypeAndProcessDefinitionId", params);
}
@Override
public List<TimerJobEntity> findJobsByExecutionId(final String executionId) {
return getList("selectTimerJobsByExecutionId", executionId, timerJobsByExecutionIdMatcher, true);
}
@Override
@SuppressWarnings("unchecked")
public List<TimerJobEntity> findJobsByProcessInstanceId(final String processInstanceId) { | return getDbSqlSession().selectList("selectTimerJobsByProcessInstanceId", processInstanceId);
}
@Override
@SuppressWarnings("unchecked")
public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionKeyNoTenantId(
String jobHandlerType,
String processDefinitionKey
) {
Map<String, String> params = new HashMap<String, String>(2);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
return getDbSqlSession().selectList("selectTimerJobByTypeAndProcessDefinitionKeyNoTenantId", params);
}
@Override
@SuppressWarnings("unchecked")
public List<TimerJobEntity> findJobsByTypeAndProcessDefinitionKeyAndTenantId(
String jobHandlerType,
String processDefinitionKey,
String tenantId
) {
Map<String, String> params = new HashMap<String, String>(3);
params.put("handlerType", jobHandlerType);
params.put("processDefinitionKey", processDefinitionKey);
params.put("tenantId", tenantId);
return getDbSqlSession().selectList("selectTimerJobByTypeAndProcessDefinitionKeyAndTenantId", params);
}
@Override
public void updateJobTenantIdForDeployment(String deploymentId, String newTenantId) {
HashMap<String, Object> params = new HashMap<String, Object>();
params.put("deploymentId", deploymentId);
params.put("tenantId", newTenantId);
getDbSqlSession().update("updateTimerJobTenantIdForDeployment", params);
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\data\impl\MybatisTimerJobDataManager.java | 1 |
请完成以下Java代码 | public void setApplicationContext(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
}
@Override
public void afterPropertiesSet() {
annotatedBeans = applicationContext.getBeansWithAnnotation(GrpcAdvice.class);
annotatedBeans.forEach(
(key, value) -> log.debug("Found gRPC advice: " + key + ", class: " + value.getClass().getName()));
annotatedMethods = findAnnotatedMethods();
}
private Set<Method> findAnnotatedMethods() {
return this.annotatedBeans.values().stream()
.map(Object::getClass)
.map(this::findAnnotatedMethods)
.flatMap(Collection::stream) | .collect(Collectors.toSet());
}
private Set<Method> findAnnotatedMethods(final Class<?> clazz) {
return MethodIntrospector.selectMethods(clazz, EXCEPTION_HANDLER_METHODS);
}
public Map<String, Object> getAnnotatedBeans() {
Assert.state(annotatedBeans != null, "@GrpcAdvice annotation scanning failed.");
return annotatedBeans;
}
public Set<Method> getAnnotatedMethods() {
Assert.state(annotatedMethods != null, "@GrpcExceptionHandler annotation scanning failed.");
return annotatedMethods;
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\advice\GrpcAdviceDiscoverer.java | 1 |
请完成以下Java代码 | public List<TbResource> findResourcesByTenantIdAndResourceType(TenantId tenantId, ResourceType resourceType,
ResourceSubType resourceSubType,
String[] objectIds,
String searchText) {
return objectIds == null ?
DaoUtil.convertDataList(resourceRepository.findResources(
tenantId.getId(),
TenantId.SYS_TENANT_ID.getId(),
resourceType.name(),
resourceSubType != null ? resourceSubType.name() : null,
searchText)) :
DaoUtil.convertDataList(resourceRepository.findResourcesByIds(
tenantId.getId(),
TenantId.SYS_TENANT_ID.getId(),
resourceType.name(), objectIds));
}
@Override
public byte[] getResourceData(TenantId tenantId, TbResourceId resourceId) {
return resourceRepository.getDataById(resourceId.getId());
}
@Override
public byte[] getResourcePreview(TenantId tenantId, TbResourceId resourceId) {
return resourceRepository.getPreviewById(resourceId.getId());
}
@Override
public long getResourceSize(TenantId tenantId, TbResourceId resourceId) {
return resourceRepository.getDataSizeById(resourceId.getId());
}
@Override
public TbResourceDataInfo getResourceDataInfo(TenantId tenantId, TbResourceId resourceId) {
return resourceRepository.getDataInfoById(resourceId.getId());
}
@Override
public Long sumDataSizeByTenantId(TenantId tenantId) {
return resourceRepository.sumDataSizeByTenantId(tenantId.getId());
}
@Override
public TbResource findByTenantIdAndExternalId(UUID tenantId, UUID externalId) {
return DaoUtil.getData(resourceRepository.findByTenantIdAndExternalId(tenantId, externalId)); | }
@Override
public PageData<TbResource> findByTenantId(UUID tenantId, PageLink pageLink) {
return findAllByTenantId(TenantId.fromUUID(tenantId), pageLink);
}
@Override
public PageData<TbResourceId> findIdsByTenantId(UUID tenantId, PageLink pageLink) {
return DaoUtil.pageToPageData(resourceRepository.findIdsByTenantId(tenantId, DaoUtil.toPageable(pageLink))
.map(TbResourceId::new));
}
@Override
public TbResourceId getExternalIdByInternal(TbResourceId internalId) {
return DaoUtil.toEntityId(resourceRepository.getExternalIdByInternal(internalId.getId()), TbResourceId::new);
}
@Override
public EntityType getEntityType() {
return EntityType.TB_RESOURCE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\resource\JpaTbResourceDao.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonBPartnerAttachment
{
@NonNull
@JsonProperty("FLAG")
Integer flag;
@NonNull
@JsonProperty("METASFRESHID")
String metasfreshId;
@NonNull
@JsonProperty("ANHANGDATEI")
String attachmentFilePath;
@Builder | public JsonBPartnerAttachment(
@JsonProperty("FLAG") final @NonNull Integer flag,
@JsonProperty("METASFRESHID") final @NonNull String metasfreshId,
@JsonProperty("ANHANGDATEI") final @NonNull String attachmentFilePath)
{
this.flag = flag;
this.metasfreshId = metasfreshId;
this.attachmentFilePath = attachmentFilePath;
}
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonPOJOBuilder(withPrefix = "")
public static class JsonBPartnerAttachmentBuilder
{
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\to_grs\api\model\JsonBPartnerAttachment.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setTransientVariablesLocal(Map<String, Object> transientVariables) {
throw new UnsupportedOperationException("Empty object, no variables can be set");
}
@Override
public void setTransientVariableLocal(String variableName, Object variableValue) {
throw new UnsupportedOperationException("Empty object, no variables can be set");
}
@Override
public void setTransientVariables(Map<String, Object> transientVariables) {
throw new UnsupportedOperationException("Empty object, no variables can be set");
}
@Override
public void setTransientVariable(String variableName, Object variableValue) {
throw new UnsupportedOperationException("Empty object, no variables can be set");
}
@Override
public Object getTransientVariableLocal(String variableName) {
return null;
}
@Override
public Map<String, Object> getTransientVariablesLocal() {
return null;
}
@Override
public Object getTransientVariable(String variableName) {
return null;
}
@Override
public Map<String, Object> getTransientVariables() {
return null;
} | @Override
public void removeTransientVariableLocal(String variableName) {
throw new UnsupportedOperationException("Empty object, no variables can be removed");
}
@Override
public void removeTransientVariablesLocal() {
throw new UnsupportedOperationException("Empty object, no variables can be removed");
}
@Override
public void removeTransientVariable(String variableName) {
throw new UnsupportedOperationException("Empty object, no variables can be removed");
}
@Override
public void removeTransientVariables() {
throw new UnsupportedOperationException("Empty object, no variables can be removed");
}
@Override
public String getTenantId() {
return null;
}
} | repos\flowable-engine-main\modules\flowable-variable-service-api\src\main\java\org\flowable\variable\api\delegate\EmptyVariableScope.java | 2 |
请完成以下Java代码 | private static void getObjectFromCache(Ignite ignite) {
IgniteCache<Integer, Employee> cache = ignite.getOrCreateCache("baeldungCache");
cache.put(1, new Employee(1, "John", true));
cache.put(2, new Employee(2, "Anna", false));
cache.put(3, new Employee(3, "George", true));
Employee employee = cache.get(1);
}
private static void getFromCacheWithSQl(Ignite ignite) {
IgniteCache<Integer, Employee> cache = ignite.cache("baeldungCache");
SqlFieldsQuery sql = new SqlFieldsQuery( | "select name from Employee where isEmployed = 'true'");
QueryCursor<List<?>> cursor = cache.query(sql);
for (List<?> row : cursor) {
System.out.println(row.get(0));
}
}
private static void customInitialization() {
IgniteConfiguration configuration = new IgniteConfiguration();
configuration.setLifecycleBeans(new CustomLifecycleBean());
Ignite ignite = Ignition.start(configuration);
}
} | repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\ignite\cache\IgniteCacheExample.java | 1 |
请完成以下Java代码 | public class Evaluator
{
float U, L, D, A;
int sentenceCount;
long start;
public Evaluator()
{
start = System.currentTimeMillis();
}
public void e(CoNLLSentence right, CoNLLSentence test)
{
++sentenceCount;
A += right.word.length;
for (int i = 0; i < test.word.length; ++i)
{
if (test.word[i].HEAD.ID == right.word[i].HEAD.ID)
{
++U;
if (right.word[i].DEPREL.equals(test.word[i].DEPREL))
{
++L;
if (test.word[i].HEAD.ID != 0)
{
++D;
}
}
}
}
}
public float getUA()
{
return U / A;
}
public float getLA()
{
return L / A;
}
public float getDA() | {
return D / (A - sentenceCount);
}
@Override
public String toString()
{
NumberFormat percentFormat = NumberFormat.getPercentInstance();
percentFormat.setMinimumFractionDigits(2);
StringBuilder sb = new StringBuilder();
sb.append("UA: ");
sb.append(percentFormat.format(getUA()));
sb.append('\t');
sb.append("LA: ");
sb.append(percentFormat.format(getLA()));
sb.append('\t');
sb.append("DA: ");
sb.append(percentFormat.format(getDA()));
sb.append('\t');
sb.append("sentences: ");
sb.append(sentenceCount);
sb.append('\t');
sb.append("speed: ");
sb.append(sentenceCount / (float)(System.currentTimeMillis() - start) * 1000);
sb.append(" sent/s");
return sb.toString();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dependency\CoNll\Evaluator.java | 1 |
请完成以下Java代码 | public CreateTaskVariablePayload handleCreateTaskVariablePayload(
CreateTaskVariablePayload createTaskVariablePayload
) {
checkNotValidCharactersInVariableName(createTaskVariablePayload.getName(), "Variable has not a valid name: ");
Object value = createTaskVariablePayload.getValue();
if (value instanceof String) {
handleAsDate((String) value).ifPresent(createTaskVariablePayload::setValue);
}
return createTaskVariablePayload;
}
public UpdateTaskVariablePayload handleUpdateTaskVariablePayload(
UpdateTaskVariablePayload updateTaskVariablePayload
) {
checkNotValidCharactersInVariableName(
updateTaskVariablePayload.getName(),
"You cannot update a variable with not a valid name: "
);
Object value = updateTaskVariablePayload.getValue();
if (value instanceof String) {
handleAsDate((String) value).ifPresent(updateTaskVariablePayload::setValue);
}
return updateTaskVariablePayload;
}
public Map<String, Object> handlePayloadVariables(Map<String, Object> variables) {
if (variables != null) {
Set<String> mismatchedVars = variableNameValidator.validateVariables(variables);
if (!mismatchedVars.isEmpty()) { | throw new IllegalStateException("Variables have not valid names: " + String.join(", ", mismatchedVars));
}
handleStringVariablesAsDates(variables);
}
return variables;
}
private void handleStringVariablesAsDates(Map<String, Object> variables) {
if (variables != null) {
variables
.entrySet()
.stream()
.filter(stringObjectEntry -> stringObjectEntry.getValue() instanceof String)
.forEach(stringObjectEntry ->
handleAsDate((String) stringObjectEntry.getValue()).ifPresent(stringObjectEntry::setValue)
);
}
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskVariablesPayloadValidator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ModelAndView redirectWithUsingXMLConfig(final ModelMap model) {
model.addAttribute("attribute", "redirectWithXMLConfig");
return new ModelAndView("RedirectedUrl", model);
}
@RequestMapping(value = "/redirectWithRedirectPrefix", method = RequestMethod.GET)
public ModelAndView redirectWithUsingRedirectPrefix(final ModelMap model) {
model.addAttribute("attribute", "redirectWithRedirectPrefix");
return new ModelAndView("redirect:/redirectedUrl", model);
}
@RequestMapping(value = "/redirectWithRedirectAttributes", method = RequestMethod.GET)
public RedirectView redirectWithRedirectAttributes(final RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute("flashAttribute", "redirectWithRedirectAttributes");
redirectAttributes.addAttribute("attribute", "redirectWithRedirectAttributes");
return new RedirectView("redirectedUrl");
}
@RequestMapping(value = "/redirectWithRedirectView", method = RequestMethod.GET)
public RedirectView redirectWithUsingRedirectView(final ModelMap model) {
model.addAttribute("attribute", "redirectWithRedirectView");
return new RedirectView("redirectedUrl");
}
@RequestMapping(value = "/forwardWithForwardPrefix", method = RequestMethod.GET)
public ModelAndView forwardWithUsingForwardPrefix(final ModelMap model) {
model.addAttribute("attribute", "redirectWithForwardPrefix");
return new ModelAndView("forward:/redirectedUrl", model); | }
@RequestMapping(value = "/redirectedUrl", method = RequestMethod.GET)
public ModelAndView redirection(final ModelMap model, @ModelAttribute("flashAttribute") final Object flashAttribute) {
model.addAttribute("redirectionAttribute", flashAttribute);
return new ModelAndView("redirection", model);
}
@RequestMapping(value = "/redirectPostToPost", method = RequestMethod.POST)
public ModelAndView redirectPostToPost(HttpServletRequest request) {
request.setAttribute(View.RESPONSE_STATUS_ATTRIBUTE, HttpStatus.TEMPORARY_REDIRECT);
return new ModelAndView("redirect:/redirectedPostToPost");
}
@RequestMapping(value = "/redirectedPostToPost", method = RequestMethod.POST)
public ModelAndView redirectedPostToPost() {
return new ModelAndView("redirection");
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-runtime\src\main\java\com\baeldung\sampleapp\web\controller\redirect\RedirectController.java | 2 |
请完成以下Java代码 | public final class CRFSegmentModel extends CRFModel
{
private int idM;
private int idE;
private int idS;
/**
* 不允许构造空白实例
*/
private CRFSegmentModel()
{
}
/**
* 以指定的trie树结构储存内部特征函数
*
* @param featureFunctionTrie
*/
public CRFSegmentModel(ITrie<FeatureFunction> featureFunctionTrie)
{
super(featureFunctionTrie);
}
/**
* 初始化几个常量
*/
private void initTagSet()
{
idM = this.getTagId("M");
idE = this.getTagId("E");
idS = this.getTagId("S");
}
@Override
public boolean load(ByteArray byteArray)
{
boolean result = super.load(byteArray);
if (result)
{
initTagSet();
}
return result;
}
@Override
protected void onLoadTxtFinished()
{
super.onLoadTxtFinished();
initTagSet();
}
@Override
public void tag(Table table)
{
int size = table.size();
if (size == 1)
{
table.setLast(0, "S");
return;
}
double[][] net = new double[size][4];
for (int i = 0; i < size; ++i)
{
LinkedList<double[]> scoreList = computeScoreList(table, i);
for (int tag = 0; tag < 4; ++tag)
{
net[i][tag] = computeScore(scoreList, tag);
}
}
net[0][idM] = -1000.0; // 第一个字不可能是M或E
net[0][idE] = -1000.0;
int[][] from = new int[size][4]; | double[][] maxScoreAt = new double[2][4]; // 滚动数组
System.arraycopy(net[0], 0, maxScoreAt[0], 0, 4); // 初始preI=0, maxScoreAt[preI][pre] = net[0][pre]
int curI = 0;
for (int i = 1; i < size; ++i)
{
curI = i & 1;
int preI = 1 - curI;
for (int now = 0; now < 4; ++now)
{
double maxScore = -1e10;
for (int pre = 0; pre < 4; ++pre)
{
double score = maxScoreAt[preI][pre] + matrix[pre][now] + net[i][now];
if (score > maxScore)
{
maxScore = score;
from[i][now] = pre;
maxScoreAt[curI][now] = maxScore;
}
}
net[i][now] = maxScore;
}
}
// 反向回溯最佳路径
int maxTag = maxScoreAt[curI][idS] > maxScoreAt[curI][idE] ? idS : idE;
table.setLast(size - 1, id2tag[maxTag]);
maxTag = from[size - 1][maxTag];
for (int i = size - 2; i > 0; --i)
{
table.setLast(i, id2tag[maxTag]);
maxTag = from[i][maxTag];
}
table.setLast(0, id2tag[maxTag]);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\CRFSegmentModel.java | 1 |
请完成以下Java代码 | public boolean isQuarantineLotNumber(@NonNull final AbstractHUAttributeStorage huAttributeStorage)
{
final String lotNumber = huAttributeStorage.getValueAsString(AttributeConstants.ATTR_LotNumber);
final List<IHUProductStorage> productStorages = handlingUnitsBL
.getStorageFactory()
.getStorage(huAttributeStorage.getM_HU())
.getProductStorages();
for (final IHUProductStorage productStorage : productStorages)
{
final ProductId productId = productStorage.getProductId();
final LotNumberQuarantine lotNumberQuarantine = lotNumberQuarantineRepository.getByProductIdAndLot(productId, lotNumber);
if (lotNumberQuarantine != null)
{
return true;
}
}
return false;
}
public boolean isQuarantineHU(final I_M_HU huRecord)
{
// retrieve the attribute
final AttributeId quarantineAttributeId = attributeDAO.getAttributeIdByCode(HUAttributeConstants.ATTR_Quarantine);
final I_M_HU_Attribute huAttribute = huAttributesDAO.retrieveAttribute(huRecord, quarantineAttributeId);
if (huAttribute == null)
{
return false;
}
return HUAttributeConstants.ATTR_Quarantine_Value_Quarantine.equals(huAttribute.getValue());
}
public void markHUAsQuarantine(final I_M_HU huRecord) | {
// retrieve the attribute
final AttributeId quarantineAttributeId = attributeDAO.getAttributeIdByCode(HUAttributeConstants.ATTR_Quarantine);
final I_M_HU_Attribute huAttribute = huAttributesDAO.retrieveAttribute(huRecord, quarantineAttributeId);
if (huAttribute == null)
{
// nothing to do. The HU doesn't have the attribute
return;
}
huAttribute.setValue(HUAttributeConstants.ATTR_Quarantine_Value_Quarantine);
save(huAttribute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\quarantine\HULotNumberQuarantineService.java | 1 |
请完成以下Java代码 | public void setC_Workplace_ID (final int C_Workplace_ID)
{
if (C_Workplace_ID < 1)
set_Value (COLUMNNAME_C_Workplace_ID, null);
else
set_Value (COLUMNNAME_C_Workplace_ID, C_Workplace_ID);
}
@Override
public int getC_Workplace_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_ID);
}
@Override
public void setC_Workplace_Product_ID (final int C_Workplace_Product_ID)
{
if (C_Workplace_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Workplace_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Workplace_Product_ID, C_Workplace_Product_ID);
}
@Override
public int getC_Workplace_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Workplace_Product_ID); | }
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Workplace_Product.java | 1 |
请完成以下Java代码 | public void setName(String name) {
this.name = name;
}
public String getCoverPic() {
return coverPic;
}
public void setCoverPic(String coverPic) {
this.coverPic = coverPic;
}
public Integer getPicCount() {
return picCount;
}
public void setPicCount(Integer picCount) {
this.picCount = picCount;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
} | public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", coverPic=").append(coverPic);
sb.append(", picCount=").append(picCount);
sb.append(", sort=").append(sort);
sb.append(", description=").append(description);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsAlbum.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DefaultGlobalSecuritySchemeOpenApiController {
@RequestMapping(method = RequestMethod.POST, value = "/login", produces = { "application/json" }, consumes = { "application/json" })
@Operation(operationId = "login", responses = {
@ApiResponse(responseCode = "200", description = "api_key to be used in the secured-ping entry point", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = TokenDto.class)) }),
@ApiResponse(responseCode = "401", description = "Unauthorized request", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ApplicationExceptionDto.class)) }) })
@SecurityRequirements()
public ResponseEntity<TokenDto> login(@Parameter(name = "LoginDto", description = "Login") @Valid @RequestBody(required = true) LoginDto loginDto) {
TokenDto token = new TokenDto();
token.setRaw("Generated Token");
return ResponseEntity.ok(token);
}
@Operation(operationId = "ping", responses = {
@ApiResponse(responseCode = "200", description = "Ping that needs an api_key attribute in the header", content = {
@Content(mediaType = "application/json", schema = @Schema(implementation = PingResponseDto.class), examples = { @ExampleObject(value = "{ pong: '2022-06-17T18:30:33.465+02:00' }") }) }),
@ApiResponse(responseCode = "401", description = "Unauthorized request", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ApplicationExceptionDto.class)) }), | @ApiResponse(responseCode = "403", description = "Forbidden request", content = { @Content(mediaType = "application/json", schema = @Schema(implementation = ApplicationExceptionDto.class)) }) })
@RequestMapping(method = RequestMethod.GET, value = "/ping", produces = { "application/json" })
public ResponseEntity<PingResponseDto> ping(@RequestHeader(name = "api_key", required = false) String api_key) {
int year = 2000;
int month = 1;
int dayOfMonth = 1;
int hour = 0;
int minute = 0;
int second = 0;
int nanoSeccond = 0;
ZoneOffset offset = ZoneOffset.UTC;
PingResponseDto response = new PingResponseDto();
response.setPong(OffsetDateTime.of(year, month, dayOfMonth, hour, minute, second, nanoSeccond, offset));
return ResponseEntity.ok(response);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-springdoc-2\src\main\java\com\baeldung\defaultglobalsecurityscheme\controller\DefaultGlobalSecuritySchemeOpenApiController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void setCreatedDate(Instant createdDate) {
this.createdDate = createdDate;
}
public String getLastModifiedBy() {
return lastModifiedBy;
}
public void setLastModifiedBy(String lastModifiedBy) {
this.lastModifiedBy = lastModifiedBy;
}
public Instant getLastModifiedDate() {
return lastModifiedDate;
}
public void setLastModifiedDate(Instant lastModifiedDate) {
this.lastModifiedDate = lastModifiedDate;
}
public Set<String> getAuthorities() {
return authorities;
}
public void setAuthorities(Set<String> authorities) {
this.authorities = authorities;
} | @Override
public String toString() {
return "UserDTO{" +
"login='" + login + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", email='" + email + '\'' +
", imageUrl='" + imageUrl + '\'' +
", activated=" + activated +
", langKey='" + langKey + '\'' +
", createdBy=" + createdBy +
", createdDate=" + createdDate +
", lastModifiedBy='" + lastModifiedBy + '\'' +
", lastModifiedDate=" + lastModifiedDate +
", authorities=" + authorities +
"}";
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\UserDTO.java | 2 |
请完成以下Java代码 | public class OAuth2AuthorizationException extends RuntimeException {
@Serial
private static final long serialVersionUID = -5470222190376181102L;
private final OAuth2Error error;
/**
* Constructs an {@code OAuth2AuthorizationException} using the provided parameters.
* @param error the {@link OAuth2Error OAuth 2.0 Error}
*/
public OAuth2AuthorizationException(OAuth2Error error) {
this(error, error.toString());
}
/**
* Constructs an {@code OAuth2AuthorizationException} using the provided parameters.
* @param error the {@link OAuth2Error OAuth 2.0 Error}
* @param message the exception message
* @since 5.3
*/
public OAuth2AuthorizationException(OAuth2Error error, String message) {
super(message);
Assert.notNull(error, "error must not be null");
this.error = error;
}
/**
* Constructs an {@code OAuth2AuthorizationException} using the provided parameters.
* @param error the {@link OAuth2Error OAuth 2.0 Error} | * @param cause the root cause
*/
public OAuth2AuthorizationException(OAuth2Error error, Throwable cause) {
this(error, error.toString(), cause);
}
/**
* Constructs an {@code OAuth2AuthorizationException} using the provided parameters.
* @param error the {@link OAuth2Error OAuth 2.0 Error}
* @param message the exception message
* @param cause the root cause
* @since 5.3
*/
public OAuth2AuthorizationException(OAuth2Error error, String message, Throwable cause) {
super(message, cause);
Assert.notNull(error, "error must not be null");
this.error = error;
}
/**
* Returns the {@link OAuth2Error OAuth 2.0 Error}.
* @return the {@link OAuth2Error}
*/
public OAuth2Error getError() {
return this.error;
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\OAuth2AuthorizationException.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class GameController implements Publisher<Payload> {
private static final Logger LOG = LoggerFactory.getLogger(GameController.class);
private final String playerName;
private final List<Long> shots;
private Subscriber<? super Payload> subscriber;
private boolean truce = false;
public GameController(String playerName) {
this.playerName = playerName;
this.shots = generateShotList();
}
/**
* Create a random list of time intervals, 0-1000ms
*
* @return List of time intervals
*/
private List<Long> generateShotList() {
return Flux.range(1, SHOT_COUNT)
.map(x -> (long) Math.ceil(Math.random() * 1000))
.collectList()
.block();
}
@Override
public void subscribe(Subscriber<? super Payload> subscriber) {
this.subscriber = subscriber;
fireAtWill();
}
/**
* Publish game events asynchronously
*/
private void fireAtWill() {
new Thread(() -> {
for (Long shotDelay : shots) {
try { Thread.sleep(shotDelay); } catch (Exception x) {} | if (truce) {
break;
}
LOG.info("{}: bang!", playerName);
subscriber.onNext(DefaultPayload.create("bang!"));
}
if (!truce) {
LOG.info("{}: I give up!", playerName);
subscriber.onNext(DefaultPayload.create("I give up"));
}
subscriber.onComplete();
}).start();
}
/**
* Process events from the opponent
*
* @param payload Payload received from the rSocket
*/
public void processPayload(Payload payload) {
String message = payload.getDataUtf8();
switch (message) {
case "bang!":
String result = Math.random() < 0.5 ? "Haha missed!" : "Ow!";
LOG.info("{}: {}", playerName, result);
break;
case "I give up":
truce = true;
LOG.info("{}: OK, truce", playerName);
break;
}
}
} | repos\tutorials-master\spring-reactive-modules\rsocket\src\main\java\com\baeldung\rsocket\support\GameController.java | 2 |
请完成以下Java代码 | public void processFile(Message<File> message) throws IOException {
securityUtil.logInAs("system");
File payload = message.getPayload();
logger.info(">>> Processing file: " + payload.getName());
String content = FileUtils.readFileToString(payload, "UTF-8");
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yy HH:mm:ss");
logger.info("> Processing content: " + content + " at " + formatter.format(new Date()));
ProcessInstance processInstance = processRuntime.start(
ProcessPayloadBuilder.start()
.withProcessDefinitionKey("categorizeProcess")
.withName("Processing Content: " + content)
.withVariable("content", content)
.build()
);
logger.info(">>> Created Process Instance: " + processInstance);
logger.info(">>> Deleting processed file: " + payload.getName());
payload.delete();
}
@Bean
public Connector processTextConnector() {
return integrationContext -> {
Map<String, Object> inBoundVariables = integrationContext.getInBoundVariables();
String contentToProcess = (String) inBoundVariables.get("content");
// Logic Here to decide if content is approved or not
if (contentToProcess.contains("activiti")) {
logger.info("> Approving content: " + contentToProcess); | integrationContext.addOutBoundVariable("approved", true);
} else {
logger.info("> Discarding content: " + contentToProcess);
integrationContext.addOutBoundVariable("approved", false);
}
return integrationContext;
};
}
@Bean
public Connector tagTextConnector() {
return integrationContext -> {
String contentToTag = (String) integrationContext.getInBoundVariables().get("content");
contentToTag += " :) ";
integrationContext.addOutBoundVariable("content", contentToTag);
logger.info("Final Content: " + contentToTag);
return integrationContext;
};
}
@Bean
public Connector discardTextConnector() {
return integrationContext -> {
String contentToDiscard = (String) integrationContext.getInBoundVariables().get("content");
contentToDiscard += " :( ";
integrationContext.addOutBoundVariable("content", contentToDiscard);
logger.info("Final Content: " + contentToDiscard);
return integrationContext;
};
}
} | repos\Activiti-develop\activiti-examples\activiti-api-spring-integration-example\src\main\java\org\activiti\examples\DemoApplication.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<PropagationType> getProduce() {
return this.produce;
}
public List<PropagationType> getConsume() {
return this.consume;
}
/**
* Supported propagation types. The declared order of the values matter.
*/
public enum PropagationType {
/**
* <a href="https://www.w3.org/TR/trace-context/">W3C</a> propagation.
*/
W3C,
/** | * <a href="https://github.com/openzipkin/b3-propagation#single-header">B3
* single header</a> propagation.
*/
B3,
/**
* <a href="https://github.com/openzipkin/b3-propagation#multiple-headers">B3
* multiple headers</a> propagation.
*/
B3_MULTI
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-tracing\src\main\java\org\springframework\boot\micrometer\tracing\autoconfigure\TracingProperties.java | 2 |
请完成以下Java代码 | public final AbstractProducerDestination setM_HU_LUTU_Configuration(final I_M_HU_LUTU_Configuration lutuConfiguration)
{
assertConfigurable();
_lutuConfiguration = lutuConfiguration;
return this;
}
public final I_M_HU_LUTU_Configuration getM_HU_LUTU_Configuration()
{
return _lutuConfiguration;
}
@Override
public final IHUProducerAllocationDestination setIsHUPlanningReceiptOwnerPM(boolean isHUPlanningReceiptOwnerPM)
{
this._isHUPlanningReceiptOwnerPM = isHUPlanningReceiptOwnerPM;
return this;
}
public final boolean isHUPlanningReceiptOwnerPM()
{
return _isHUPlanningReceiptOwnerPM;
}
/**
* Sets this producer in "non-configurable" state. No further configuration to this producer will be allowed after calling this method.
*/
protected final void setNotConfigurable()
{
_configurable = false;
}
/**
* Makes sure producer is in configurable state. If not, and exception will be thrown.
*/
protected final void assertConfigurable()
{
if (!_configurable)
{
throw new HUException("This producer is not configurable anymore: " + this);
}
}
@Override
public final IHUProducerAllocationDestination setHUClearanceStatusInfo(final ClearanceStatusInfo huClearanceStatusInfo)
{
assertConfigurable();
_huClearanceStatusInfo = huClearanceStatusInfo;
return this;
}
public final ClearanceStatusInfo getHUClearanceStatusInfo()
{
return _huClearanceStatusInfo;
}
private void destroyCurrentHU(final HUListCursor currentHUCursor, final IHUContext huContext)
{
final I_M_HU hu = currentHUCursor.current();
if (hu == null) | {
return; // shall not happen
}
currentHUCursor.closeCurrent(); // close the current position of this cursor
// since _createdNonAggregateHUs is just a subset of _createdHUs, we don't know if 'hu' was in there to start with. All we care is that it's not in _createdNonAggregateHUs after this method.
_createdNonAggregateHUs.remove(hu);
final boolean removedFromCreatedHUs = _createdHUs.remove(hu);
Check.assume(removedFromCreatedHUs, "Cannot destroy {} because it wasn't created by us", hu);
// Delete only those HUs which were internally created by THIS producer
if (DYNATTR_Producer.getValue(hu) == this)
{
final Supplier<IAutoCloseable> getDontDestroyParentLUClosable = () -> {
final I_M_HU lu = handlingUnitsBL.getLoadingUnitHU(hu);
return lu != null
? huContext.temporarilyDontDestroyHU(HuId.ofRepoId(lu.getM_HU_ID()))
: () -> {
};
};
try (final IAutoCloseable ignored = getDontDestroyParentLUClosable.get())
{
handlingUnitsBL.destroyIfEmptyStorage(huContext, hu);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AbstractProducerDestination.java | 1 |
请完成以下Java代码 | public String getOnPartId() {
return onPartId;
}
@Override
public void setOnPartId(String onPartId) {
this.onPartId = onPartId;
}
@Override
public String getIfPartId() {
return ifPartId;
}
@Override | public void setIfPartId(String ifPartId) {
this.ifPartId = ifPartId;
}
@Override
public Date getTimeStamp() {
return timeStamp;
}
@Override
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\SentryPartInstanceEntityImpl.java | 1 |
请完成以下Java代码 | private File concatenateFiles(final I_C_Queue_WorkPackage workpackage) throws IOException, DocumentException
{
final File file = createNewTemporaryPDFFile(workpackage);
final Document document = new Document();
final FileOutputStream fos = new FileOutputStream(file, false);
try
{
final PdfCopy copy = new PdfCopy(document, fos);
document.open();
final List<I_C_Printing_Queue> pqs = queueDAO.retrieveAllItems(workpackage, I_C_Printing_Queue.class);
for (final I_C_Printing_Queue pq : pqs)
{
try (final MDC.MDCCloseable ignored = TableRecordMDC.putTableRecordReference(pq))
{
if (pq.isProcessed())
{
Loggables.withLogger(logger, Level.DEBUG).addLog("*** Printing queue is already processed. Skipping it: {}", pq);
continue;
}
final PdfReader reader = getPdfReader(pq);
appendToPdf(copy, reader);
copy.freeReader(reader);
reader.close();
printingQueueBL.setProcessedAndSave(pq);
}
}
}
finally
{
document.close();
fos.close();
return file;
}
}
@NonNull
private File createNewTemporaryPDFFile(final I_C_Queue_WorkPackage workpackage)
{
final I_C_Async_Batch asyncBatch = workpackage.getC_Async_Batch();
Check.assumeNotNull(asyncBatch, "Async batch is not null");
final String fileName = "PDF_" + asyncBatch.getC_Async_Batch_ID();
try
{
return File.createTempFile(fileName, ".pdf");
}
catch (Exception ex)
{
throw new AdempiereException("Failed to create temporary file with prefix: " + fileName, ex);
}
}
@NonNull
private PdfReader getPdfReader(final I_C_Printing_Queue pq) | {
final I_AD_Archive archive = pq.getAD_Archive();
Check.assumeNotNull(archive, "Archive references an AD_Archive record");
final byte[] data = archiveBL.getBinaryData(archive);
try
{
return new PdfReader(data);
}
catch (IOException e)
{
throw new AdempiereException("Failed to create PDF reader from archive=" + archive + ", printing queue=" + pq, e);
}
}
private void appendToPdf(final PdfCopy pdf, final PdfReader from)
{
try
{
for (int page = 0; page < from.getNumberOfPages(); )
{
pdf.addPage(pdf.getImportedPage(from, ++page));
}
}
catch (IOException | BadPdfFormatException e)
{
throw new AdempiereException("Failed appending to pdf=" + pdf + " from " + from, e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\async\spi\impl\PrintingQueuePDFConcatenateWorkpackageProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Class<?> getObjectType() {
return AuthorizationManagerWebInvocationPrivilegeEvaluator.HttpServletRequestTransformer.class;
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
}
static class RoleVoterBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory {
private RoleVoter voter = new RoleVoter();
@Override
public RoleVoter getBean() {
this.voter.setRolePrefix(this.rolePrefix);
return this.voter;
}
}
static class SecurityContextHolderAwareRequestFilterBeanFactory
extends GrantedAuthorityDefaultsParserUtils.AbstractGrantedAuthorityDefaultsBeanFactory {
private SecurityContextHolderAwareRequestFilter filter = new SecurityContextHolderAwareRequestFilter();
private SecurityContextHolderStrategy securityContextHolderStrategy = SecurityContextHolder
.getContextHolderStrategy();
@Override
public SecurityContextHolderAwareRequestFilter getBean() {
this.filter.setSecurityContextHolderStrategy(this.securityContextHolderStrategy);
this.filter.setRolePrefix(this.rolePrefix);
return this.filter;
}
void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
}
static class SecurityContextHolderStrategyFactory implements FactoryBean<SecurityContextHolderStrategy> {
@Override
public SecurityContextHolderStrategy getObject() throws Exception { | return SecurityContextHolder.getContextHolderStrategy();
}
@Override
public Class<?> getObjectType() {
return SecurityContextHolderStrategy.class;
}
}
static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> {
@Override
public ObservationRegistry getObject() throws Exception {
return ObservationRegistry.NOOP;
}
@Override
public Class<?> getObjectType() {
return ObservationRegistry.class;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\HttpConfigurationBuilder.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public DocumentReferenceType getStockEntryReference() {
return stockEntryReference;
}
/**
* Sets the value of the stockEntryReference property.
*
* @param value
* allowed object is
* {@link DocumentReferenceType }
*
*/
public void setStockEntryReference(DocumentReferenceType value) {
this.stockEntryReference = value;
}
/**
* Gets the value of the additionalReferences property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the additionalReferences property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getAdditionalReferences().add(newItem);
* </pre>
* | *
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DocumentReferenceType }
*
*
*/
public List<DocumentReferenceType> getAdditionalReferences() {
if (additionalReferences == null) {
additionalReferences = new ArrayList<DocumentReferenceType>();
}
return this.additionalReferences;
}
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\INVRPTListLineItemExtensionType.java | 2 |
请完成以下Java代码 | public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
return email;
} | public void setEmail(String email) {
this.email = email;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
} | repos\springBoot-master\springboot-dynamicDataSource\src\main\java\cn\abel\bean\User.java | 1 |
请完成以下Java代码 | public boolean hasMoreElements()
{
if( place < elements.length && current != place )
return true;
return false;
}
public void setSize(int size)
{
this.size = size;
}
public int getCurrentSize()
{
return current;
}
public void rehash()
{
tmpElements = new Object[size];
int count = 0;
for ( int x = 0; x < elements.length; x++ )
{
if( elements[x] != null )
{
tmpElements[count] = elements[x];
count++;
}
}
elements = (Object[])tmpElements.clone();
tmpElements = null;
current = count;
}
public void setGrow(int grow)
{
this.grow = grow;
}
public void grow()
{
size = size+=(size/grow);
rehash();
}
public void add(Object o)
{
if( current == elements.length )
grow();
try
{ | elements[current] = o;
current++;
}
catch(java.lang.ArrayStoreException ase)
{
}
}
public void add(int location,Object o)
{
try
{
elements[location] = o;
}
catch(java.lang.ArrayStoreException ase)
{
}
}
public void remove(int location)
{
elements[location] = null;
}
public int location(Object o) throws NoSuchObjectException
{
int loc = -1;
for ( int x = 0; x < elements.length; x++ )
{
if((elements[x] != null && elements[x] == o )||
(elements[x] != null && elements[x].equals(o)))
{
loc = x;
break;
}
}
if( loc == -1 )
throw new NoSuchObjectException();
return(loc);
}
public Object get(int location)
{
return elements[location];
}
public java.util.Enumeration elements()
{
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\storage\Array.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getAdditionalCostType() {
return additionalCostType;
}
/**
* Sets the value of the additionalCostType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAdditionalCostType(String value) {
this.additionalCostType = value;
}
/**
* Gets the value of the additionalCostAmount property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getAdditionalCostAmount() {
return additionalCostAmount;
}
/**
* Sets the value of the additionalCostAmount property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setAdditionalCostAmount(BigDecimal value) {
this.additionalCostAmount = value;
}
/**
* Gets the value of the vatRate property. | *
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getVATRate() {
return vatRate;
}
/**
* Sets the value of the vatRate property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setVATRate(BigDecimal value) {
this.vatRate = value;
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\AdditionalCostsType.java | 2 |
请完成以下Java代码 | public Integer getUsePointLimitOld() {
return usePointLimitOld;
}
public void setUsePointLimitOld(Integer usePointLimitOld) {
this.usePointLimitOld = usePointLimitOld;
}
public Integer getUsePointLimitNew() {
return usePointLimitNew;
}
public void setUsePointLimitNew(Integer usePointLimitNew) {
this.usePointLimitNew = usePointLimitNew;
}
public String getOperateMan() {
return operateMan;
}
public void setOperateMan(String operateMan) {
this.operateMan = operateMan;
}
public Date getCreateTime() {
return createTime;
} | public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", productId=").append(productId);
sb.append(", priceOld=").append(priceOld);
sb.append(", priceNew=").append(priceNew);
sb.append(", salePriceOld=").append(salePriceOld);
sb.append(", salePriceNew=").append(salePriceNew);
sb.append(", giftPointOld=").append(giftPointOld);
sb.append(", giftPointNew=").append(giftPointNew);
sb.append(", usePointLimitOld=").append(usePointLimitOld);
sb.append(", usePointLimitNew=").append(usePointLimitNew);
sb.append(", operateMan=").append(operateMan);
sb.append(", createTime=").append(createTime);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductOperateLog.java | 1 |
请完成以下Java代码 | private String buildTitle()
{
return Env.getHeader(getCtx(), _parentWindowNo);
}
private String buildMessage()
{
final StringBuilder out = new StringBuilder();
final String adMessageTrl = getAD_Message_Translated();
if (!Check.isEmpty(adMessageTrl))
{
out.append(adMessageTrl);
}
final String additionalMessage = getAdditionalMessage();
if (!Check.isEmpty(additionalMessage))
{
out.append("\n").append(additionalMessage);
}
return out.toString();
}
private Properties getCtx()
{
return Env.getCtx();
}
@Override
public IAskDialogBuilder setParentComponent(final Object parentCompObj)
{
this._parentCompObj = parentCompObj;
return this;
}
@Override
public IAskDialogBuilder setParentWindowNo(final int windowNo)
{
this._parentWindowNo = windowNo;
return this;
}
private Window getParentWindowOrNull()
{
Window parent = null;
if (_parentCompObj instanceof Component)
{
parent = SwingUtils.getParentWindow((Component)_parentCompObj);
}
if (parent == null && Env.isRegularOrMainWindowNo(_parentWindowNo))
{
parent = Env.getWindow(_parentWindowNo);
} | return parent;
}
@Override
public IAskDialogBuilder setAD_Message(final String adMessage, Object ... params)
{
this._adMessage = adMessage;
this._adMessageParams = params;
return this;
}
private String getAD_Message_Translated()
{
if (Check.isEmpty(_adMessage, true))
{
return "";
}
final Properties ctx = getCtx();
if (Check.isEmpty(_adMessageParams))
{
return msgBL.getMsg(ctx, _adMessage);
}
else
{
return msgBL.getMsg(ctx, _adMessage, _adMessageParams);
}
}
@Override
public IAskDialogBuilder setAdditionalMessage(final String additionalMessage)
{
this._additionalMessage = additionalMessage;
return this;
}
private String getAdditionalMessage()
{
return this._additionalMessage;
}
@Override
public IAskDialogBuilder setDefaultAnswer(final boolean defaultAnswer)
{
this._defaultAnswer = defaultAnswer;
return this;
}
private boolean getDefaultAnswer()
{
return this._defaultAnswer;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\adempiere\form\swing\SwingAskDialogBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static class KPIDataCacheValue
{
public static KPIDataCacheValue ok(@NonNull final KPIDataResult data, @NonNull final Duration defaultMaxStaleAccepted)
{
return new KPIDataCacheValue(data, defaultMaxStaleAccepted);
}
@NonNull Instant created = SystemTime.asInstant();
@NonNull Duration defaultMaxStaleAccepted;
KPIDataResult data;
public KPIDataCacheValue(@NonNull final KPIDataResult data, @NonNull final Duration defaultMaxStaleAccepted)
{
this.data = data;
this.defaultMaxStaleAccepted = defaultMaxStaleAccepted;
}
public boolean isExpired()
{
return isExpired(null); | }
public boolean isExpired(@Nullable final Duration maxStaleAccepted)
{
final Duration maxStaleAcceptedEffective = maxStaleAccepted != null
? maxStaleAccepted
: defaultMaxStaleAccepted;
final Instant now = SystemTime.asInstant();
final Duration staleActual = Duration.between(created, now);
final boolean expired = staleActual.compareTo(maxStaleAcceptedEffective) > 0;
logger.trace("isExpired={}, now={}, maxStaleAcceptedEffective={}, staleActual={}, cacheValue={}", expired, now, maxStaleAcceptedEffective, staleActual, this);
return expired;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataProvider.java | 2 |
请完成以下Java代码 | public Profile getAuthor(DataFetchingEnvironment dataFetchingEnvironment) {
Map<String, ArticleData> map = dataFetchingEnvironment.getLocalContext();
Article article = dataFetchingEnvironment.getSource();
return queryProfile(map.get(article.getSlug()).getProfileData().getUsername());
}
@DgsData(parentType = COMMENT.TYPE_NAME, field = COMMENT.Author)
public Profile getCommentAuthor(DataFetchingEnvironment dataFetchingEnvironment) {
Comment comment = dataFetchingEnvironment.getSource();
Map<String, CommentData> map = dataFetchingEnvironment.getLocalContext();
return queryProfile(map.get(comment.getId()).getProfileData().getUsername());
}
@DgsData(parentType = DgsConstants.QUERY_TYPE, field = QUERY.Profile)
public ProfilePayload queryProfile(
@InputArgument("username") String username, DataFetchingEnvironment dataFetchingEnvironment) {
Profile profile = queryProfile(dataFetchingEnvironment.getArgument("username"));
return ProfilePayload.newBuilder().profile(profile).build(); | }
private Profile queryProfile(String username) {
User current = SecurityUtil.getCurrentUser().orElse(null);
ProfileData profileData =
profileQueryService
.findByUsername(username, current)
.orElseThrow(ResourceNotFoundException::new);
return Profile.newBuilder()
.username(profileData.getUsername())
.bio(profileData.getBio())
.image(profileData.getImage())
.following(profileData.isFollowing())
.build();
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\graphql\ProfileDatafetcher.java | 1 |
请完成以下Java代码 | public class Response {
private String fileName;
private String fileDownloadUri;
private String fileType;
private long size;
public Response(String fileName, String fileDownloadUri, String fileType, long size) {
this.fileName = fileName;
this.fileDownloadUri = fileDownloadUri;
this.fileType = fileType;
this.size = size;
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public String getFileDownloadUri() {
return fileDownloadUri; | }
public void setFileDownloadUri(String fileDownloadUri) {
this.fileDownloadUri = fileDownloadUri;
}
public String getFileType() {
return fileType;
}
public void setFileType(String fileType) {
this.fileType = fileType;
}
public long getSize() {
return size;
}
public void setSize(long size) {
this.size = size;
}
} | repos\Spring-Boot-Advanced-Projects-main\springboot-upload-download-file-database\src\main\java\net\alanbinu\springboot\fileuploaddownload\payload\Response.java | 1 |
请完成以下Java代码 | public void setAD_OrgTrx_ID(int AD_OrgTrx_ID)
{
if (AD_OrgTrx_ID == 0)
set_Value(COLUMNNAME_AD_OrgTrx_ID, null);
else
set_Value(COLUMNNAME_AD_OrgTrx_ID, new Integer(AD_OrgTrx_ID));
}
/**
* Get Trx Organization. Performing or initiating organization
*/
public int getAD_OrgTrx_ID()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_OrgTrx_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
protected final GenericPO newInstance()
{
return new GenericPO(tableName, getCtx(), ID_NewInstanceNoInit);
}
@Override
public final PO copy()
{
final GenericPO po = (GenericPO)super.copy(); | po.tableName = this.tableName;
po.tableID = this.tableID;
return po;
}
} // GenericPO
/**
* Wrapper class to workaround the limit of PO constructor that doesn't take a tableName or
* tableID parameter. Note that in the generated class scenario ( X_ ), tableName and tableId
* is generated as a static field.
*
* @author Low Heng Sin
*
*/
final class PropertiesWrapper extends Properties
{
/**
*
*/
private static final long serialVersionUID = 8887531951501323594L;
protected Properties source;
protected String tableName;
PropertiesWrapper(Properties source, String tableName)
{
this.source = source;
this.tableName = tableName;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\GenericPO.java | 1 |
请完成以下Java代码 | public Long getDurationInMillis() {
return durationInMillis;
}
public String getCreateUserId() {
return createUserId;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getTenantId() {
return tenantId;
}
public Boolean getActive() {
return active;
}
public Boolean getCompleted() {
return completed;
}
public Boolean getTerminated() {
return terminated;
}
public Boolean getClosed() {
return closed;
} | public static HistoricCaseInstanceDto fromHistoricCaseInstance(HistoricCaseInstance historicCaseInstance) {
HistoricCaseInstanceDto dto = new HistoricCaseInstanceDto();
dto.id = historicCaseInstance.getId();
dto.businessKey = historicCaseInstance.getBusinessKey();
dto.caseDefinitionId = historicCaseInstance.getCaseDefinitionId();
dto.caseDefinitionKey = historicCaseInstance.getCaseDefinitionKey();
dto.caseDefinitionName = historicCaseInstance.getCaseDefinitionName();
dto.createTime = historicCaseInstance.getCreateTime();
dto.closeTime = historicCaseInstance.getCloseTime();
dto.durationInMillis = historicCaseInstance.getDurationInMillis();
dto.createUserId = historicCaseInstance.getCreateUserId();
dto.superCaseInstanceId = historicCaseInstance.getSuperCaseInstanceId();
dto.superProcessInstanceId = historicCaseInstance.getSuperProcessInstanceId();
dto.tenantId = historicCaseInstance.getTenantId();
dto.active = historicCaseInstance.isActive();
dto.completed = historicCaseInstance.isCompleted();
dto.terminated = historicCaseInstance.isTerminated();
dto.closed = historicCaseInstance.isClosed();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricCaseInstanceDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Application
{
public static final String ENDPOINT_ROOT = "/rest";
public static void main(final String[] args)
{
SpringApplication.run(Application.class, args);
}
@Bean
public static ObjectMapper jsonObjectMapper()
{
// important to register the jackson-datatype-jsr310 module which we have in our pom and
// which is needed to serialize/deserialize java.time.Instant
//noinspection ConstantConditions
assert com.fasterxml.jackson.datatype.jsr310.JavaTimeModule.class != null; // just to get a compile error if not present
return new ObjectMapper()
.findAndRegisterModules()
.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS)
.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE)
.enable(MapperFeature.USE_ANNOTATIONS);
}
/**
* @return default task executor used by {@link Async} calls
*/
@Bean("asyncCallsTaskExecutor")
public TaskExecutor asyncCallsTaskExecutor()
{
final ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor(); | executor.setCorePoolSize(1);
executor.setMaxPoolSize(10);
executor.setQueueCapacity(100);
return executor;
}
@Bean
public Docket docket()
{
return new Docket(DocumentationType.OAS_30)
.select()
.paths(PathSelectors.any())
.build();
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\Application.java | 2 |
请在Spring Boot框架中完成以下Java代码 | static class IntegrationRSocketEndpointAvailable {
}
@ConditionalOnBean(RSocketOutboundGateway.class)
static class RSocketOutboundGatewayAvailable {
}
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(TcpServerTransport.class)
protected static class IntegrationRSocketServerConfiguration {
@Bean
@ConditionalOnMissingBean(ServerRSocketMessageHandler.class)
RSocketMessageHandler serverRSocketMessageHandler(RSocketStrategies rSocketStrategies,
IntegrationProperties integrationProperties) {
RSocketMessageHandler messageHandler = new ServerRSocketMessageHandler(
integrationProperties.getRsocket().getServer().isMessageMappingEnabled());
messageHandler.setRSocketStrategies(rSocketStrategies);
return messageHandler;
}
@Bean
@ConditionalOnMissingBean
ServerRSocketConnector serverRSocketConnector(ServerRSocketMessageHandler messageHandler) {
return new ServerRSocketConnector(messageHandler);
}
}
@Configuration(proxyBeanMethods = false)
protected static class IntegrationRSocketClientConfiguration {
@Bean
@ConditionalOnMissingBean
@Conditional(RemoteRSocketServerAddressConfigured.class)
ClientRSocketConnector clientRSocketConnector(IntegrationProperties integrationProperties,
RSocketStrategies rSocketStrategies) { | IntegrationProperties.RSocket.Client client = integrationProperties.getRsocket().getClient();
ClientRSocketConnector clientRSocketConnector;
if (client.getUri() != null) {
clientRSocketConnector = new ClientRSocketConnector(client.getUri());
}
else if (client.getHost() != null && client.getPort() != null) {
clientRSocketConnector = new ClientRSocketConnector(client.getHost(), client.getPort());
}
else {
throw new IllegalStateException("Neither uri nor host and port is set");
}
clientRSocketConnector.setRSocketStrategies(rSocketStrategies);
return clientRSocketConnector;
}
/**
* Check if a remote address is configured for the RSocket Integration client.
*/
static class RemoteRSocketServerAddressConfigured extends AnyNestedCondition {
RemoteRSocketServerAddressConfigured() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty("spring.integration.rsocket.client.uri")
static class WebSocketAddressConfigured {
}
@ConditionalOnProperty({ "spring.integration.rsocket.client.host",
"spring.integration.rsocket.client.port" })
static class TcpAddressConfigured {
}
}
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-integration\src\main\java\org\springframework\boot\integration\autoconfigure\IntegrationAutoConfiguration.java | 2 |
请完成以下Java代码 | public static String toPermissionsKeyString(final Properties ctx)
{
final int adRoleId = Env.getAD_Role_ID(ctx);
final int adUserId = Env.getAD_User_ID(ctx);
final int adClientId = Env.getAD_Client_ID(ctx);
final LocalDate date = TimeUtil.asLocalDate(Env.getDate(ctx));
return toPermissionsKeyString(adRoleId, adUserId, adClientId, date);
}
private static final transient Logger logger = LogManager.getLogger(UserRolePermissionsKey.class);
@Getter
private final RoleId roleId;
@Getter
private final UserId userId;
@Getter
private final ClientId clientId;
@Getter
private final LocalDate date;
private transient String _permissionsKeyStr;
@Builder
private UserRolePermissionsKey(final RoleId roleId, final UserId userId, final ClientId clientId, final Date date)
{
this(roleId, userId, clientId,
date != null ? TimeUtil.asLocalDate(date) : SystemTime.asLocalDate());
}
private UserRolePermissionsKey(
@NonNull final RoleId roleId,
@NonNull final UserId userId,
final ClientId clientId,
@NonNull final LocalDate date)
{
this.roleId = roleId;
this.userId = userId;
this.clientId = clientId;
this.date = date;
}
private UserRolePermissionsKey(final String permissionsKeyStr)
{
// NOTE: keep in sync with the counterpart method toPermissionsKeyString(...) !!!
try
{
final String[] list = permissionsKeyStr.split("\\|");
if (list.length != 4)
{
throw new IllegalArgumentException("invalid format");
}
roleId = RoleId.ofRepoId(Integer.parseInt(list[0]));
userId = UserId.ofRepoId(Integer.parseInt(list[1]));
clientId = ClientId.ofRepoId(Integer.parseInt(list[2]));
date = LocalDate.parse(list[3]);
_permissionsKeyStr = permissionsKeyStr;
}
catch (final Exception e)
{
throw new IllegalArgumentException("Invalid permissionsKey string: " + permissionsKeyStr, e);
}
}
/** | * @see #fromString(String)
*/
public String toPermissionsKeyString()
{
String permissionsKeyStr = _permissionsKeyStr;
if (permissionsKeyStr == null)
{
_permissionsKeyStr = permissionsKeyStr = toPermissionsKeyString(roleId, userId, clientId, date);
}
return permissionsKeyStr;
}
public static long normalizeDate(final Instant date)
{
return normalizeDate(TimeUtil.asDate(date));
}
public static long normalizeDate(final Date date)
{
final long dateDayMillis = TimeUtil.truncToMillis(date, TimeUtil.TRUNC_DAY);
// Make sure we are we are caching only on day level, else would make no sense,
// and performance penalty would be quite big
// (i.e. retrieve and load and aggregate the whole shit everything we need to check something in permissions)
if (date == null || date.getTime() != dateDayMillis)
{
logger.warn("For performance purpose, make sure you providing a date which is truncated on day level: {}", date);
}
return dateDayMillis;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\UserRolePermissionsKey.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getCalledProcessInstanceId() {
return calledProcessInstanceId;
}
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
@ApiModelProperty(example = "fozzie")
public String getAssignee() {
return assignee;
}
public void setAssignee(String assignee) {
this.assignee = assignee;
}
@ApiModelProperty(example = "2013-04-17T10:17:43.902+0000")
public Date getStartTime() {
return startTime;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
@ApiModelProperty(example = "2013-04-18T14:06:32.715+0000")
public Date getEndTime() {
return endTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
@ApiModelProperty(example = "86400056") | public Long getDurationInMillis() {
return durationInMillis;
}
public void setDurationInMillis(Long durationInMillis) {
this.durationInMillis = durationInMillis;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricActivityInstanceResponse.java | 2 |
请完成以下Java代码 | private ColorId getColorIdBySysConfig(final String sysConfigName)
{
final String colorName = Services.get(ISysConfigBL.class).getValue(sysConfigName, "-");
if (Check.isEmpty(colorName) || "-".equals(colorName))
{
return null;
}
return Services.get(IColorRepository.class).getColorIdByName(colorName);
}
@Override
public void failForMissingPricingConditions(final de.metas.adempiere.model.I_C_Order order)
{
final boolean mandatoryPricingConditions = isMandatoryPricingConditions();
if (!mandatoryPricingConditions)
{
return;
}
final List<I_C_OrderLine> orderLines = Services.get(IOrderDAO.class).retrieveOrderLines(order);
final boolean existsOrderLineWithNoPricingConditions = orderLines
.stream()
.anyMatch(this::isPricingConditionsMissingButRequired);
if (existsOrderLineWithNoPricingConditions)
{
throw new AdempiereException(MSG_NoPricingConditionsError)
.setParameter("HowToDisablePricingConditionsCheck", "To disable it, please set " + SYSCONFIG_NoPriceConditionsColorName + " to `-`");
}
}
private boolean isMandatoryPricingConditions()
{
final ColorId noPriceConditionsColorId = getNoPriceConditionsColorId();
return noPriceConditionsColorId != null;
}
private boolean isPricingConditionsMissingButRequired(final I_C_OrderLine orderLine)
{
// Pricing conditions are not required for packing material line (task 3925)
if (orderLine.isPackagingMaterial())
{ | return false;
}
return hasPricingConditions(orderLine) == HasPricingConditions.NO;
}
private HasPricingConditions hasPricingConditions(final I_C_OrderLine orderLine)
{
if (orderLine.isTempPricingConditions())
{
return HasPricingConditions.TEMPORARY;
}
else if (orderLine.getM_DiscountSchemaBreak_ID() > 0)
{
return HasPricingConditions.YES;
}
else
{
return HasPricingConditions.NO;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLinePricingConditions.java | 1 |
请完成以下Java代码 | public ResponseEntity getComments(
@PathVariable("slug") String slug, @AuthenticationPrincipal User user) {
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
List<CommentData> comments = commentQueryService.findByArticleId(article.getId(), user);
return ResponseEntity.ok(
new HashMap<String, Object>() {
{
put("comments", comments);
}
});
}
@RequestMapping(path = "{id}", method = RequestMethod.DELETE)
public ResponseEntity deleteComment(
@PathVariable("slug") String slug,
@PathVariable("id") String commentId,
@AuthenticationPrincipal User user) {
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
return commentRepository
.findById(article.getId(), commentId)
.map(
comment -> {
if (!AuthorizationService.canWriteComment(user, article, comment)) {
throw new NoAuthorizationException();
}
commentRepository.remove(comment);
return ResponseEntity.noContent().build();
})
.orElseThrow(ResourceNotFoundException::new);
}
private Map<String, Object> commentResponse(CommentData commentData) { | return new HashMap<String, Object>() {
{
put("comment", commentData);
}
};
}
}
@Getter
@NoArgsConstructor
@JsonRootName("comment")
class NewCommentParam {
@NotBlank(message = "can't be empty")
private String body;
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\CommentsApi.java | 1 |
请完成以下Java代码 | private Integer getTargetRecordIdMatchingConfig(@NonNull final ExternalSystemScriptedExportConversionConfig config,
@NonNull final Integer recordId)
{
final String sql = getSqlWithWhereClauseAndDocBaseTypeIfPresent(config);
try
{
return DB.retrieveFirstRowOrNull(sql, Collections.singletonList(recordId), rs -> {
final int intValue = rs.getInt(1);
return rs.wasNull() ? null : intValue;
});
}
catch (final Exception exception)
{
log.warn("Error executing SQL: {} with param: {}", sql, recordId);
}
return null;
}
@NonNull
private String getSqlWithWhereClauseAndDocBaseTypeIfPresent(@NonNull final ExternalSystemScriptedExportConversionConfig config)
{
final String rootTableName = tableDAO.retrieveTableName(config.getAdTableId());
final String rootKeyColumnName = columnBL.getSingleKeyColumn(rootTableName);
return Optional.ofNullable(config.getDocBaseType())
.map(docBaseType -> "SELECT " + rootKeyColumnName +
" FROM " + rootTableName + " root" +
" WHERE " + config.getWhereClause() +
" AND root." + rootKeyColumnName + " = ?" +
" AND EXISTS (" +
" SELECT 1 FROM C_DocType targetType" +
" WHERE targetType.DocBaseType = '" + docBaseType.getCode() + "'" +
" AND targetType.C_DocType_ID = root.C_DocType_ID" +
")")
.orElseGet(() -> "SELECT " + rootKeyColumnName
+ " FROM " + rootTableName
+ " WHERE " + rootKeyColumnName + "=?"
+ " AND " + config.getWhereClause());
}
@NonNull
private String getOutboundProcessResponse(
@NonNull final ExternalSystemScriptedExportConversionConfig config,
@NonNull final Properties context,
@NonNull final String outboundDataProcessRecordId)
{
final String rootTableName = tableDAO.retrieveTableName(config.getAdTableId());
final String rootKeyColumnName = columnBL.getSingleKeyColumn(rootTableName);
final ProcessExecutor processExecutor = ProcessInfo.builder() | .setCtx(context)
.setRecord(TableRecordReference.of(config.getAdTableId(), StringUtils.toIntegerOrZero(outboundDataProcessRecordId)))
.setAD_Process_ID(config.getOutboundDataProcessId())
.addParameter(rootKeyColumnName, outboundDataProcessRecordId)
.buildAndPrepareExecution()
.executeSync();
final Resource resource = Optional.ofNullable(processExecutor.getResult())
.map(ProcessExecutionResult::getReportDataResource)
.orElse(null);
if (resource == null || !resource.exists())
{
throw new AdempiereException("Process did not return a valid Resource")
.appendParametersToMessage()
.setParameter("OutboundDataProcessId", config.getOutboundDataProcessId());
}
try (final InputStream in = resource.getInputStream())
{
return StreamUtils.copyToString(in, StandardCharsets.UTF_8);
}
catch (final IOException ex)
{
throw new AdempiereException("Failed to read process output Resource", ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\scriptedexportconversion\ExternalSystemScriptedExportConversionService.java | 1 |
请完成以下Java代码 | public void addProduct(@Nullable final I_M_Product product)
{
builder.product(product);
}
public void setConditions(I_C_Flatrate_Conditions conditions)
{
builder.conditions(conditions);
}
public void setIsSimulation(final boolean isSimulation)
{
builder.isSimulation(isSimulation);
}
public void setIsCompleteDocument(final boolean isCompleteDocument)
{
builder.isCompleteDocument(isCompleteDocument);
}
@Override
public String doIt() throws Exception | {
builder
.ctx(getCtx())
.bPartners(getBPartners())
.build()
.createTermsForBPartners();
return MSG_OK;
}
/**
* Implement this method in the subclass to provide all the partners that are about to have terms created.
*
* @return an iterator of the partners.
*/
protected abstract Iterable<I_C_BPartner> getBPartners();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\process\C_Flatrate_Term_Create.java | 1 |
请完成以下Java代码 | public ProductBOMVersionsId createBOMVersions(@NonNull final BOMVersionsCreateRequest request)
{
final OrgId orgId = request.getOrgId();
final I_PP_Product_BOMVersions bomVersionsRecord = newInstance(I_PP_Product_BOMVersions.class);
bomVersionsRecord.setAD_Org_ID(orgId.getRepoId());
bomVersionsRecord.setM_Product_ID(request.getProductId().getRepoId());
bomVersionsRecord.setName(request.getName());
bomVersionsRecord.setDescription(request.getDescription());
saveRecord(bomVersionsRecord);
return ProductBOMVersionsId.ofRepoId(bomVersionsRecord.getPP_Product_BOMVersions_ID());
}
@NonNull
public Optional<ProductBOMVersionsId> retrieveBOMVersionsId(@NonNull final ProductId productId)
{
return getBOMVersionsByProductId(productId)
.map(I_PP_Product_BOMVersions::getPP_Product_BOMVersions_ID) | .map(ProductBOMVersionsId::ofRepoId);
}
@NonNull
public I_PP_Product_BOMVersions getBOMVersions(@NonNull final ProductBOMVersionsId versionsId)
{
return InterfaceWrapperHelper.load(versionsId, I_PP_Product_BOMVersions.class);
}
@NonNull
private Optional<I_PP_Product_BOMVersions> getBOMVersionsByProductId(@NonNull final ProductId productId)
{
return queryBL.createQueryBuilder(I_PP_Product_BOMVersions.class)
.addEqualsFilter(I_PP_Product_BOMVersions.COLUMNNAME_M_Product_ID, productId.getRepoId())
.addOnlyActiveRecordsFilter()
.create()
.firstOnlyOptional(I_PP_Product_BOMVersions.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\impl\ProductBOMVersionsDAO.java | 1 |
请完成以下Java代码 | private void registerHandler(@NonNull final ManageSchedulerRequestHandler handler)
{
getEventBus().subscribe(SchedulerEventBusService.ManageSchedulerRequestHandlerAsEventListener.builder()
.handler(handler)
.eventLogUserService(eventLogUserService)
.build());
logger.info("Registered handler: {}", handler);
}
@lombok.ToString
private static final class ManageSchedulerRequestHandlerAsEventListener implements IEventListener
{
private final EventLogUserService eventLogUserService;
private final ManageSchedulerRequestHandler handler;
@lombok.Builder
private ManageSchedulerRequestHandlerAsEventListener(
@NonNull final ManageSchedulerRequestHandler handler,
@NonNull final EventLogUserService eventLogUserService)
{
this.handler = handler;
this.eventLogUserService = eventLogUserService;
}
@Override
public void onEvent(@NonNull final IEventBus eventBus, @NonNull final Event event)
{
final ManageSchedulerRequest request = extractManageSchedulerRequest(event);
try (final IAutoCloseable ignored = switchCtx(request);
final MDC.MDCCloseable ignored1 = MDC.putCloseable("eventHandler.className", handler.getClass().getName()))
{
eventLogUserService.invokeHandlerAndLog(EventLogUserService.InvokeHandlerAndLogRequest.builder()
.handlerClass(handler.getClass()) | .invokaction(() -> handleRequest(request))
.build());
}
}
private void handleRequest(@NonNull final ManageSchedulerRequest request)
{
handler.handleRequest(request);
}
private IAutoCloseable switchCtx(@NonNull final ManageSchedulerRequest request)
{
final Properties ctx = createCtx(request);
return Env.switchContext(ctx);
}
private Properties createCtx(@NonNull final ManageSchedulerRequest request)
{
final Properties ctx = Env.newTemporaryCtx();
Env.setClientId(ctx, request.getClientId());
return ctx;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\scheduler\eventbus\SchedulerEventBusService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MyAccessDecisionManager implements AccessDecisionManager {
private final static Logger logger = LoggerFactory.getLogger(MyAccessDecisionManager.class);
/**
* 通过传递的参数来决定用户是否有访问对应受保护对象的权限
*
* @param authentication 包含了当前的用户信息,包括拥有的权限。这里的权限来源就是前面登录时UserDetailsService中设置的authorities。
* @param object 就是FilterInvocation对象,可以得到request等web资源
* @param configAttributes configAttributes是本次访问需要的权限
*/
@Override
public void decide(Authentication authentication, Object object, Collection<ConfigAttribute> configAttributes) throws AccessDeniedException, InsufficientAuthenticationException {
if (null == configAttributes || 0 >= configAttributes.size()) {
return;
} else {
String needRole;
for(Iterator<ConfigAttribute> iter = configAttributes.iterator(); iter.hasNext(); ) {
needRole = iter.next().getAttribute();
for(GrantedAuthority ga : authentication.getAuthorities()) {
if(needRole.trim().equals(ga.getAuthority().trim())) {
return;
}
}
}
throw new AccessDeniedException("当前访问没有权限");
}
} | /**
* 表示此AccessDecisionManager是否能够处理传递的ConfigAttribute呈现的授权请求
*/
@Override
public boolean supports(ConfigAttribute configAttribute) {
return true;
}
/**
* 表示当前AccessDecisionManager实现是否能够为指定的安全对象(方法调用或Web请求)提供访问控制决策
*/
@Override
public boolean supports(Class<?> aClass) {
return true;
}
} | repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\config\MyAccessDecisionManager.java | 2 |
请完成以下Java代码 | private StructuredLogEncoder createStructuredLogEncoder(String format) {
StructuredLogEncoder encoder = new StructuredLogEncoder();
encoder.setFormat(format);
return encoder;
}
private void setRollingPolicy(RollingFileAppender<ILoggingEvent> appender, LogbackConfigurator config) {
SizeAndTimeBasedRollingPolicy<ILoggingEvent> rollingPolicy = new SizeAndTimeBasedRollingPolicy<>();
rollingPolicy.setContext(config.getContext());
rollingPolicy.setFileNamePattern(
resolve(config, "${LOGBACK_ROLLINGPOLICY_FILE_NAME_PATTERN:-${LOG_FILE}.%d{yyyy-MM-dd}.%i.gz}"));
rollingPolicy
.setCleanHistoryOnStart(resolveBoolean(config, "${LOGBACK_ROLLINGPOLICY_CLEAN_HISTORY_ON_START:-false}"));
rollingPolicy.setMaxFileSize(resolveFileSize(config, "${LOGBACK_ROLLINGPOLICY_MAX_FILE_SIZE:-10MB}"));
rollingPolicy.setTotalSizeCap(resolveFileSize(config, "${LOGBACK_ROLLINGPOLICY_TOTAL_SIZE_CAP:-0}"));
rollingPolicy.setMaxHistory(resolveInt(config, "${LOGBACK_ROLLINGPOLICY_MAX_HISTORY:-7}"));
appender.setRollingPolicy(rollingPolicy);
rollingPolicy.setParent(appender);
config.start(rollingPolicy);
}
private boolean resolveBoolean(LogbackConfigurator config, String val) {
return Boolean.parseBoolean(resolve(config, val));
}
private int resolveInt(LogbackConfigurator config, String val) {
return Integer.parseInt(resolve(config, val));
}
private FileSize resolveFileSize(LogbackConfigurator config, String val) {
return FileSize.valueOf(resolve(config, val));
}
private Charset resolveCharset(LogbackConfigurator config, String val) {
return Charset.forName(resolve(config, val));
}
private String resolve(LogbackConfigurator config, String val) {
try {
return OptionHelper.substVars(val, config.getContext());
}
catch (ScanException ex) {
throw new RuntimeException(ex);
}
} | private static String faint(String value) {
return color(value, AnsiStyle.FAINT);
}
private static String cyan(String value) {
return color(value, AnsiColor.CYAN);
}
private static String magenta(String value) {
return color(value, AnsiColor.MAGENTA);
}
private static String colorByLevel(String value) {
return "%clr(" + value + "){}";
}
private static String color(String value, AnsiElement ansiElement) {
return "%clr(" + value + "){" + ColorConverter.getName(ansiElement) + "}";
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\logback\DefaultLogbackConfiguration.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getBoundSqlInterceptors() {
return boundSqlInterceptors;
}
public void setBoundSqlInterceptors(String boundSqlInterceptors) {
this.boundSqlInterceptors = boundSqlInterceptors;
Optional.ofNullable(boundSqlInterceptors).ifPresent(v -> properties.setProperty("boundSqlInterceptors", v));
}
public Boolean getKeepOrderBy() {
return keepOrderBy;
}
public void setKeepOrderBy(Boolean keepOrderBy) {
this.keepOrderBy = keepOrderBy;
Optional.ofNullable(keepOrderBy).ifPresent(v -> properties.setProperty("keepOrderBy", v.toString()));
}
public Boolean getKeepSubSelectOrderBy() {
return keepSubSelectOrderBy;
}
public void setKeepSubSelectOrderBy(Boolean keepSubSelectOrderBy) {
this.keepSubSelectOrderBy = keepSubSelectOrderBy;
Optional.ofNullable(keepSubSelectOrderBy).ifPresent(v -> properties.setProperty("keepSubSelectOrderBy", v.toString()));
}
public String getSqlParser() {
return sqlParser;
}
public void setSqlParser(String sqlParser) {
this.sqlParser = sqlParser;
Optional.ofNullable(sqlParser).ifPresent(v -> properties.setProperty("sqlParser", v));
}
public Boolean getAsyncCount() {
return asyncCount;
}
public void setAsyncCount(Boolean asyncCount) { | this.asyncCount = asyncCount;
Optional.ofNullable(asyncCount).ifPresent(v -> properties.setProperty("asyncCount", v.toString()));
}
public String getCountSqlParser() {
return countSqlParser;
}
public void setCountSqlParser(String countSqlParser) {
this.countSqlParser = countSqlParser;
Optional.ofNullable(countSqlParser).ifPresent(v -> properties.setProperty("countSqlParser", v));
}
public String getOrderBySqlParser() {
return orderBySqlParser;
}
public void setOrderBySqlParser(String orderBySqlParser) {
this.orderBySqlParser = orderBySqlParser;
Optional.ofNullable(orderBySqlParser).ifPresent(v -> properties.setProperty("orderBySqlParser", v));
}
public String getSqlServerSqlParser() {
return sqlServerSqlParser;
}
public void setSqlServerSqlParser(String sqlServerSqlParser) {
this.sqlServerSqlParser = sqlServerSqlParser;
Optional.ofNullable(sqlServerSqlParser).ifPresent(v -> properties.setProperty("sqlServerSqlParser", v));
}
} | repos\pagehelper-spring-boot-master\pagehelper-spring-boot-autoconfigure\src\main\java\com\github\pagehelper\autoconfigure\PageHelperStandardProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private class PropertiesCluster implements Cluster {
private final List<Node> nodes;
PropertiesCluster(DataRedisProperties.Cluster properties) {
this.nodes = asNodes(properties.getNodes());
}
@Override
public List<Node> getNodes() {
return this.nodes;
}
}
/**
* {@link MasterReplica} implementation backed by properties.
*/
private class PropertiesMasterReplica implements MasterReplica {
private final List<Node> nodes;
PropertiesMasterReplica(DataRedisProperties.Masterreplica properties) {
this.nodes = asNodes(properties.getNodes());
}
@Override
public List<Node> getNodes() {
return this.nodes;
}
}
/**
* {@link Sentinel} implementation backed by properties.
*/
private class PropertiesSentinel implements Sentinel {
private final int database; | private final DataRedisProperties.Sentinel properties;
PropertiesSentinel(int database, DataRedisProperties.Sentinel properties) {
this.database = database;
this.properties = properties;
}
@Override
public int getDatabase() {
return this.database;
}
@Override
public String getMaster() {
String master = this.properties.getMaster();
Assert.state(master != null, "'master' must not be null");
return master;
}
@Override
public List<Node> getNodes() {
return asNodes(this.properties.getNodes());
}
@Override
public @Nullable String getUsername() {
return this.properties.getUsername();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\PropertiesDataRedisConnectionDetails.java | 2 |
请在Spring Boot框架中完成以下Java代码 | DefaultEndpointObjectNameFactory endpointObjectNameFactory(MBeanServer mBeanServer) {
String contextId = ObjectUtils.getIdentityHexString(this.applicationContext);
return new DefaultEndpointObjectNameFactory(this.properties, this.jmxProperties, mBeanServer, contextId);
}
@Bean
IncludeExcludeEndpointFilter<ExposableJmxEndpoint> jmxIncludeExcludePropertyEndpointFilter() {
JmxEndpointProperties.Exposure exposure = this.properties.getExposure();
return new IncludeExcludeEndpointFilter<>(ExposableJmxEndpoint.class, exposure.getInclude(),
exposure.getExclude(), EndpointExposure.JMX.getDefaultIncludes());
}
@Bean
static LazyInitializationExcludeFilter eagerlyInitializeJmxEndpointExporter() {
return LazyInitializationExcludeFilter.forBeanTypes(JmxEndpointExporter.class);
}
@Bean
OperationFilter<JmxOperation> jmxAccessPropertiesOperationFilter(EndpointAccessResolver endpointAccessResolver) {
return OperationFilter.byAccess(endpointAccessResolver);
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JsonMapper.class)
static class JmxJacksonEndpointConfiguration {
@Bean
@ConditionalOnSingleCandidate(MBeanServer.class)
JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer,
EndpointObjectNameFactory endpointObjectNameFactory, ObjectProvider<JsonMapper> jsonMapper,
JmxEndpointsSupplier jmxEndpointsSupplier) {
JmxOperationResponseMapper responseMapper = new JacksonJmxOperationResponseMapper(
jsonMapper.getIfAvailable());
return new JmxEndpointExporter(mBeanServer, endpointObjectNameFactory, responseMapper,
jmxEndpointsSupplier.getEndpoints());
}
} | @Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
@ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper")
@Deprecated(since = "4.0.0", forRemoval = true)
@SuppressWarnings("removal")
static class JmxJackson2EndpointConfiguration {
@Bean
@ConditionalOnSingleCandidate(MBeanServer.class)
JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer,
EndpointObjectNameFactory endpointObjectNameFactory, ObjectProvider<ObjectMapper> objectMapper,
JmxEndpointsSupplier jmxEndpointsSupplier) {
JmxOperationResponseMapper responseMapper = new org.springframework.boot.actuate.endpoint.jmx.Jackson2JmxOperationResponseMapper(
objectMapper.getIfAvailable());
return new JmxEndpointExporter(mBeanServer, endpointObjectNameFactory, responseMapper,
jmxEndpointsSupplier.getEndpoints());
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\jmx\JmxEndpointAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<Hazardous> getHazardous() {
if (hazardous == null) {
hazardous = new ArrayList<Hazardous>();
}
return this.hazardous;
}
/**
* Gets the value of the printInfo1OnParcelLabel property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isPrintInfo1OnParcelLabel() {
return printInfo1OnParcelLabel;
}
/**
* Sets the value of the printInfo1OnParcelLabel property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setPrintInfo1OnParcelLabel(Boolean value) {
this.printInfo1OnParcelLabel = value;
}
/**
* Gets the value of the info1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getInfo1() {
return info1;
}
/**
* Sets the value of the info1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInfo1(String value) {
this.info1 = value;
}
/**
* Gets the value of the info2 property.
*
* @return
* possible object is
* {@link String }
*
*/ | public String getInfo2() {
return info2;
}
/**
* Sets the value of the info2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setInfo2(String value) {
this.info2 = value;
}
/**
* Gets the value of the returns property.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isReturns() {
return returns;
}
/**
* Sets the value of the returns property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setReturns(Boolean value) {
this.returns = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Parcel.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getTaskDefinitionKey() {
return taskDefinitionKey;
}
public String getTaskOwnerLike() {
return taskOwnerLike;
}
public String getTaskOwner() {
return taskOwner;
}
public Collection<String> getTaskDefinitionKeys() {
return taskDefinitionKeys;
}
public String getTaskParentTaskId() {
return taskParentTaskId;
}
public String getCandidateUser() {
return candidateUser;
}
public String getCandidateGroup() {
return candidateGroup;
}
public String getInvolvedUser() {
return involvedUser;
}
public Collection<String> getInvolvedGroups() {
return involvedGroups;
}
public boolean isIgnoreAssigneeValue() {
return ignoreAssigneeValue;
}
public String getProcessDefinitionKeyLikeIgnoreCase() {
return processDefinitionKeyLikeIgnoreCase;
}
public String getProcessInstanceBusinessKeyLikeIgnoreCase() {
return processInstanceBusinessKeyLikeIgnoreCase;
}
public String getTaskNameLikeIgnoreCase() {
return taskNameLikeIgnoreCase;
}
public String getTaskDescriptionLikeIgnoreCase() {
return taskDescriptionLikeIgnoreCase;
}
public String getTaskOwnerLikeIgnoreCase() {
return taskOwnerLikeIgnoreCase;
}
public String getTaskAssigneeLikeIgnoreCase() {
return taskAssigneeLikeIgnoreCase;
}
public boolean isWithoutDeleteReason() {
return withoutDeleteReason;
}
public String getLocale() {
return locale;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
} | public String getCaseDefinitionKeyLike() {
return caseDefinitionKeyLike;
}
public String getCaseDefinitionKeyLikeIgnoreCase() {
return caseDefinitionKeyLikeIgnoreCase;
}
public Collection<String> getCaseDefinitionKeys() {
return caseDefinitionKeys;
}
public boolean isWithLocalizationFallback() {
return withLocalizationFallback;
}
public List<HistoricTaskInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public List<List<String>> getSafeCandidateGroups() {
return safeCandidateGroups;
}
public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) {
this.safeCandidateGroups = safeCandidateGroups;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public List<List<String>> getSafeScopeIds() {
return safeScopeIds;
}
public void setSafeScopeIds(List<List<String>> safeScopeIds) {
this.safeScopeIds = safeScopeIds;
}
} | repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\HistoricTaskInstanceQueryImpl.java | 2 |
请完成以下Java代码 | public VariableMap getCachedVariables() {
return cachedVariables;
}
@SuppressWarnings("unchecked")
public <T extends TypedValue> T getVariableLocal(String variableName) {
TypedValue value = cachedVariablesLocal.getValueTyped(variableName);
if (value == null) {
if (task != null) {
value = taskService.getVariableLocalTyped(task.getId(), variableName);
cachedVariablesLocal.put(variableName, value);
} else if (execution != null) {
value = runtimeService.getVariableLocalTyped(execution.getId(), variableName);
cachedVariablesLocal.put(variableName, value);
}
}
return (T) value;
}
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 String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Displayed.
@param IsDisplayed
Determines, if this field is displayed
*/
public void setIsDisplayed (boolean IsDisplayed)
{
set_Value (COLUMNNAME_IsDisplayed, Boolean.valueOf(IsDisplayed));
}
/** Get Displayed.
@return Determines, if this field is displayed
*/
public boolean isDisplayed ()
{
Object oo = get_Value(COLUMNNAME_IsDisplayed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Multi Row Only.
@param IsMultiRowOnly
This applies to Multi-Row view only
*/
public void setIsMultiRowOnly (boolean IsMultiRowOnly)
{
set_Value (COLUMNNAME_IsMultiRowOnly, Boolean.valueOf(IsMultiRowOnly));
}
/** Get Multi Row Only.
@return This applies to Multi-Row view only
*/
public boolean isMultiRowOnly ()
{
Object oo = get_Value(COLUMNNAME_IsMultiRowOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Read Only.
@param IsReadOnly
Field is read only
*/
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Read Only.
@return Field is read only
*/
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Single Row Layout.
@param IsSingleRow
Default for toggle between Single- and Multi-Row (Grid) Layout
*/
public void setIsSingleRow (boolean IsSingleRow)
{
set_Value (COLUMNNAME_IsSingleRow, Boolean.valueOf(IsSingleRow));
}
/** Get Single Row Layout.
@return Default for toggle between Single- and Multi-Row (Grid) Layout | */
public boolean isSingleRow ()
{
Object oo = get_Value(COLUMNNAME_IsSingleRow);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Tab.java | 1 |
请完成以下Java代码 | protected LookupValuesList getAvailableLocators(final LookupDataSourceContext evalCtx)
{
final WarehouseId selectedWarehouseId = warehouseId;
if (selectedWarehouseId == null)
{
return LookupValuesList.EMPTY;
}
final ImmutableList<I_M_HU> selectedHUs = getSelectedHUs();
final ImmutableSet<LocatorId> eligibleLocatorIds = getEligibleLocatorIds(selectedHUs)
.stream()
.filter(locatorId -> WarehouseId.equals(locatorId.getWarehouseId(), selectedWarehouseId))
.collect(ImmutableSet.toImmutableSet());
return locatorLookup.findByIdsOrdered(eligibleLocatorIds);
}
private Set<LocatorId> getEligibleLocatorIds(final ImmutableList<I_M_HU> hus)
{
if (hus.isEmpty())
{
return ImmutableSet.of();
}
final Set<LocatorId> huLocatorIds = handlingUnitsDAO.getLocatorIds(hus);
// use the org of first HU to decide which warehouses to fetch (preserved already existing logic)
final OrgId orgId = OrgId.ofRepoId(hus.get(0).getAD_Org_ID());
final Set<WarehouseId> orgWarehouseIds = warehouseDAO.getWarehouseIdsByOrgId(orgId);
final ImmutableSet<LocatorId> orgLocatorIds = warehouseDAO.getLocatorIdsByWarehouseIds(orgWarehouseIds);
return Sets.difference(orgLocatorIds, huLocatorIds);
}
private LocatorId getMoveToLocatorId()
{
if (warehouseId == null)
{
throw new FillMandatoryException(I_M_Locator.COLUMNNAME_M_Warehouse_ID);
}
if (moveToLocatorRepoId <= 0)
{
throw new FillMandatoryException(I_M_Locator.COLUMNNAME_M_Locator_ID); | }
return LocatorId.ofRepoId(warehouseId, moveToLocatorRepoId);
}
protected final ImmutableList<I_M_HU> getSelectedHUs()
{
return streamSelectedHUs(Select.ONLY_TOPLEVEL).collect(ImmutableList.toImmutableList());
}
@Override
protected String doIt()
{
final LocatorId locatorId = getMoveToLocatorId();
final List<I_M_HU> hus = getSelectedHUs();
if (hus.isEmpty())
{
throw new AdempiereException("@NoSelection@");
}
checkHUsEligible().throwExceptionIfRejected();
movementResult = huMovementBL.moveHUsToLocator(hus, locatorId);
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
if (movementResult != null)
{
getView().invalidateAll();
}
}
public abstract ProcessPreconditionsResolution checkHUsEligible();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_MoveToAnotherWarehouse_Template.java | 1 |
请完成以下Java代码 | public HistoricCaseInstanceQuery orderByTenantId() {
return orderBy(HistoricCaseInstanceQueryProperty.TENANT_ID);
}
public long executeCount(CommandContext commandContext) {
checkQueryOk();
ensureVariablesInitialized();
return commandContext
.getHistoricCaseInstanceManager()
.findHistoricCaseInstanceCountByQueryCriteria(this);
}
public List<HistoricCaseInstance> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
ensureVariablesInitialized();
return commandContext
.getHistoricCaseInstanceManager()
.findHistoricCaseInstancesByQueryCriteria(this, page);
}
@Override
protected boolean hasExcludingConditions() {
return super.hasExcludingConditions()
|| CompareUtil.areNotInAscendingOrder(createdAfter, createdBefore)
|| CompareUtil.areNotInAscendingOrder(closedAfter, closedBefore)
|| CompareUtil.elementIsNotContainedInList(caseInstanceId, caseInstanceIds)
|| CompareUtil.elementIsContainedInList(caseDefinitionKey, caseKeyNotIn);
}
public String getBusinessKey() {
return businessKey;
}
public String getBusinessKeyLike() {
return businessKeyLike;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCaseDefinitionIdLike() {
return caseDefinitionKey + ":%:%";
}
public String getCaseDefinitionName() {
return caseDefinitionName;
}
public String getCaseDefinitionNameLike() {
return caseDefinitionNameLike;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public Set<String> getCaseInstanceIds() { | return caseInstanceIds;
}
public String getStartedBy() {
return createdBy;
}
public String getSuperCaseInstanceId() {
return superCaseInstanceId;
}
public void setSuperCaseInstanceId(String superCaseInstanceId) {
this.superCaseInstanceId = superCaseInstanceId;
}
public List<String> getCaseKeyNotIn() {
return caseKeyNotIn;
}
public Date getCreatedAfter() {
return createdAfter;
}
public Date getCreatedBefore() {
return createdBefore;
}
public Date getClosedAfter() {
return closedAfter;
}
public Date getClosedBefore() {
return closedBefore;
}
public String getSubCaseInstanceId() {
return subCaseInstanceId;
}
public String getSuperProcessInstanceId() {
return superProcessInstanceId;
}
public String getSubProcessInstanceId() {
return subProcessInstanceId;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricCaseInstanceQueryImpl.java | 1 |
请完成以下Java代码 | private String extractTopLevelParentHUIdValue(@NonNull final I_M_HU hu)
{
return Optional.ofNullable(handlingUnitsBL.getTopLevelParent(hu))
.map(I_M_HU::getM_HU_ID)
.filter(parentHUId -> parentHUId != hu.getM_HU_ID())
.map(String::valueOf)
.orElse(null);
}
private static @NonNull ResponseEntity<JsonGetSingleHUResponse> toBadRequestResponseEntity(final Exception e)
{
final String adLanguage = Env.getADLanguageOrBaseLanguage();
return ResponseEntity.badRequest()
.body(JsonGetSingleHUResponse.builder()
.error(JsonErrors.ofThrowable(e, adLanguage)) | .multipleHUsFound(wereMultipleHUsFound(e))
.build());
}
private static boolean wereMultipleHUsFound(final Exception e)
{
return Optional.of(e)
.filter(error -> error instanceof AdempiereException)
.map(error -> (AdempiereException)error)
.map(adempiereEx -> adempiereEx.getParameter(MORE_THAN_ONE_HU_FOUND_ERROR_PARAM_NAME))
.filter(moreThanOneHUFoundParam -> moreThanOneHUFoundParam instanceof Boolean)
.map(moreThanOneHUFoundParam -> (Boolean)moreThanOneHUFoundParam)
.orElse(false);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\HandlingUnitsService.java | 1 |
请完成以下Java代码 | public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
if (PARAM_QtyTU.equals(parameter.getColumnName()))
{
return handlingUnitsBL.getTUsCount(getTUOrAggregatedTU()).toInt();
}
else
{
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
}
@Override
protected String doIt()
{
final I_M_HU tuOrAggregatedHU = getTUOrAggregatedTU();
final QtyTU qtyTU = QtyTU.ofInt(this.qtyTU);
final QtyTU maxQtyTU = handlingUnitsBL.getTUsCount(tuOrAggregatedHU);
if (qtyTU.isGreaterThan(maxQtyTU))
{
throw new AdempiereException("@QtyTU@ <= " + maxQtyTU);
}
final I_M_HU luHU = getTargetLU();
//
// If it's a top level TU then
// first remove it from picking slots
final boolean isTopLevelHU = handlingUnitsBL.isTopLevel(tuOrAggregatedHU);
if (isTopLevelHU)
{
huPickingSlotBL.removeFromPickingSlotQueueRecursivelly(tuOrAggregatedHU);
this.huExtractedFromPickingSlotEvent = HUExtractedFromPickingSlotEvent.builder()
.huId(tuOrAggregatedHU.getM_HU_ID())
.bpartnerId(tuOrAggregatedHU.getC_BPartner_ID())
.bpartnerLocationId(tuOrAggregatedHU.getC_BPartner_Location_ID())
.build();
}
final HashSet<HuId> huIdsDestroyedCollector = new HashSet<>();
HUTransformService.builder()
.emptyHUListener(EmptyHUListener.collectDestroyedHUIdsTo(huIdsDestroyedCollector))
.build()
.tuToExistingLU(tuOrAggregatedHU, qtyTU, luHU);
// Remove from picking slots all destroyed HUs
pickingCandidateService.inactivateForHUIds(huIdsDestroyedCollector);
return MSG_OK;
}
@Override | protected void postProcess(final boolean success)
{
if (!success)
{
return;
}
// Invalidate views
final PickingSlotsClearingView pickingSlotsClearingView = getPickingSlotsClearingView();
pickingSlotsClearingView.invalidateAll();
getPackingHUsView().invalidateAll();
if (huExtractedFromPickingSlotEvent != null)
{
pickingSlotsClearingView.handleEvent(huExtractedFromPickingSlotEvent);
}
}
@NonNull
private I_M_HU getTargetLU()
{
final HUEditorRow packingHURow = getSingleSelectedPackingHUsRow();
Check.assume(packingHURow.isLU(), "Pack to HU shall be a LU: {}", packingHURow);
return handlingUnitsBL.getById(packingHURow.getHuId());
}
@NonNull
private I_M_HU getTUOrAggregatedTU()
{
final PickingSlotRow pickingSlotRow = getSingleSelectedPickingSlotRow();
Check.assume(pickingSlotRow.isTU(), "Picking slot HU shall be a TU: {}", pickingSlotRow);
return handlingUnitsBL.getById(pickingSlotRow.getHuId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pickingslotsClearing\process\WEBUI_PickingSlotsClearingView_TakeOutTUAndAddToLU.java | 1 |
请完成以下Java代码 | public class C_BankStatement_UnReconcileLine extends BankStatementBasedProcess
{
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
return checkBankStatementIsDraftOrInProcessOrCompleted(context)
.and(() -> checkSingleLineSelectedWhichIsReconciled(context));
}
private ProcessPreconditionsResolution checkSingleLineSelectedWhichIsReconciled(@NonNull final IProcessPreconditionsContext context)
{
// there should be a single line selected
final Set<TableRecordReference> bankStatemementLineRefs = context.getSelectedIncludedRecords();
if (bankStatemementLineRefs.size() != 1)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("a single line shall be selected");
}
final TableRecordReference bankStatemementLineRef = bankStatemementLineRefs.iterator().next();
final BankStatementLineId bankStatementLineId = BankStatementLineId.ofRepoId(bankStatemementLineRef.getRecord_ID());
final I_C_BankStatementLine line = bankStatementBL.getLineById(bankStatementLineId);
if (!line.isReconciled())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("line shall be reconciled");
}
if (isReconciledByGLJournal(line))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("GL Journal reconciliation");
} | return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt()
{
final I_C_BankStatement bankStatement = getSelectedBankStatement();
bankStatementBL.assertBankStatementIsDraftOrInProcessOrCompleted(bankStatement);
final I_C_BankStatementLine bankStatementLine = getSingleSelectedBankStatementLine();
if (isReconciledByGLJournal(bankStatementLine))
{
throw new AdempiereException("Clearing GL Journal reconciliation is not allowed. Consider reversing the GL Journal instead");
}
bankStatementBL.unreconcile(ImmutableList.of(bankStatementLine));
bankStatementBL.unpost(bankStatement);
return MSG_OK;
}
private static boolean isReconciledByGLJournal(final I_C_BankStatementLine bankStatementLine)
{
return bankStatementLine.isReconciled() && bankStatementLine.getReconciledBy_SAP_GLJournalLine_ID() > 0;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\banking\process\C_BankStatement_UnReconcileLine.java | 1 |
请完成以下Java代码 | public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findMobileAppById(tenantId, new MobileAppId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(mobileAppDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
@Transactional
public void deleteEntity(TenantId tenantId, EntityId id, boolean force) {
deleteMobileAppById(tenantId, (MobileAppId) id);
}
@Override
public MobileApp findByBundleIdAndPlatformType(TenantId tenantId, MobileAppBundleId mobileAppBundleId, PlatformType platformType) {
log.trace("Executing findAndroidQrConfig, tenantId [{}], mobileAppBundleId [{}]", tenantId, mobileAppBundleId);
return mobileAppDao.findByBundleIdAndPlatformType(tenantId, mobileAppBundleId, platformType);
}
@Override
public MobileApp findMobileAppByPkgNameAndPlatformType(String pkgName, PlatformType platformType) {
log.trace("Executing findMobileAppByPkgNameAndPlatformType, pkgName [{}], platform [{}]", pkgName, platformType);
Validator.checkNotNull(platformType, PLATFORM_TYPE_IS_REQUIRED); | return mobileAppDao.findByPkgNameAndPlatformType(TenantId.SYS_TENANT_ID, pkgName, platformType);
}
@Override
public void deleteByTenantId(TenantId tenantId) {
log.trace("Executing deleteByTenantId, tenantId [{}]", tenantId);
mobileAppDao.deleteByTenantId(tenantId);
}
@Override
public EntityType getEntityType() {
return EntityType.MOBILE_APP;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\mobile\MobileAppServiceImpl.java | 1 |
请完成以下Java代码 | public class SysMessage extends JeecgEntity {
/**推送内容*/
@Excel(name = "推送内容", width = 15)
private java.lang.String esContent;
/**推送所需参数Json格式*/
@Excel(name = "推送所需参数Json格式", width = 15)
private java.lang.String esParam;
/**接收人*/
@Excel(name = "接收人", width = 15)
private java.lang.String esReceiver;
/**推送失败原因*/
@Excel(name = "推送失败原因", width = 15)
private java.lang.String esResult;
/**发送次数*/
@Excel(name = "发送次数", width = 15)
private java.lang.Integer esSendNum;
/**推送状态 0未推送 1推送成功 2推送失败*/
@Excel(name = "推送状态 0未推送 1推送成功 2推送失败", width = 15)
@Dict(dicCode = "msgSendStatus")
private java.lang.String esSendStatus;
/**推送时间*/ | @Excel(name = "推送时间", width = 20, format = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private java.util.Date esSendTime;
/**消息标题*/
@Excel(name = "消息标题", width = 15)
private java.lang.String esTitle;
/**
* 推送方式:参考枚举类MessageTypeEnum
*/
@Excel(name = "推送方式", width = 15)
@Dict(dicCode = "messageType")
private java.lang.String esType;
/**备注*/
@Excel(name = "备注", width = 15)
private java.lang.String remark;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\entity\SysMessage.java | 1 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Konnektor.
@param ImpEx_Connector_ID Konnektor */
public void setImpEx_Connector_ID (int ImpEx_Connector_ID)
{
if (ImpEx_Connector_ID < 1)
set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, Integer.valueOf(ImpEx_Connector_ID));
}
/** Get Konnektor.
@return Konnektor */
public int getImpEx_Connector_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_Connector_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public de.metas.impex.model.I_ImpEx_ConnectorType getImpEx_ConnectorType() throws RuntimeException
{
return (de.metas.impex.model.I_ImpEx_ConnectorType)MTable.get(getCtx(), de.metas.impex.model.I_ImpEx_ConnectorType.Table_Name)
.getPO(getImpEx_ConnectorType_ID(), get_TrxName()); }
/** Set Konnektor-Typ.
@param ImpEx_ConnectorType_ID Konnektor-Typ */
public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID)
{
if (ImpEx_ConnectorType_ID < 1)
set_Value (COLUMNNAME_ImpEx_ConnectorType_ID, null);
else
set_Value (COLUMNNAME_ImpEx_ConnectorType_ID, Integer.valueOf(ImpEx_ConnectorType_ID));
}
/** Get Konnektor-Typ.
@return Konnektor-Typ */
public int getImpEx_ConnectorType_ID ()
{ | Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_Connector.java | 1 |
请完成以下Java代码 | public IQueryBuilder<Object> createQueryBuilder(final String modelTableName, final Object contextProvider)
{
return QueryBuilder.createForTableName(modelTableName)
.setContext(contextProvider);
}
@Deprecated
@Override
public <T> IQueryOrderByBuilder<T> createQueryOrderByBuilder()
{
return new QueryOrderByBuilder<>();
}
@Override
public <T> IQueryOrderByBuilder<T> createQueryOrderByBuilder(final Class<T> modelClass)
{
return new QueryOrderByBuilder<>();
}
@Override
public IQueryOrderBy createSqlQueryOrderBy(final String orderBy)
{
return SqlQueryOrderBy.of(orderBy);
}
@Override
public <T> ICompositeQueryFilter<T> createCompositeQueryFilter(final Class<T> modelClass)
{
return CompositeQueryFilter.newInstance(modelClass);
}
@Override
public ICompositeQueryFilter<Object> createCompositeQueryFilter(@Nullable final String modelTableName)
{
return CompositeQueryFilter.newInstance(modelTableName);
}
@Override
public <T> ICompositeQueryUpdater<T> createCompositeQueryUpdater(final Class<T> modelClass)
{
return new CompositeQueryUpdater<>();
}
@Override
public <T> String debugAccept(final IQueryFilter<T> filter, final T model)
{
final StringBuilder sb = new StringBuilder();
sb.append("\n-------------------------------------------------------------------------------");
sb.append("\nModel: " + model);
final List<IQueryFilter<T>> filters = extractAllFilters(filter);
for (final IQueryFilter<T> f : filters)
{
final boolean accept = f.accept(model);
sb.append("\nFilter(accept=" + accept + "): " + f);
}
sb.append("\n-------------------------------------------------------------------------------"); | return sb.toString();
}
private <T> List<IQueryFilter<T>> extractAllFilters(@Nullable final IQueryFilter<T> filter)
{
if (filter == null)
{
return Collections.emptyList();
}
final List<IQueryFilter<T>> result = new ArrayList<>();
result.add(filter);
if (filter instanceof ICompositeQueryFilter)
{
final ICompositeQueryFilter<T> compositeFilter = (ICompositeQueryFilter<T>)filter;
for (final IQueryFilter<T> f : compositeFilter.getFilters())
{
final List<IQueryFilter<T>> resultLocal = extractAllFilters(f);
result.addAll(resultLocal);
}
}
return result;
}
@Override
public <T> QueryResultPage<T> retrieveNextPage(
@NonNull final Class<T> clazz,
@NonNull final String next)
{
if (Adempiere.isUnitTestMode())
{
return POJOQuery.getPage(clazz, next);
}
return SpringContextHolder.instance
.getBean(PaginationService.class)
.loadPage(clazz, next);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryBL.java | 1 |
请完成以下Java代码 | public boolean isShipTo()
{
return get_ValueAsBoolean(COLUMNNAME_IsShipTo);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
/**
* Role AD_Reference_ID=541254
* Reference name: Role
*/
public static final int ROLE_AD_Reference_ID=541254;
/** Main Producer = MP */
public static final String ROLE_MainProducer = "MP";
/** Hostpital = HO */
public static final String ROLE_Hostpital = "HO";
/** Physician Doctor = PD */
public static final String ROLE_PhysicianDoctor = "PD"; | /** General Practitioner = GP */
public static final String ROLE_GeneralPractitioner = "GP";
/** Health Insurance = HI */
public static final String ROLE_HealthInsurance = "HI";
/** Nursing Home = NH */
public static final String ROLE_NursingHome = "NH";
/** Caregiver = CG */
public static final String ROLE_Caregiver = "CG";
/** Preferred Pharmacy = PP */
public static final String ROLE_PreferredPharmacy = "PP";
/** Nursing Service = NS */
public static final String ROLE_NursingService = "NS";
/** Payer = PA */
public static final String ROLE_Payer = "PA";
/** Payer = PA */
public static final String ROLE_Pharmacy = "PH";
@Override
public void setRole (final @Nullable java.lang.String Role)
{
set_Value (COLUMNNAME_Role, Role);
}
@Override
public java.lang.String getRole()
{
return get_ValueAsString(COLUMNNAME_Role);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_Relation.java | 1 |
请完成以下Java代码 | private static void findMiddleRecursively(Node node, MiddleAuxRecursion middleAux) {
if (node == null) {
// reached the end
middleAux.length = middleAux.length / 2;
return;
}
middleAux.length++;
findMiddleRecursively(node.next(), middleAux);
if (middleAux.length == 0) {
// found the middle
middleAux.middle = node;
}
middleAux.length--;
}
public static Optional<String> findMiddleElementFromHead1PassIteratively(Node head) {
if (head == null) {
return Optional.empty(); | }
Node slowPointer = head;
Node fastPointer = head;
while (fastPointer.hasNext() && fastPointer.next()
.hasNext()) {
fastPointer = fastPointer.next()
.next();
slowPointer = slowPointer.next();
}
return Optional.ofNullable(slowPointer.data());
}
private static class MiddleAuxRecursion {
Node middle;
int length = 0;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\middleelementlookup\MiddleElementLookup.java | 1 |
请完成以下Java代码 | public int getM_ChangeRequest_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ChangeRequest_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_ChangeNotice getM_FixChangeNotice() throws RuntimeException
{
return (I_M_ChangeNotice)MTable.get(getCtx(), I_M_ChangeNotice.Table_Name)
.getPO(getM_FixChangeNotice_ID(), get_TrxName()); }
/** Set Fixed in.
@param M_FixChangeNotice_ID
Fixed in Change Notice
*/
public void setM_FixChangeNotice_ID (int M_FixChangeNotice_ID)
{
if (M_FixChangeNotice_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_FixChangeNotice_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_FixChangeNotice_ID, Integer.valueOf(M_FixChangeNotice_ID));
}
/** Get Fixed in.
@return Fixed in Change Notice
*/
public int getM_FixChangeNotice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_FixChangeNotice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
public org.eevolution.model.I_PP_Product_BOM getPP_Product_BOM() throws RuntimeException
{
return (org.eevolution.model.I_PP_Product_BOM)MTable.get(getCtx(), org.eevolution.model.I_PP_Product_BOM.Table_Name) | .getPO(getPP_Product_BOM_ID(), get_TrxName()); }
/** Set BOM & Formula.
@param PP_Product_BOM_ID
BOM & Formula
*/
public void setPP_Product_BOM_ID (int PP_Product_BOM_ID)
{
if (PP_Product_BOM_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Product_BOM_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Product_BOM_ID, Integer.valueOf(PP_Product_BOM_ID));
}
/** Get BOM & Formula.
@return BOM & Formula
*/
public int getPP_Product_BOM_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PP_Product_BOM_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_ChangeRequest.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Person extends User {
// ==============
// PRIVATE FIELDS
// ==============
// Person's first name
private String firstName;
//Person's last name
private String lastName;
// ==============
// PUBLIC METHODS
// ==============
/**
* Default Person constructor
*/
public Person() { }
/**
* Build a new Person with the passed id.
*/
public Person(Long id) {
this.setId(id);
}
/**
* @return the firstName | */
public String getFirstName() {
return firstName;
}
/**
* @return the lastName
*/
public String getLastName() {
return lastName;
}
/**
* @param firstName the firstName to set
*/
public void setFirstName(String firstName) {
this.firstName = firstName;
}
/**
* @param lastName the lastName to set
*/
public void setLastName(String lastName) {
this.lastName = lastName;
}
} // class Person | repos\spring-boot-samples-master\spring-boot-springdatajpa-inheritance\src\main\java\netgloo\models\Person.java | 2 |
请完成以下Java代码 | public class Path
{
public Node rnode;
public Node lnode;
public List<Integer> fvector;
public double cost;
public Path()
{
clear();
}
public void clear()
{
rnode = lnode = null;
fvector = null;
cost = 0.0;
}
/**
* 计算边的期望
*
* @param expected 输出期望
* @param Z 规范化因子
* @param size 标签个数
*/
public void calcExpectation(double[] expected, double Z, int size)
{
double c = Math.exp(lnode.alpha + cost + rnode.beta - Z); | for (int i = 0; fvector.get(i) != -1; i++)
{
int idx = fvector.get(i) + lnode.y * size + rnode.y;
expected[idx] += c;
}
}
public void add(Node _lnode, Node _rnode)
{
lnode = _lnode;
rnode = _rnode;
lnode.rpath.add(this);
rnode.lpath.add(this);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Path.java | 1 |
请完成以下Java代码 | public boolean isValidFromDate(final I_C_Fiscal_Representation fiscalRep)
{
return fiscalRep.getValidFrom().before(fiscalRep.getValidTo());
}
public boolean isValidToDate(final I_C_Fiscal_Representation fiscalRep)
{
return fiscalRep.getValidTo() == null || fiscalRep.getValidTo().after(fiscalRep.getValidFrom());
}
public void updateValidTo(final I_C_Fiscal_Representation fiscalRep)
{
fiscalRep.setValidTo(fiscalRep.getValidFrom());
}
public void updateValidFrom(final I_C_Fiscal_Representation fiscalRep)
{
fiscalRep.setValidFrom(fiscalRep.getValidTo());
}
@Override
public boolean hasFiscalRepresentation(@NonNull final CountryId countryId, @NonNull final OrgId orgId, @NonNull final Timestamp date)
{ | final ICompositeQueryFilter<I_C_Fiscal_Representation> validToFilter = queryBL.createCompositeQueryFilter(I_C_Fiscal_Representation.class)
.setJoinOr()
.addCompareFilter(I_C_Fiscal_Representation.COLUMN_ValidTo, CompareQueryFilter.Operator.GREATER_OR_EQUAL, date)
.addEqualsFilter(I_C_Fiscal_Representation.COLUMN_ValidTo, null);
return queryBL.createQueryBuilder(I_C_Fiscal_Representation.class)
.addEqualsFilter(I_C_Fiscal_Representation.COLUMNNAME_To_Country_ID, countryId)
.addEqualsFilter(I_C_Fiscal_Representation.COLUMNNAME_AD_Org_ID, orgId)
.addCompareFilter(I_C_Fiscal_Representation.COLUMN_ValidFrom, CompareQueryFilter.Operator.LESS_OR_EQUAL,date)
.filter(validToFilter)
.addOnlyActiveRecordsFilter()
.create()
.anyMatch();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\impl\FiscalRepresentationBL.java | 1 |
请完成以下Java代码 | public class DDOrderCandidateCreatedEvent extends AbstractDDOrderCandidateEvent
{
public static final String TYPE = "DDOrderCandidateCreatedEvent";
@JsonCreator
@Builder
public DDOrderCandidateCreatedEvent(
@JsonProperty("eventDescriptor") @NonNull final EventDescriptor eventDescriptor,
@JsonProperty("ddOrderCandidate") @NonNull final DDOrderCandidateData ddOrderCandidate)
{
super(eventDescriptor, ddOrderCandidate, null);
}
public static DDOrderCandidateCreatedEvent of(@NonNull final DDOrderCandidateData data,
@NonNull final UserId userId)
{ | return builder()
.eventDescriptor(EventDescriptor.ofClientOrgAndUserId(data.getClientAndOrgId(), userId))
.ddOrderCandidate(data)
.build();
}
public static Optional<DDOrderCandidateCreatedEvent> castIfApplies(@Nullable final AbstractDDOrderCandidateEvent event)
{
return event instanceof DDOrderCandidateCreatedEvent
? Optional.of((DDOrderCandidateCreatedEvent)event)
: Optional.empty();
}
@Override
public String getEventName() {return TYPE;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\ddordercandidate\DDOrderCandidateCreatedEvent.java | 1 |
请完成以下Java代码 | public void setCostCalculationMethod (final String CostCalculationMethod)
{
set_Value (COLUMNNAME_CostCalculationMethod, CostCalculationMethod);
}
@Override
public String getCostCalculationMethod()
{
return get_ValueAsString(COLUMNNAME_CostCalculationMethod);
}
@Override
public void setCostCalculation_Percentage (final @Nullable BigDecimal CostCalculation_Percentage)
{
set_Value (COLUMNNAME_CostCalculation_Percentage, CostCalculation_Percentage);
}
@Override
public BigDecimal getCostCalculation_Percentage()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CostCalculation_Percentage);
return bd != null ? bd : BigDecimal.ZERO;
}
/**
* CostDistributionMethod AD_Reference_ID=541712
* Reference name: CostDistributionMethod
*/
public static final int COSTDISTRIBUTIONMETHOD_AD_Reference_ID=541712;
/** Quantity = Q */
public static final String COSTDISTRIBUTIONMETHOD_Quantity = "Q";
/** Amount = A */
public static final String COSTDISTRIBUTIONMETHOD_Amount = "A";
@Override
public void setCostDistributionMethod (final String CostDistributionMethod)
{
set_Value (COLUMNNAME_CostDistributionMethod, CostDistributionMethod);
}
@Override
public String getCostDistributionMethod()
{
return get_ValueAsString(COLUMNNAME_CostDistributionMethod);
}
@Override
public I_C_OrderLine getCreated_OrderLine()
{
return get_ValueAsPO(COLUMNNAME_Created_OrderLine_ID, I_C_OrderLine.class);
}
@Override
public void setCreated_OrderLine(final I_C_OrderLine Created_OrderLine)
{
set_ValueFromPO(COLUMNNAME_Created_OrderLine_ID, I_C_OrderLine.class, Created_OrderLine);
}
@Override
public void setCreated_OrderLine_ID (final int Created_OrderLine_ID)
{
if (Created_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_Created_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Created_OrderLine_ID, Created_OrderLine_ID);
}
@Override
public int getCreated_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_Created_OrderLine_ID);
} | @Override
public void setIsSOTrx (final boolean IsSOTrx)
{
set_Value (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public boolean isSOTrx()
{
return get_ValueAsBoolean(COLUMNNAME_IsSOTrx);
}
@Override
public I_M_CostElement getM_CostElement()
{
return get_ValueAsPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class);
}
@Override
public void setM_CostElement(final I_M_CostElement M_CostElement)
{
set_ValueFromPO(COLUMNNAME_M_CostElement_ID, I_M_CostElement.class, M_CostElement);
}
@Override
public void setM_CostElement_ID (final int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, M_CostElement_ID);
}
@Override
public int getM_CostElement_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostElement_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Order_Cost.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class ConfigDataActivationContext {
private final @Nullable CloudPlatform cloudPlatform;
private final @Nullable Profiles profiles;
/**
* Create a new {@link ConfigDataActivationContext} instance before any profiles have
* been activated.
* @param environment the source environment
* @param binder a binder providing access to relevant config data contributions
*/
ConfigDataActivationContext(Environment environment, Binder binder) {
this.cloudPlatform = deduceCloudPlatform(environment, binder);
this.profiles = null;
}
/**
* Create a new {@link ConfigDataActivationContext} instance with the given
* {@link CloudPlatform} and {@link Profiles}.
* @param cloudPlatform the cloud platform
* @param profiles the profiles
*/
ConfigDataActivationContext(@Nullable CloudPlatform cloudPlatform, @Nullable Profiles profiles) {
this.cloudPlatform = cloudPlatform;
this.profiles = profiles;
}
private @Nullable CloudPlatform deduceCloudPlatform(Environment environment, Binder binder) {
for (CloudPlatform candidate : CloudPlatform.values()) {
if (candidate.isEnforced(binder)) {
return candidate;
}
}
return CloudPlatform.getActive(environment);
}
/**
* Return a new {@link ConfigDataActivationContext} with specific profiles.
* @param profiles the profiles
* @return a new {@link ConfigDataActivationContext} with specific profiles
*/
ConfigDataActivationContext withProfiles(Profiles profiles) {
return new ConfigDataActivationContext(this.cloudPlatform, profiles);
}
/**
* Return the active {@link CloudPlatform} or {@code null}.
* @return the active cloud platform | */
@Nullable CloudPlatform getCloudPlatform() {
return this.cloudPlatform;
}
/**
* Return profile information if it is available.
* @return profile information or {@code null}
*/
@Nullable Profiles getProfiles() {
return this.profiles;
}
@Override
public String toString() {
ToStringCreator creator = new ToStringCreator(this);
creator.append("cloudPlatform", this.cloudPlatform);
creator.append("profiles", this.profiles);
return creator.toString();
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataActivationContext.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Token {
private final String encoded;
private final String signature;
private final Map<String, Object> header;
private final Map<String, Object> claims;
public Token(String encoded) {
this.encoded = encoded;
int firstPeriod = encoded.indexOf('.');
int lastPeriod = encoded.lastIndexOf('.');
if (firstPeriod <= 0 || lastPeriod <= firstPeriod) {
throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN,
"JWT must have header, body and signature");
}
this.header = parseJson(encoded.substring(0, firstPeriod));
this.claims = parseJson(encoded.substring(firstPeriod + 1, lastPeriod));
this.signature = encoded.substring(lastPeriod + 1);
if (!StringUtils.hasLength(this.signature)) {
throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN,
"Token must have non-empty crypto segment");
}
}
private Map<String, Object> parseJson(String base64) {
try {
byte[] bytes = Base64.getUrlDecoder().decode(base64);
return JsonParserFactory.getJsonParser().parseMap(new String(bytes, StandardCharsets.UTF_8));
}
catch (RuntimeException ex) {
throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Token could not be parsed", ex);
}
}
public byte[] getContent() {
return this.encoded.substring(0, this.encoded.lastIndexOf('.')).getBytes();
}
public byte[] getSignature() {
return Base64.getUrlDecoder().decode(this.signature); | }
public String getSignatureAlgorithm() {
return getRequired(this.header, "alg", String.class);
}
public String getIssuer() {
return getRequired(this.claims, "iss", String.class);
}
public long getExpiry() {
return getRequired(this.claims, "exp", Integer.class).longValue();
}
@SuppressWarnings("unchecked")
public List<String> getScope() {
return getRequired(this.claims, "scope", List.class);
}
public String getKeyId() {
return getRequired(this.header, "kid", String.class);
}
@SuppressWarnings("unchecked")
private <T> T getRequired(Map<String, Object> map, String key, Class<T> type) {
Object value = map.get(key);
if (value == null) {
throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN, "Unable to get value from key " + key);
}
if (!type.isInstance(value)) {
throw new CloudFoundryAuthorizationException(Reason.INVALID_TOKEN,
"Unexpected value type from key " + key + " value " + value);
}
return (T) value;
}
@Override
public String toString() {
return this.encoded;
}
} | repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\Token.java | 2 |
请完成以下Java代码 | public Long getNewsCategoryId() {
return newsCategoryId;
}
public void setNewsCategoryId(Long newsCategoryId) {
this.newsCategoryId = newsCategoryId;
}
public String getNewsCoverImage() {
return newsCoverImage;
}
public void setNewsCoverImage(String newsCoverImage) {
this.newsCoverImage = newsCoverImage == null ? null : newsCoverImage.trim();
}
public Byte getNewsStatus() {
return newsStatus;
}
public void setNewsStatus(Byte newsStatus) {
this.newsStatus = newsStatus;
}
public Long getNewsViews() {
return newsViews;
}
public void setNewsViews(Long newsViews) {
this.newsViews = newsViews;
}
public Byte getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(Byte isDeleted) {
this.isDeleted = isDeleted;
}
public Date getCreateTime() { | return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Date getUpdateTime() {
return updateTime;
}
public void setUpdateTime(Date updateTime) {
this.updateTime = updateTime;
}
public String getNewsContent() {
return newsContent;
}
public void setNewsContent(String newsContent) {
this.newsContent = newsContent;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", newsId=").append(newsId);
sb.append(", newsTitle=").append(newsTitle);
sb.append(", newsCategoryId=").append(newsCategoryId);
sb.append(", newsCoverImage=").append(newsCoverImage);
sb.append(", newsStatus=").append(newsStatus);
sb.append(", newsViews=").append(newsViews);
sb.append(", isDeleted=").append(isDeleted);
sb.append(", createTime=").append(createTime);
sb.append(", updateTime=").append(updateTime);
sb.append("]");
return sb.toString();
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\entity\News.java | 1 |
请完成以下Java代码 | protected Integer parseAndValidate(String historyTimeToLiveString, String definitionKey, boolean skipEnforceTtl) throws NotValidException {
HTTLParsedResult result = new HTTLParsedResult(historyTimeToLiveString);
if (!skipEnforceTtl) {
if (result.isInValidAgainstConfig()) {
throw LOG.logErrorNoTTLConfigured();
}
if (result.hasLongerModelValueThanGlobalConfig()) {
LOG.logModelHTTLLongerThanGlobalConfiguration(definitionKey);
}
}
return result.valueAsInteger;
}
protected class HTTLParsedResult {
protected final boolean systemDefaultConfigWillBeUsed;
protected final String value;
protected final Integer valueAsInteger;
public HTTLParsedResult(String historyTimeToLiveString) {
this.systemDefaultConfigWillBeUsed = (historyTimeToLiveString == null); | this.value = systemDefaultConfigWillBeUsed ? httlConfigValue : historyTimeToLiveString;
this.valueAsInteger = ParseUtil.parseHistoryTimeToLive(value);
}
protected boolean isInValidAgainstConfig() {
return enforceNonNullValue && (valueAsInteger == null);
}
protected boolean hasLongerModelValueThanGlobalConfig() {
return !systemDefaultConfigWillBeUsed // only values originating from models make sense to be logged
&& valueAsInteger != null
&& httlConfigValue != null && !httlConfigValue.isEmpty()
&& valueAsInteger > ParseUtil.parseHistoryTimeToLive(httlConfigValue);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoryTimeToLiveParser.java | 1 |
请完成以下Java代码 | public class AuthenticationDto {
protected String userId;
protected List<String> authorizedApps;
// transformer ///////////////////////
public static AuthenticationDto fromAuthentication(Authentication authentication) {
AuthenticationDto dto = new AuthenticationDto();
dto.setUserId(authentication.getIdentityId());
if (authentication instanceof UserAuthentication) {
dto.setAuthorizedApps(new ArrayList<String>(((UserAuthentication) authentication).getAuthorizedApps()));
}
return dto;
}
// getter / setters /////////////////
public String getUserId() { | return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public void setAuthorizedApps(List<String> authorizedApps) {
this.authorizedApps = authorizedApps;
}
public List<String> getAuthorizedApps() {
return authorizedApps;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\webapp\impl\security\auth\AuthenticationDto.java | 1 |
请完成以下Java代码 | public boolean isOneConfigurationPerPI()
{
return oneConfigurationPerPI;
}
@Override
public boolean isAllowDifferentCapacities()
{
return allowDifferentCapacities;
}
@Override
public void setAllowDifferentCapacities(final boolean allowDifferentCapacities)
{
this.allowDifferentCapacities = allowDifferentCapacities;
}
@Override
public boolean isAllowInfiniteCapacity()
{
return allowInfiniteCapacity;
}
@Override
public void setAllowInfiniteCapacity(final boolean allowInfiniteCapacity)
{
this.allowInfiniteCapacity = allowInfiniteCapacity; | }
@Override
public boolean isAllowAnyPartner()
{
return allowAnyPartner;
}
@Override
public void setAllowAnyPartner(final boolean allowAnyPartner)
{
this.allowAnyPartner = allowAnyPartner;
}
@Override
public int getM_Product_Packaging_ID()
{
return packagingProductId;
}
@Override
public void setM_Product_Packaging_ID(final int packagingProductId)
{
this.packagingProductId = packagingProductId > 0 ? packagingProductId : -1;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductQuery.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JacksonUtil {
private static ObjectMapper mapper = new ObjectMapper();
public static String bean2Json(Object obj) {
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
e.printStackTrace();
return null;
}
}
// public static <T> T json2Bean(String jsonStr, Class<T> objClass) {
// try {
// return mapper.readValue(jsonStr, objClass); | // } catch (IOException e) {
// e.printStackTrace();
// return null;
// }
// }
public static <T> T json2Bean(String jsonStr, TypeReference<T> typeReference) {
try {
return mapper.readValue(jsonStr, typeReference);
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
} | repos\SpringBootBucket-master\springboot-cxf\src\main\java\com\xncoding\webservice\util\JacksonUtil.java | 2 |
请完成以下Java代码 | public Set<LocalDateTime> explodeForward(final LocalDateTime date)
{
return days.stream()
.map(day -> withDayOfMonth(date, day))
.filter(dayDate -> dayDate.compareTo(date) >= 0) // Skip all dates which are before our given date
.collect(ImmutableSet.toImmutableSet());
}
@Override
public Set<LocalDateTime> explodeBackward(final LocalDateTime date)
{
return days.stream()
.map(day -> withDayOfMonth(date, day))
.filter(dayDate -> dayDate.compareTo(date) <= 0) // Skip all dates which are after our given date
.collect(ImmutableSet.toImmutableSet()); | }
private static final LocalDateTime withDayOfMonth(final LocalDateTime date, final int dayOfMonth)
{
if (dayOfMonth >= 31)
{
return date.with(TemporalAdjusters.lastDayOfMonth());
}
else
{
return date.withDayOfMonth(dayOfMonth);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\generator\DaysOfMonthExploder.java | 1 |
请完成以下Java代码 | public class Tutorial {
private final Integer tutId;
private final String title;
private final String description;
private final String author;
public Tutorial(Integer tutId, String title, String description, String author) {
this.tutId = tutId;
this.title = title;
this.description = description;
this.author = author;
}
public Integer getTutId() { | return tutId;
}
public String getTitle() {
return title;
}
public String getDescription() {
return description;
}
public String getAuthor() {
return author;
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-velocity\src\main\java\com\baeldung\mvc\velocity\domain\Tutorial.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public User getUser(@PathVariable Long id) {
return users.get(id);
}
@ApiOperation(value = "更新用户信息", notes = "根据用户ID更新信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "用户ID", required = true, dataType = "Long", paramType = "query"),
@ApiImplicitParam(name = "name", value = "用户名", required = true, dataType = "String", paramType = "query"),
@ApiImplicitParam(name = "age", value = "年龄", required = true, dataType = "String", paramType = "query")
})
@RequestMapping(value = "/{id}", method = RequestMethod.PUT)
public BaseResult<User> putUser(@PathVariable Long id, @ApiIgnore User user) {
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge()); | users.put(id, u);
return BaseResult.successWithData(u);
}
@RequestMapping(value = "/{id}", method = RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
users.remove(id);
return "success";
}
@RequestMapping(value = "/ignoreMe/{id}", method = RequestMethod.DELETE)
public String ignoreMe(@PathVariable Long id) {
users.remove(id);
return "success";
}
} | repos\spring-boot-leaning-master\2.x_42_courses\第 2-9 课:Spring Boot 中使用 Swagger2 构建 RESTful APIs\spring-boot-swagger\src\main\java\com\neo\controller\UserController.java | 2 |
请完成以下Java代码 | public List<POSOrder> getOpenOrders(
@NonNull final POSTerminalId posTerminalId,
@NonNull final UserId userId,
@Nullable final Set<POSOrderExternalId> onlyOrderExternalIds)
{
return ordersService.list(POSOrderQuery.builder()
.posTerminalId(posTerminalId)
.cashierId(userId)
.isOpen(true)
.onlyOrderExternalIds(onlyOrderExternalIds)
.build());
}
public POSOrder changeStatusTo(
@NonNull final POSTerminalId posTerminalId,
@NonNull final POSOrderExternalId externalId,
@NonNull final POSOrderStatus nextStatus,
@NonNull final UserId userId)
{
return ordersService.changeStatusTo(posTerminalId, externalId, nextStatus, userId);
}
public POSOrder updateOrderFromRemote(
@NonNull final RemotePOSOrder remoteOrder,
@NonNull final UserId userId)
{
return ordersService.updateOrderFromRemote(remoteOrder, userId);
}
public POSOrder checkoutPayment(@NonNull POSPaymentCheckoutRequest request)
{
return ordersService.checkoutPayment(request); | }
public POSOrder refundPayment(
@NonNull final POSTerminalId posTerminalId,
@NonNull final POSOrderExternalId posOrderExternalId,
@NonNull final POSPaymentExternalId posPaymentExternalId,
@NonNull final UserId userId)
{
return ordersService.refundPayment(posTerminalId, posOrderExternalId, posPaymentExternalId, userId);
}
public Optional<Resource> getReceiptPdf(@NonNull final POSOrderExternalId externalId)
{
return ordersService.getReceiptPdf(externalId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSService.java | 1 |
请完成以下Java代码 | public String getName() {
return this.path;
}
public Map<String, String> getAttributes() {
return attributes;
}
public String getAttribute(String name) {
return attributes.get(name);
}
public void addAttribute(String name, String value) {
attributes.put(name, value);
} | public Map<String, String> getDirectives() {
return directives;
}
public String getDirective(String name) {
return directives.get(name);
}
public void addDirective(String name, String value) {
directives.put(name, value);
}
}
} | repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\HeaderParser.java | 1 |
请完成以下Java代码 | protected HistoricProcessInstanceEntityManager getHistoricProcessInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricProcessInstanceEntityManager();
}
protected HistoricDetailEntityManager getHistoricDetailEntityManager() {
return getProcessEngineConfiguration().getHistoricDetailEntityManager();
}
protected HistoricActivityInstanceEntityManager getHistoricActivityInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricActivityInstanceEntityManager();
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricVariableInstanceEntityManager();
} | protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() {
return getProcessEngineConfiguration().getHistoricTaskInstanceEntityManager();
}
protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getProcessEngineConfiguration().getHistoricIdentityLinkEntityManager();
}
protected AttachmentEntityManager getAttachmentEntityManager() {
return getProcessEngineConfiguration().getAttachmentEntityManager();
}
protected CommentEntityManager getCommentEntityManager() {
return getProcessEngineConfiguration().getCommentEntityManager();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\AbstractManager.java | 1 |
请完成以下Java代码 | public class AesDesDefaultEncrypt extends BaseEncrypt {
private static final String DEFAULT_SEC = "FMjDV69Xkd6y9HVVK";
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
private String password;
private SecretKeySpec secretKeySpec;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public AesDesDefaultEncrypt() throws NoSuchAlgorithmException {
log.info("init encrypt by default passwd");
this.password = DEFAULT_SEC;
this.secretKeySpec = getSecretKey(this.password);
}
public AesDesDefaultEncrypt(String password) throws NoSuchAlgorithmException {
if (StringUtils.isEmpty(password)) {
throw new IllegalArgumentException("password should not be null!");
}
log.info("init encrypt by custom passwd");
this.password = password;
this.secretKeySpec = getSecretKey(password);
}
@Override
public String encrypt(String value) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
byte[] content = value.getBytes("UTF-8");
byte[] encryptData = cipher.doFinal(content);
return Hex.bytesToHexString(encryptData);
} catch (Exception e) {
log.error("AES加密时出现问题,密钥为:{}", password);
throw new IllegalStateException("AES加密时出现问题" + e.getMessage(), e);
}
} | @Override
public String decrypt(String value) {
if (StringUtils.isEmpty(value)) {
return "";
}
try {
byte[] encryptData = Hex.hexStringToBytes(value);
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] content = cipher.doFinal(encryptData);
return new String(content, "UTF-8");
} catch (Exception e) {
log.error("AES解密时出现问题,密钥为:{},密文为:{}", password, value);
throw new IllegalStateException("AES解密时出现问题" + e.getMessage(), e);
}
}
private static SecretKeySpec getSecretKey(final String password) throws NoSuchAlgorithmException {
//返回生成指定算法密钥生成器的 KeyGenerator 对象
KeyGenerator kg = KeyGenerator.getInstance(KEY_ALGORITHM);
//AES 要求密钥长度为 128
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(password.getBytes());
kg.init(128, random);
//生成一个密钥
SecretKey secretKey = kg.generateKey();
// 转换为AES专用密钥
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
}
} | repos\spring-boot-quick-master\mybatis-crypt-plugin\src\main\java\com\quick\db\crypt\encrypt\AesDesDefaultEncrypt.java | 1 |
请完成以下Java代码 | public Properties getCtx()
{
return ctx;
}
@Override
public int getAD_Client_ID()
{
return orderLine.getAD_Client_ID();
}
@Override
public int getAD_Org_ID()
{
return orderLine.getAD_Org_ID();
}
@Override
public int getM_Product_ID() | {
return orderLine.getM_Product_ID();
}
@Override
public int getM_Warehouse_ID()
{
return orderLine.getM_Warehouse_ID();
}
@Override
public I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return orderLine.getM_AttributeSetInstance();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\OrderLineReceiptScheduleProducer.java | 1 |
请完成以下Java代码 | public void rebrandStore(@PathVariable final Integer storeId, @RequestBody RebrandStoreDto rebrandStoreDto) {
storeService.rebrandStore(storeId, rebrandStoreDto.name);
}
@PostMapping(value = "/stores/{storeId}/products/{productId}/price", consumes = MediaType.APPLICATION_JSON_VALUE)
public void updateProductPrice(@PathVariable final Integer productId, @PathVariable String storeId, @RequestBody UpdatePriceDto priceDto) {
storeService.updateProductPrice(productId, priceDto.price);
}
@GetMapping("/products/{productId}/changes")
public String getProductChanges(@PathVariable int productId) {
Product product = storeService.findProductById(productId);
QueryBuilder jqlQuery = QueryBuilder.byInstance(product);
Changes changes = javers.findChanges(jqlQuery.build());
return javers.getJsonConverter().toJson(changes);
}
@GetMapping("/products/snapshots")
public String getProductSnapshots() {
QueryBuilder jqlQuery = QueryBuilder.byClass(Product.class);
List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build());
return javers.getJsonConverter().toJson(snapshots);
}
@GetMapping("/stores/{storeId}/shadows") | public String getStoreShadows(@PathVariable int storeId) {
Store store = storeService.findStoreById(storeId);
JqlQuery jqlQuery = QueryBuilder.byInstance(store)
.withChildValueObjects().build();
List<Shadow<Store>> shadows = javers.findShadows(jqlQuery);
return javers.getJsonConverter().toJson(shadows.get(0));
}
@GetMapping("/stores/snapshots")
public String getStoresSnapshots() {
QueryBuilder jqlQuery = QueryBuilder.byClass(Store.class);
List<CdoSnapshot> snapshots = javers.findSnapshots(jqlQuery.build());
return javers.getJsonConverter().toJson(snapshots);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\javers\web\StoreController.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.