instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public class SecurityConfig {
private final UserDetailsService userDetailsService;
public SecurityConfig(UserDetailsService userDetailsService) {
this.userDetailsService = userDetailsService;
}
@Bean
public AuthenticationManager customAuthenticationManager(HttpSecurity http) throws Exception {
AuthenticationManagerBuilder authenticationManagerBuilder = http.getSharedObject(AuthenticationManagerBuilder.class);
authenticationManagerBuilder.userDetailsService(userDetailsService)
.passwordEncoder(bCryptPasswordEncoder());
return authenticationManagerBuilder.build();
}
@Bean
|
public BCryptPasswordEncoder bCryptPasswordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(AbstractHttpConfigurer::disable)
.authorizeHttpRequests(Customizer.withDefaults())
.httpBasic(Customizer.withDefaults())
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry.anyRequest().permitAll())
.sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS));
return http.build();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\mongoauth\config\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public GarnishmentType1Choice getCdOrPrtry() {
return cdOrPrtry;
}
/**
* Sets the value of the cdOrPrtry property.
*
* @param value
* allowed object is
* {@link GarnishmentType1Choice }
*
*/
public void setCdOrPrtry(GarnishmentType1Choice value) {
this.cdOrPrtry = value;
}
/**
* Gets the value of the issr property.
*
* @return
* possible object is
* {@link String }
*
*/
|
public String getIssr() {
return issr;
}
/**
* Sets the value of the issr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIssr(String value) {
this.issr = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\GarnishmentType1.java
| 1
|
请完成以下Spring Boot application配置
|
##########################################################
################## 所有profile共有的配置 #################
##########################################################
################### spring配置 ###################
spring:
profiles:
active: dev
---
#####################################################################
######################## 开发环境profile ##########################
#####################################################################
spring:
profiles: dev
logging:
level:
ROOT: INFO
com:
xncoding: DEBUG
file: E:/logs/app.log
---
################################################
|
#####################
######################## 测试环境profile ##########################
#####################################################################
spring:
profiles: test
logging:
level:
ROOT: INFO
com:
xncoding: DEBUG
file: /var/logs/app.log
|
repos\SpringBootBucket-master\springboot-async\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
private static DocumentPath toDocumentPath(final ViewRowAttributesKey key)
{
final DocumentId documentTypeId = key.getHuId();
final DocumentId huEditorRowId = key.getHuEditorRowId();
return DocumentPath.rootDocumentPath(DocumentType.ViewRecordAttributes, documentTypeId, huEditorRowId);
}
private IAttributeStorageFactory getAttributeStorageFactory()
{
return _attributeStorageFactory.get();
}
private IAttributeStorageFactory createAttributeStorageFactory()
{
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
|
return attributeStorageFactoryService.createHUAttributeStorageFactory(storageFactory);
}
@Override
public void invalidateAll()
{
//
// Destroy AttributeStorageFactory
_attributeStorageFactory.forget();
//
// Destroy attribute documents
rowAttributesByKey.clear();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowAttributesProvider.java
| 1
|
请完成以下Java代码
|
public void setType(String type) {
this.type = type;
}
public ModelApiResponse message(String message) {
this.message = message;
return this;
}
/**
* Get message
* @return message
**/
@ApiModelProperty(value = "")
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
ModelApiResponse _apiResponse = (ModelApiResponse) o;
return Objects.equals(this.code, _apiResponse.code) &&
Objects.equals(this.type, _apiResponse.type) &&
Objects.equals(this.message, _apiResponse.message);
}
@Override
|
public int hashCode() {
return Objects.hash(code, type, message);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class ModelApiResponse {\n");
sb.append(" code: ").append(toIndentedString(code)).append("\n");
sb.append(" type: ").append(toIndentedString(type)).append("\n");
sb.append(" message: ").append(toIndentedString(message)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\ModelApiResponse.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CustomerService {
private static final Logger LOGGER = LoggerFactory.getLogger(CustomerService.class);
private final Map<String, Customer> customerRepoMap = new HashMap<>();
public List<Customer> createCustomers(List<Customer> customers) {
return customers.stream()
.map(this::createCustomer)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(toList());
}
public Optional<Customer> createCustomer(Customer customer) {
LOGGER.info("Creating Customer : {}", customer);
if (!customerRepoMap.containsKey(customer.getEmail()) && customer.getId() == 0) {
Customer customerToCreate = new Customer(customerRepoMap.size() + 1, customer.getName(), customer.getEmail());
customerToCreate.setAddress(customer.getAddress());
customerRepoMap.put(customerToCreate.getEmail(), customerToCreate);
LOGGER.info("Created Customer : {}", customerToCreate);
return Optional.of(customerToCreate);
}
return Optional.empty();
}
public Optional<Customer> updateCustomer(Customer customer) {
LOGGER.info("Updating Customer : {}", customer);
Customer customerToUpdate = customerRepoMap.get(customer.getEmail());
if (customerToUpdate != null && customerToUpdate.getId() == customer.getId()) {
|
customerToUpdate.setName(customer.getName());
customerToUpdate.setAddress(customer.getAddress());
LOGGER.info("Updated Customer : {}", customerToUpdate);
}
return Optional.ofNullable(customerToUpdate);
}
public Optional<Customer> deleteCustomer(Customer customer) {
LOGGER.info("Deleting Customer : {}", customer);
Customer customerToDelete = customerRepoMap.get(customer.getEmail());
if (customerToDelete != null && customerToDelete.getId() == customer.getId()) {
customerRepoMap.remove(customer.getEmail());
LOGGER.info("Deleted Customer : {}", customerToDelete);
}
return Optional.ofNullable(customerToDelete);
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\bulkandbatchapi\service\CustomerService.java
| 2
|
请完成以下Java代码
|
public boolean isReadWrite()
{
return readWrite;
} // getReadWrite
/**
* Set Mandatory
* @param mandatory
*/
@Override
public void setMandatory (final boolean mandatory)
{
if (this.m_mandatory == mandatory)
{
return;
}
m_mandatory = mandatory;
setBackground(false);
} // setMandatory
/**
* Get Mandatory
* @return true if mandatory
*/
@Override
public boolean isMandatory()
{
return m_mandatory;
} // isMandatory
/**
* Set Background - nop
* @param color
*/
@Override
public void setBackground(Color color)
{
}
/**
* Set Background
* @param error
*/
@Override
public void setBackground(boolean error)
{
if (error)
super.setBackground(AdempierePLAF.getFieldBackground_Error());
else if (!isReadWrite())
super.setBackground(AdempierePLAF.getFieldBackground_Inactive());
else if (isMandatory())
super.setBackground(AdempierePLAF.getFieldBackground_Mandatory());
else
super.setBackground(AdempierePLAF.getFieldBackground_Normal());
}
/**
* Property Change
* @param evt
*/
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(org.compiere.model.GridField.PROPERTY))
setValue(evt.getNewValue());
// metas: request focus (2009_0027_G131)
if (evt.getPropertyName().equals(org.compiere.model.GridField.REQUEST_FOCUS))
|
requestFocus();
// metas end
} // propertyChange
/**
* Start dialog and set value
*/
private final void onButtonPressed()
{
try
{
// Show the dialog
final VImageDialog vid = new VImageDialog(Env.getWindow(m_WindowNo), m_WindowNo, m_mImage);
vid.setVisible(true);
// Do nothing if user canceled (i.e. closed the window)
if (vid.isCanceled())
{
return;
}
final int AD_Image_ID = vid.getAD_Image_ID();
final Integer newValue = AD_Image_ID > 0 ? AD_Image_ID : null;
//
m_mImage = null; // force reload
setValue(newValue); // set explicitly
//
try
{
fireVetoableChange(m_columnName, null, newValue);
}
catch (PropertyVetoException pve) {}
}
catch (Exception e)
{
Services.get(IClientUI.class).error(m_WindowNo, e);
}
} // actionPerformed
// Field for Value Preference
private GridField m_mField = null;
/**
* Set Field/WindowNo for ValuePreference (NOP)
* @param mField
*/
@Override
public void setField (GridField mField)
{
m_mField = mField;
} // setField
@Override
public GridField getField() {
return m_mField;
}
// metas
@Override
public boolean isAutoCommit()
{
return true;
}
} // VImage
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VImage.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<PmsOperatorRole> listByOperatorId(Long operatorId) {
return super.getSessionTemplate().selectList(getStatement("listByOperatorId"), operatorId);
}
/**
* 根据角色ID查找该操作员关联的操作员.
*
* @param roleId
* @return
*/
public List<PmsOperatorRole> listByRoleId(Long roleId) {
return super.getSessionTemplate().selectList(getStatement("listByRoleId"), roleId);
}
/**
* 根据操作员ID删除与角色的关联记录.
*
* @param operatorId
* .
*/
public void deleteByOperatorId(Long operatorId) {
super.getSessionTemplate().delete(getStatement("deleteByOperatorId"), operatorId);
}
/**
* 根据角色ID删除操作员与角色的关联关系.
*
* @param roleId
* .
|
*/
public void deleteByRoleId(Long roleId) {
super.getSessionTemplate().delete(getStatement("deleteByRoleId"), roleId);
}
/**
* 根据角色ID和操作员ID删除关联数据(用于更新操作员的角色).
*
* @param roleId
* 角色ID.
* @param operatorId
* 操作员ID.
*/
@Override
public void deleteByRoleIdAndOperatorId(Long roleId, Long operatorId) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("roleId", roleId);
paramMap.put("operatorId", operatorId);
super.getSessionTemplate().delete(getStatement("deleteByRoleIdAndOperatorId"), paramMap);
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\dao\impl\PmsOperatorRoleDaoImpl.java
| 2
|
请完成以下Java代码
|
public class ExpiryAttributeUpdater
{
private final transient IAttributeSetInstanceAwareFactoryService attributeSetInstanceAwareFactoryService = Services.get(IAttributeSetInstanceAwareFactoryService.class);
private Object sourceModel;
private final transient IAttributeSetInstanceBL attributeSetInstanceBL = Services.get(IAttributeSetInstanceBL.class);
private final transient IAttributesBL attributesBL = Services.get(IAttributesBL.class);
public void updateASI()
{
final Object sourceModel = getSourceModel();
final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(sourceModel);
if (asiAware == null)
{
return;
}
if (asiAware.getM_Product_ID() <= 0)
{
return;
}
final IAttributeDAO attributesRepo = Services.get(IAttributeDAO.class);
final AttributeId expiredAttribute = attributesRepo.retrieveActiveAttributeIdByValueOrNull(HUAttributeConstants.ATTR_Expired);
if (expiredAttribute == null)
{
return;
}
final ProductId productId = ProductId.ofRepoId(asiAware.getM_Product_ID());
final I_M_Attribute attribute = attributesBL.getAttributeOrNull(productId, expiredAttribute);
if (attribute == null)
{
return;
}
attributeSetInstanceBL.getCreateASI(asiAware);
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoId(asiAware.getM_AttributeSetInstance_ID());
final I_M_AttributeInstance ai = attributeSetInstanceBL.getAttributeInstance(asiId, expiredAttribute);
|
if (ai != null)
{
// If it was set, just leave it as it is
return;
}
attributeSetInstanceBL.getCreateAttributeInstance(asiId, expiredAttribute);
}
public ExpiryAttributeUpdater setSourceModel(final Object sourceModel)
{
this.sourceModel = sourceModel;
return this;
}
private Object getSourceModel()
{
Check.assumeNotNull(sourceModel, "sourceModel not null");
return sourceModel;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\ExpiryAttributeUpdater.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setDateTrx (final java.sql.Timestamp DateTrx)
{
set_Value (COLUMNNAME_DateTrx, DateTrx);
}
@Override
public java.sql.Timestamp getDateTrx()
{
return get_ValueAsTimestamp(COLUMNNAME_DateTrx);
}
@Override
public void setDocumentNo (final java.lang.String DocumentNo)
{
set_Value (COLUMNNAME_DocumentNo, DocumentNo);
}
@Override
public java.lang.String getDocumentNo()
{
return get_ValueAsString(COLUMNNAME_DocumentNo);
}
|
@Override
public void setIsClosed (final boolean IsClosed)
{
set_Value (COLUMNNAME_IsClosed, IsClosed);
}
@Override
public boolean isClosed()
{
return get_ValueAsBoolean(COLUMNNAME_IsClosed);
}
@Override
public void setOpeningNote (final @Nullable java.lang.String OpeningNote)
{
set_Value (COLUMNNAME_OpeningNote, OpeningNote);
}
@Override
public java.lang.String getOpeningNote()
{
return get_ValueAsString(COLUMNNAME_OpeningNote);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java-gen\de\metas\pos\repository\model\X_C_POS_Journal.java
| 2
|
请完成以下Java代码
|
public void replayApiRequests(@NonNull final ApiRequestIterator apiRequestIterator)
{
apiRequestIterator.forEach(this::replayAction);
}
@VisibleForTesting
public void replayApiRequests(@NonNull final ImmutableList<ApiRequestAudit> apiRequestAuditTimeSortedList)
{
apiRequestAuditTimeSortedList.forEach(this::replayActionNoFailing);
}
private void replayActionNoFailing(@NonNull final ApiRequestAudit apiRequestAudit)
{
final ApiAuditLoggable loggable = apiAuditService.createLogger(apiRequestAudit.getIdNotNull(), apiRequestAudit.getUserId());
try (final IAutoCloseable loggableRestorer = Loggables.temporarySetLoggable(loggable))
{
Loggables.addLog("Replaying request!");
replayAction(apiRequestAudit);
}
catch (final Exception e)
{
loggable.addLog("Error while trying to replay the request:" + e.getMessage(), e);
}
finally
|
{
loggable.flush();
}
}
private void replayAction(@NonNull final ApiRequestAudit apiRequestAudit)
{
try
{
final ApiResponse apiResponse = apiAuditService.executeHttpCall(apiRequestAudit);
final ApiAuditConfig apiAuditConfig = apiAuditConfigRepository.getConfigById(apiRequestAudit.getApiAuditConfigId());
apiAuditService.auditResponse(apiAuditConfig, apiResponse, apiRequestAudit);
}
catch (final Exception e)
{
apiAuditService.updateRequestStatus(Status.ERROR, apiRequestAudit);
throw e;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\ApiRequestReplayService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ParamController extends BladeController {
private IParamService paramService;
/**
* 详情
*/
@GetMapping("/detail")
@ApiOperationSupport(order = 1)
@Operation(summary = "详情", description = "传入param")
public R<Param> detail(Param param) {
Param detail = paramService.getOne(Condition.getQueryWrapper(param));
return R.data(detail);
}
/**
* 分页
*/
@GetMapping("/list")
@Parameters({
@Parameter(name = "paramName", description = "参数名称", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "paramKey", description = "参数键名", in = ParameterIn.QUERY, schema = @Schema(type = "string")),
@Parameter(name = "paramValue", description = "参数键值", in = ParameterIn.QUERY, schema = @Schema(type = "string"))
})
@ApiOperationSupport(order = 2)
@Operation(summary = "分页", description = "传入param")
@PreAuth(RoleConstant.HAS_ROLE_ADMIN)
public R<IPage<Param>> list(@Parameter(hidden = true) @RequestParam Map<String, Object> param, Query query) {
IPage<Param> pages = paramService.page(Condition.getPage(query), Condition.getQueryWrapper(param, Param.class));
return R.data(pages);
}
/**
* 新增或修改
*/
@PostMapping("/submit")
@ApiOperationSupport(order = 3)
@Operation(summary = "新增或修改", description = "传入param")
|
public R submit(@Valid @RequestBody Param param) {
return R.status(paramService.saveOrUpdate(param));
}
/**
* 删除
*/
@PostMapping("/remove")
@ApiOperationSupport(order = 4)
@Operation(summary = "逻辑删除", description = "传入ids")
public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) {
return R.status(paramService.deleteLogic(Func.toLongList(ids)));
}
}
|
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\ParamController.java
| 2
|
请完成以下Java代码
|
public class EDI_Desadv_Pack_PrintSSCCLabels extends JavaProcess implements IProcessPrecondition
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final IDesadvBL desadvBL = Services.get(IDesadvBL.class);
@Override
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
if (context.getSelectionSize().isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@Override
protected String doIt() throws Exception
{
final IQueryFilter<I_EDI_Desadv_Pack> selectedRecordsFilter = getProcessInfo()
.getQueryFilterOrElse(ConstantQueryFilter.of(false));
|
final Set<EDIDesadvPackId> list = queryBL
.createQueryBuilder(I_EDI_Desadv_Pack.class)
.filter(selectedRecordsFilter)
.create()
.stream()
.map(I_EDI_Desadv_Pack::getEDI_Desadv_Pack_ID)
.map(EDIDesadvPackId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
final ReportResultData reportResult = desadvBL.printSSCC18_Labels(getCtx(), list);
getProcessInfo().getResult().setReportData(reportResult);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_Desadv_Pack_PrintSSCCLabels.java
| 1
|
请完成以下Java代码
|
public void setOverrides_Window_ID (final int Overrides_Window_ID)
{
if (Overrides_Window_ID < 1)
set_Value (COLUMNNAME_Overrides_Window_ID, null);
else
set_Value (COLUMNNAME_Overrides_Window_ID, Overrides_Window_ID);
}
@Override
public int getOverrides_Window_ID()
{
return get_ValueAsInt(COLUMNNAME_Overrides_Window_ID);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
/**
* WindowType AD_Reference_ID=108
* Reference name: AD_Window Types
*/
public static final int WINDOWTYPE_AD_Reference_ID=108;
/** Single Record = S */
public static final String WINDOWTYPE_SingleRecord = "S";
/** Maintain = M */
public static final String WINDOWTYPE_Maintain = "M";
/** Transaktion = T */
public static final String WINDOWTYPE_Transaktion = "T";
/** Query Only = Q */
public static final String WINDOWTYPE_QueryOnly = "Q";
@Override
public void setWindowType (final java.lang.String WindowType)
{
set_Value (COLUMNNAME_WindowType, WindowType);
}
@Override
public java.lang.String getWindowType()
{
return get_ValueAsString(COLUMNNAME_WindowType);
}
|
@Override
public void setWinHeight (final int WinHeight)
{
set_Value (COLUMNNAME_WinHeight, WinHeight);
}
@Override
public int getWinHeight()
{
return get_ValueAsInt(COLUMNNAME_WinHeight);
}
@Override
public void setWinWidth (final int WinWidth)
{
set_Value (COLUMNNAME_WinWidth, WinWidth);
}
@Override
public int getWinWidth()
{
return get_ValueAsInt(COLUMNNAME_WinWidth);
}
@Override
public void setZoomIntoPriority (final int ZoomIntoPriority)
{
set_Value (COLUMNNAME_ZoomIntoPriority, ZoomIntoPriority);
}
@Override
public int getZoomIntoPriority()
{
return get_ValueAsInt(COLUMNNAME_ZoomIntoPriority);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Window.java
| 1
|
请完成以下Java代码
|
/* package */ static String convertDecimalPatternToPG(final String formatPattern)
{
if (formatPattern == null || formatPattern.isEmpty())
{
return null;
}
final StringBuilder pgFormatPattern = new StringBuilder(formatPattern.length() + 2);
pgFormatPattern.append("FM"); // fill mode (suppress padding blanks and trailing zeroes)
for (int i = 0; i < formatPattern.length(); i++)
{
final char ch = formatPattern.charAt(i);
// Case: chars that don't need to be translated because have the same meaning
if (ch == '0' || ch == '.' || ch == ',')
{
pgFormatPattern.append(ch);
}
// Case: # - Digit, zero shows as absent
// Convert to: 9 - value with the specified number of digits
else if (ch == '#')
{
pgFormatPattern.append('9');
}
// Case: invalid char / char that we cannot convert (atm)
else
{
return null;
}
}
return pgFormatPattern.toString();
}
|
/**
* Return number as string for INSERT statements with correct precision
*
* @param number number
* @param displayType display Type
* @return number as string
*/
public static String TO_NUMBER(final BigDecimal number, final int displayType)
{
if (number == null)
{
return "NULL";
}
BigDecimal result = number;
final int scale = DisplayType.getDefaultPrecision(displayType);
if (scale > number.scale())
{
result = number.setScale(scale, RoundingMode.HALF_UP);
}
return result.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\Database.java
| 1
|
请完成以下Java代码
|
private static void jsonMembers(Environment environment, @Nullable StackTracePrinter stackTracePrinter,
ContextPairs contextPairs, JsonWriter.Members<LogEvent> members) {
Extractor extractor = new Extractor(stackTracePrinter);
members.add("@timestamp", LogEvent::getInstant).as(ElasticCommonSchemaStructuredLogFormatter::asTimestamp);
members.add("log").usingMembers((log) -> {
log.add("level", LogEvent::getLevel).as(Level::name);
log.add("logger", LogEvent::getLoggerName);
});
members.add("process").usingMembers((process) -> {
process.add("pid", environment.getProperty("spring.application.pid", Long.class)).whenNotNull();
process.add("thread").usingMembers((thread) -> thread.add("name", LogEvent::getThreadName));
});
ElasticCommonSchemaProperties.get(environment).jsonMembers(members);
members.add("message", LogEvent::getMessage).as(StructuredMessage::get);
members.from(LogEvent::getContextData)
.usingPairs(contextPairs.nested(ElasticCommonSchemaStructuredLogFormatter::addContextDataPairs));
members.from(LogEvent::getThrown)
.whenNotNull()
.usingMembers((thrownMembers) -> thrownMembers.add("error").usingMembers((error) -> {
error.add("type", ObjectUtils::nullSafeClassName);
error.add("message", Throwable::getMessage);
error.add("stack_trace", extractor::stackTrace);
}));
members.add("tags", LogEvent::getMarker)
.whenNotNull()
.as(ElasticCommonSchemaStructuredLogFormatter::getMarkers)
.whenNotEmpty();
members.add("ecs").usingMembers((ecs) -> ecs.add("version", "8.11"));
}
|
private static void addContextDataPairs(Pairs<ReadOnlyStringMap> contextPairs) {
contextPairs.add((contextData, pairs) -> contextData.forEach(pairs::accept));
}
private static java.time.Instant asTimestamp(Instant instant) {
return java.time.Instant.ofEpochMilli(instant.getEpochMillisecond()).plusNanos(instant.getNanoOfMillisecond());
}
private static Set<String> getMarkers(Marker marker) {
Set<String> result = new TreeSet<>();
addMarkers(result, marker);
return result;
}
private static void addMarkers(Set<String> result, Marker marker) {
result.add(marker.getName());
if (marker.hasParents()) {
for (Marker parent : marker.getParents()) {
addMarkers(result, parent);
}
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\logging\log4j2\ElasticCommonSchemaStructuredLogFormatter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public GitIgnoreCustomizer mavenGitIgnoreCustomizer() {
return (gitIgnore) -> {
gitIgnore.getGeneral()
.add("target/", ".mvn/wrapper/maven-wrapper.jar", "!**/src/main/**/target/", "!**/src/test/**/target/");
gitIgnore.getNetBeans().add("build/", "!**/src/main/**/build/", "!**/src/test/**/build/");
};
}
@Bean
@ConditionalOnBuildSystem(GradleBuildSystem.ID)
public GitIgnoreCustomizer gradleGitIgnoreCustomizer() {
return (gitIgnore) -> {
gitIgnore.getGeneral()
.add(".gradle", "build/", "!gradle/wrapper/gradle-wrapper.jar", "!**/src/main/**/build/",
"!**/src/test/**/build/");
gitIgnore.getIntellijIdea().add("out/", "!**/src/main/**/out/", "!**/src/test/**/out/");
gitIgnore.getSts().add("bin/", "!**/src/main/**/bin/", "!**/src/test/**/bin/");
};
}
@Bean
@ConditionalOnBuildSystem(MavenBuildSystem.ID)
public GitAttributesCustomizer mavenGitAttributesCustomizer() {
return (gitAttributes) -> {
gitAttributes.add("/mvnw", "text", "eol=lf");
gitAttributes.add("*.cmd", "text", "eol=crlf");
|
};
}
@Bean
@ConditionalOnBuildSystem(GradleBuildSystem.ID)
public GitAttributesCustomizer gradleGitAttributesCustomizer() {
return (gitAttributes) -> {
gitAttributes.add("/gradlew", "text", "eol=lf");
gitAttributes.add("*.bat", "text", "eol=crlf");
gitAttributes.add("*.jar", "binary");
};
}
private GitIgnore createGitIgnore() {
GitIgnore gitIgnore = new GitIgnore();
gitIgnore.getSts()
.add(".apt_generated", ".classpath", ".factorypath", ".project", ".settings", ".springBeans",
".sts4-cache");
gitIgnore.getIntellijIdea().add(".idea", "*.iws", "*.iml", "*.ipr");
gitIgnore.getNetBeans().add("/nbproject/private/", "/nbbuild/", "/dist/", "/nbdist/", "/.nb-gradle/");
gitIgnore.getVscode().add(".vscode/");
return gitIgnore;
}
}
|
repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\scm\git\GitProjectGenerationConfiguration.java
| 2
|
请完成以下Java代码
|
static AvailabilityInfoResultForWebui.Group.Type extractGroupType(@NonNull final AttributesKeyPattern attributesKey)
{
if (AttributesKeyPattern.ALL.equals(attributesKey))
{
return AvailabilityInfoResultForWebui.Group.Type.ALL_STORAGE_KEYS;
}
else if (AttributesKeyPattern.OTHER.equals(attributesKey))
{
return AvailabilityInfoResultForWebui.Group.Type.OTHER_STORAGE_KEYS;
}
else
{
return AvailabilityInfoResultForWebui.Group.Type.ATTRIBUTE_SET;
}
}
@NonNull
public AvailabilityInfoResultForWebui retrieveAvailableStock(@NonNull final AvailableForSalesMultiQuery query)
{
final AvailableForSalesLookupResult commonsAvailableStock = availableForSalesRepository.retrieveAvailableStock(query);
final AvailabilityInfoResultForWebuiBuilder clientResultBuilder = AvailabilityInfoResultForWebui.builder();
for (final AvailableForSalesLookupBucketResult commonsResultGroup : commonsAvailableStock.getAvailableForSalesResults())
{
final AvailabilityInfoResultForWebui.Group clientResultGroup = createClientResultGroup(commonsResultGroup);
clientResultBuilder.group(clientResultGroup);
}
return clientResultBuilder.build();
}
private AvailabilityInfoResultForWebui.Group createClientResultGroup(@NonNull final AvailableForSalesLookupBucketResult commonsResultGroup)
{
try
{
return createClientResultGroup0(commonsResultGroup);
}
catch (final RuntimeException e)
{
throw AdempiereException.wrapIfNeeded(e).appendParametersToMessage()
.setParameter("commonsResultGroup", commonsResultGroup);
}
}
private AvailabilityInfoResultForWebui.Group createClientResultGroup0(final AvailableForSalesLookupBucketResult commonsResultGroup)
{
final Quantity quantity = extractQuantity(commonsResultGroup);
final AttributesKeyPattern attributesKey = AttributesKeyPatternsUtil.ofAttributeKey(commonsResultGroup.getStorageAttributesKey());
final AvailabilityInfoResultForWebui.Group.Type type = extractGroupType(attributesKey);
final ImmutableAttributeSet attributes = AvailabilityInfoResultForWebui.Group.Type.ATTRIBUTE_SET.equals(type)
|
? AttributesKeys.toImmutableAttributeSet(commonsResultGroup.getStorageAttributesKey())
: ImmutableAttributeSet.EMPTY;
return AvailabilityInfoResultForWebui.Group.builder()
.productId(commonsResultGroup.getProductId())
.qty(quantity)
.type(type)
.attributes(attributes)
.build();
}
private Quantity extractQuantity(final AvailableForSalesLookupBucketResult commonsResultGroup)
{
final AvailableForSalesLookupBucketResult.Quantities quantities = commonsResultGroup.getQuantities();
final BigDecimal qty = quantities.getQtyOnHandStock().subtract(quantities.getQtyToBeShipped());
final I_C_UOM uom = productsService.getStockUOM(commonsResultGroup.getProductId());
return Quantity.of(qty, uom);
}
public Set<AttributesKeyPattern> getPredefinedStorageAttributeKeys()
{
return availableForSalesRepository.getPredefinedStorageAttributeKeys();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\adapter\AvailableForSaleAdapter.java
| 1
|
请完成以下Java代码
|
public boolean isUserParameter()
{
return parameterAnnotation != null;
}
public DocumentFieldDescriptor.Builder createParameterFieldDescriptor()
{
Preconditions.checkState(isUserParameter(), "parameter is internal");
LookupDescriptorProvider lookupDescriptorProvider = LookupDescriptorProviders.NULL;
if (parameterAnnotation.widgetType().isLookup())
{
if (Check.isEmpty(parameterAnnotation.sqlLookupTableName(), true))
{
logger.warn("sqlLookupTableName not provided in " + parameterAnnotation + " (" + this + "). Continuing...");
}
else
{
lookupDescriptorProvider = LookupDescriptorProviders.sharedInstance().sql()
.setCtxTableName(null) // tableName
.setCtxColumnName(InterfaceWrapperHelper.getKeyColumnName(parameterAnnotation.sqlLookupTableName()))
.setDisplayType(DisplayType.Search)
.setReadOnlyAccess()
.build();
}
}
|
return DocumentFieldDescriptor.builder(parameterName)
.setCaption(parameterAnnotation.caption())
// .setDescription(parameterAnnotation.description())
//
.setValueClass(parameterValueClass)
.setWidgetType(parameterAnnotation.widgetType())
.setLookupDescriptorProvider(lookupDescriptorProvider != null ? lookupDescriptorProvider : LookupDescriptorProviders.NULL)
//
// .setDefaultValueExpression(defaultValueExpr)
.setReadonlyLogic(false)
.setDisplayLogic(true)
.setMandatoryLogic(parameterAnnotation.mandatory())
//
.addCharacteristic(Characteristic.PublicField)
//
// .setDataBinding(new ASIAttributeFieldBinding(attributeId, fieldName, attribute.isMandatory(), readMethod, writeMethod))
;
}
public Object extractArgument(final IView view, final Document processParameters, final DocumentIdsSelection selectedDocumentIds)
{
return methodArgumentExtractor.extractArgument(view, processParameters, selectedDocumentIds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewActionParamDescriptor.java
| 1
|
请完成以下Java代码
|
public int getM_HU_PI_Item_Product_ID()
{
//
// Check the invoice line first
final int invoiceLine_PIItemProductId = invoiceLine.getM_HU_PI_Item_Product_ID();
if (invoiceLine_PIItemProductId > 0)
{
return invoiceLine_PIItemProductId;
}
//
// Check order line
final I_C_OrderLine orderline = InterfaceWrapperHelper.create(invoiceLine.getC_OrderLine(), I_C_OrderLine.class);
if (orderline == null)
{
//
// C_OrderLine not found (i.e Manual Invoice)
return -1;
}
return orderline.getM_HU_PI_Item_Product_ID();
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
invoiceLine.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
@Override
public BigDecimal getQtyTU()
{
return invoiceLine.getQtyEnteredTU();
}
|
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
invoiceLine.setQtyEnteredTU(qtyPacks);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
values.setC_BPartner_ID(partnerId);
}
@Override
public int getC_BPartner_ID()
{
return values.getC_BPartner_ID();
}
@Override
public boolean isInDispute()
{
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\InvoiceLineHUPackingAware.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public List<String> getCustomMybatisXMLMappers() {
return customMybatisXMLMappers;
}
public void setCustomMybatisXMLMappers(List<String> customMybatisXMLMappers) {
this.customMybatisXMLMappers = customMybatisXMLMappers;
}
public String getActivityFontName() {
return activityFontName;
}
public void setActivityFontName(String activityFontName) {
this.activityFontName = activityFontName;
}
public String getLabelFontName() {
return labelFontName;
}
public void setLabelFontName(String labelFontName) {
this.labelFontName = labelFontName;
}
public String getAnnotationFontName() {
return annotationFontName;
}
public void setAnnotationFontName(String annotationFontName) {
this.annotationFontName = annotationFontName;
}
public boolean isFormFieldValidationEnabled() {
return formFieldValidationEnabled;
}
public void setFormFieldValidationEnabled(boolean formFieldValidationEnabled) {
this.formFieldValidationEnabled = formFieldValidationEnabled;
}
public Duration getLockPollRate() {
return lockPollRate;
}
public void setLockPollRate(Duration lockPollRate) {
this.lockPollRate = lockPollRate;
}
public Duration getSchemaLockWaitTime() {
return schemaLockWaitTime;
|
}
public void setSchemaLockWaitTime(Duration schemaLockWaitTime) {
this.schemaLockWaitTime = schemaLockWaitTime;
}
public boolean isEnableHistoryCleaning() {
return enableHistoryCleaning;
}
public void setEnableHistoryCleaning(boolean enableHistoryCleaning) {
this.enableHistoryCleaning = enableHistoryCleaning;
}
public String getHistoryCleaningCycle() {
return historyCleaningCycle;
}
public void setHistoryCleaningCycle(String historyCleaningCycle) {
this.historyCleaningCycle = historyCleaningCycle;
}
@Deprecated
@DeprecatedConfigurationProperty(replacement = "flowable.history-cleaning-after", reason = "Switched to using a Duration that allows more flexible configuration")
public void setHistoryCleaningAfterDays(int historyCleaningAfterDays) {
this.historyCleaningAfter = Duration.ofDays(historyCleaningAfterDays);
}
public Duration getHistoryCleaningAfter() {
return historyCleaningAfter;
}
public void setHistoryCleaningAfter(Duration historyCleaningAfter) {
this.historyCleaningAfter = historyCleaningAfter;
}
public int getHistoryCleaningBatchSize() {
return historyCleaningBatchSize;
}
public void setHistoryCleaningBatchSize(int historyCleaningBatchSize) {
this.historyCleaningBatchSize = historyCleaningBatchSize;
}
public String getVariableJsonMapper() {
return variableJsonMapper;
}
public void setVariableJsonMapper(String variableJsonMapper) {
this.variableJsonMapper = variableJsonMapper;
}
}
|
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\FlowableProperties.java
| 2
|
请完成以下Java代码
|
public void setAD_ReplicationStrategy_ID (final int AD_ReplicationStrategy_ID)
{
if (AD_ReplicationStrategy_ID < 1)
set_Value (COLUMNNAME_AD_ReplicationStrategy_ID, null);
else
set_Value (COLUMNNAME_AD_ReplicationStrategy_ID, AD_ReplicationStrategy_ID);
}
@Override
public int getAD_ReplicationStrategy_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_ReplicationStrategy_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsEUOneStopShop (final boolean IsEUOneStopShop)
{
set_Value (COLUMNNAME_IsEUOneStopShop, IsEUOneStopShop);
}
@Override
public boolean isEUOneStopShop()
{
return get_ValueAsBoolean(COLUMNNAME_IsEUOneStopShop);
}
@Override
public void setIsSummary (final boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, IsSummary);
|
}
@Override
public boolean isSummary()
{
return get_ValueAsBoolean(COLUMNNAME_IsSummary);
}
@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);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Org.java
| 1
|
请完成以下Java代码
|
public VariableInstanceQuery orderBy(QueryProperty property) {
wrappedVariableInstanceQuery.orderBy(property);
return this;
}
@Override
public VariableInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) {
wrappedVariableInstanceQuery.orderBy(property, nullHandlingOnOrder);
return this;
}
@Override
public long count() {
return wrappedVariableInstanceQuery.count();
}
@Override
|
public VariableInstance singleResult() {
return wrappedVariableInstanceQuery.singleResult();
}
@Override
public List<VariableInstance> list() {
return wrappedVariableInstanceQuery.list();
}
@Override
public List<VariableInstance> listPage(int firstResult, int maxResults) {
return wrappedVariableInstanceQuery.listPage(firstResult, maxResults);
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\CmmnVariableInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public String getName() {
return TYPE_NAME;
}
@Override
public Object getInformation(String key) {
if (key.equals("values")) {
return values;
}
return null;
}
public TypedValue convertValue(TypedValue propertyValue) {
Object value = propertyValue.getValue();
if(value == null || String.class.isInstance(value)) {
validateValue(value);
return Variables.stringValue((String) value, propertyValue.isTransient());
}
else {
throw new ProcessEngineException("Value '"+value+"' is not of type String.");
}
}
protected void validateValue(Object value) {
if(value != null) {
if(values != null && !values.containsKey(value)) {
throw new ProcessEngineException("Invalid value for enum form property: " + value);
}
}
}
public Map<String, String> getValues() {
return values;
|
}
//////////////////// deprecated ////////////////////////////////////////
@Override
public Object convertFormValueToModelValue(Object propertyValue) {
validateValue(propertyValue);
return propertyValue;
}
@Override
public String convertModelValueToFormValue(Object modelValue) {
if(modelValue != null) {
if(!(modelValue instanceof String)) {
throw new ProcessEngineException("Model value should be a String");
}
validateValue(modelValue);
}
return (String) modelValue;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\form\type\EnumFormType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public final class DevelopmentWorkspaceJasperDirectoriesFinder
{
public static List<File> getReportsDirectoriesForWorkspace(final File workspaceDir)
{
if (!workspaceDir.isDirectory())
{
return ImmutableList.of();
}
final File[] projectDirs = workspaceDir.listFiles(File::isDirectory);
final ArrayList<File> result = new ArrayList<>();
// First consider all other projects, but not metasfresh.
for (final File projectDir : projectDirs)
{
if (!isMetasfreshRepository(projectDir))
{
result.addAll(getReportsDirectories(projectDir));
}
}
// Consider metasfresh projects
for (final File projectDir : projectDirs)
{
if (isMetasfreshRepository(projectDir))
{
final File metasfreshBackend = new File(projectDir, "backend");
if (isProjectDir(metasfreshBackend))
{
result.addAll(getReportsDirectories(metasfreshBackend));
}
}
}
return result;
}
private static List<File> getReportsDirectories(@NonNull final File dir)
{
final ArrayList<File> result = new ArrayList<>();
if (isIgnore(dir))
{
return result;
}
if (isProjectDir(dir))
{
|
final File reportsDir = getReportsDirOfProjectDirIfExists(dir);
if (reportsDir != null)
{
result.add(reportsDir);
}
}
for (final File subProjectDir : dir.listFiles(DevelopmentWorkspaceJasperDirectoriesFinder::isProjectDir))
{
result.addAll(getReportsDirectories(subProjectDir));
}
return result;
}
@Nullable
private static File getReportsDirOfProjectDirIfExists(final File projectDir)
{
final File reportsDir = new File(projectDir, "src//main//jasperreports");
if (reportsDir.exists() && reportsDir.isDirectory())
{
return reportsDir;
}
else
{
return null;
}
}
private static boolean isProjectDir(final File dir)
{
return dir.isDirectory()
&& new File(dir, "pom.xml").exists()
&& !isIgnore(dir);
}
private static boolean isIgnore(final File dir)
{
return new File(dir, ".ignore-reports").exists();
}
private static boolean isMetasfreshRepository(@NonNull final File projectDir)
{
return "metasfresh".equals(projectDir.getName())
&& projectDir.isDirectory();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\util\DevelopmentWorkspaceJasperDirectoriesFinder.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public TaskService taskServiceBean(ProcessEngine processEngine) {
return super.taskServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public HistoryService historyServiceBean(ProcessEngine processEngine) {
return super.historyServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public ManagementService managementServiceBeanBean(ProcessEngine processEngine) {
return super.managementServiceBeanBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
|
public TaskExecutor taskExecutor() {
return new SimpleAsyncTaskExecutor();
}
@Bean
@ConditionalOnMissingBean
@Override
public IntegrationContextManager integrationContextManagerBean(ProcessEngine processEngine) {
return super.integrationContextManagerBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public IntegrationContextService integrationContextServiceBean(ProcessEngine processEngine) {
return super.integrationContextServiceBean(processEngine);
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\AbstractProcessEngineAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public Boolean getBoolField() {
return boolField;
}
public void setBoolField(Boolean boolField) {
this.boolField = boolField;
}
public Boolean getTrueField() {
return trueField;
}
public void setTrueField(Boolean trueField) {
this.trueField = trueField;
}
|
public Boolean getFalseField() {
return falseField;
}
public void setFalseField(Boolean falseField) {
this.falseField = falseField;
}
public Boolean getBoolStringVar() {
return boolStringVar;
}
public void setBoolStringVar(Boolean boolStringVar) {
this.boolStringVar = boolStringVar;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-validations\src\main\java\com\baeldung\dto\BooleanObject.java
| 1
|
请完成以下Java代码
|
public boolean getIsShipToOr(final boolean defaultValue)
{
return shipTo.orElse(defaultValue);
}
public boolean getIsShipToDefaultOr(final boolean defaultValue)
{
return shipToDefault.orElse(defaultValue);
}
public boolean getIsBillToOr(final boolean defaultValue)
{
return billTo.orElse(defaultValue);
}
public boolean getIsBillToDefaultOr(final boolean defaultValue)
{
return billToDefault.orElse(defaultValue);
}
public boolean getIsVisitorsAddressOr(final boolean defaultValue)
{
return visitorsAddress.orElse(defaultValue);
|
}
public boolean getIsVisitorsAddressDefaultOr(final boolean defaultValue)
{
return visitorsAddressDefault.orElse(defaultValue);
}
public void setBillToDefault(final boolean billToDefault)
{
this.billToDefault = Optional.of(billToDefault);
}
public void setShipToDefault(final boolean shipToDefault)
{
this.shipToDefault = Optional.of(shipToDefault);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerLocationType.java
| 1
|
请完成以下Java代码
|
public void setDocumentFlavor (final @Nullable java.lang.String DocumentFlavor)
{
set_Value (COLUMNNAME_DocumentFlavor, DocumentFlavor);
}
@Override
public java.lang.String getDocumentFlavor()
{
return get_ValueAsString(COLUMNNAME_DocumentFlavor);
}
@Override
public void setDocumentNo (final @Nullable java.lang.String DocumentNo)
{
set_ValueNoCheck (COLUMNNAME_DocumentNo, DocumentNo);
}
@Override
public java.lang.String getDocumentNo()
{
return get_ValueAsString(COLUMNNAME_DocumentNo);
}
@Override
public void setHelp (final @Nullable java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setIsDirectEnqueue (final boolean IsDirectEnqueue)
{
set_Value (COLUMNNAME_IsDirectEnqueue, IsDirectEnqueue);
}
@Override
public boolean isDirectEnqueue()
{
return get_ValueAsBoolean(COLUMNNAME_IsDirectEnqueue);
}
@Override
public void setIsDirectProcessQueueItem (final boolean IsDirectProcessQueueItem)
{
set_Value (COLUMNNAME_IsDirectProcessQueueItem, IsDirectProcessQueueItem);
}
@Override
public boolean isDirectProcessQueueItem()
{
return get_ValueAsBoolean(COLUMNNAME_IsDirectProcessQueueItem);
}
@Override
public void setIsFileSystem (final boolean IsFileSystem)
{
set_Value (COLUMNNAME_IsFileSystem, IsFileSystem);
}
@Override
public boolean isFileSystem()
{
return get_ValueAsBoolean(COLUMNNAME_IsFileSystem);
}
@Override
public void setIsReport (final boolean IsReport)
|
{
set_Value (COLUMNNAME_IsReport, IsReport);
}
@Override
public boolean isReport()
{
return get_ValueAsBoolean(COLUMNNAME_IsReport);
}
@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);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_Value (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Archive.java
| 1
|
请完成以下Java代码
|
private AllocablePackageable toBOMLineAllocablePackageable(final PickingCandidateIssueToBOMLine candidate, final AllocablePackageable finishedGoodPackageable)
{
return finishedGoodPackageable.toBuilder()
.productId(candidate.getProductId())
.qtyToAllocateTarget(candidate.getQtyToIssue())
.issueToBOMLine(IssueToBOMLine.builder()
.issueToOrderBOMLineId(candidate.getIssueToOrderBOMLineId())
.issueFromHUId(candidate.getIssueFromHUId())
.build())
.build();
}
private PickingPlanLine updateAlternativeKeys(@NonNull final PickingPlanLine line)
{
final PickFromHU pickFromHU = line.getPickFromHU();
if (pickFromHU == null)
{
return line;
}
final AlternativePickFromKeys alternativeKeys = pickFromHU.getAlternatives()
.filter(alternativeKey -> storages.getStorage(alternativeKey.getHuId(), alternativeKey.getProductId()).hasQtyFreeToAllocate());
return line.withPickFromHU(pickFromHU.withAlternatives(alternativeKeys));
}
private AlternativePickFromsList getRelevantAlternativesFor(final List<PickingPlanLine> lines)
|
{
final HashSet<AlternativePickFromKey> keysConsidered = new HashSet<>();
final ArrayList<AlternativePickFrom> alternatives = new ArrayList<>();
for (final PickingPlanLine line : lines)
{
final PickFromHU pickFromHU = line.getPickFromHU();
if (pickFromHU == null)
{
continue;
}
for (final AlternativePickFromKey key : pickFromHU.getAlternatives())
{
if (keysConsidered.add(key))
{
storages.getStorage(key.getHuId(), key.getProductId())
.getQtyFreeToAllocate()
.filter(Quantity::isPositive)
.map(availableQty -> AlternativePickFrom.of(key, availableQty))
.ifPresent(alternatives::add);
}
}
}
return AlternativePickFromsList.ofList(alternatives);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\plan\generator\CreatePickingPlanCommand.java
| 1
|
请完成以下Java代码
|
public TablePageQueryImpl orderAsc(String column) {
addOrder(column, ListQueryParameterObject.SORTORDER_ASC);
return this;
}
@Override
public TablePageQueryImpl orderDesc(String column) {
addOrder(column, ListQueryParameterObject.SORTORDER_DESC);
return this;
}
public String getTableName() {
return tableName;
}
protected void addOrder(String column, String sortOrder) {
if (order == null) {
order = "";
} else {
order = order + ", ";
}
|
order = order + column + " " + sortOrder;
}
@Override
public TablePage listPage(int firstResult, int maxResults) {
this.firstResult = firstResult;
this.maxResults = maxResults;
return commandExecutor.execute(this);
}
@Override
public TablePage execute(CommandContext commandContext) {
return engineConfiguration.getTableDataManager().getTablePage(this, firstResult, maxResults);
}
public String getOrder() {
return order;
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\persistence\entity\TablePageQueryImpl.java
| 1
|
请完成以下Java代码
|
public Order complete(Boolean complete) {
this.complete = complete;
return this;
}
/**
* Get complete
* @return complete
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "")
@JsonProperty(JSON_PROPERTY_COMPLETE)
@JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)
public Boolean getComplete() {
return complete;
}
public void setComplete(Boolean complete) {
this.complete = complete;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Order order = (Order) o;
return Objects.equals(this.id, order.id) &&
Objects.equals(this.petId, order.petId) &&
Objects.equals(this.quantity, order.quantity) &&
Objects.equals(this.shipDate, order.shipDate) &&
Objects.equals(this.status, order.status) &&
Objects.equals(this.complete, order.complete);
}
@Override
public int hashCode() {
return Objects.hash(id, petId, quantity, shipDate, status, complete);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
|
sb.append("class Order {\n");
sb.append(" id: ").append(toIndentedString(id)).append("\n");
sb.append(" petId: ").append(toIndentedString(petId)).append("\n");
sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n");
sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" complete: ").append(toIndentedString(complete)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\tutorials-master\spring-swagger-codegen-modules\spring-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\Order.java
| 1
|
请完成以下Java代码
|
public ResponseEntity<PageResult<LocalStorageDto>> queryFile(LocalStorageQueryCriteria criteria, Pageable pageable){
return new ResponseEntity<>(localStorageService.queryAll(criteria,pageable),HttpStatus.OK);
}
@ApiOperation("导出数据")
@GetMapping(value = "/download")
@PreAuthorize("@el.check('storage:list')")
public void exportFile(HttpServletResponse response, LocalStorageQueryCriteria criteria) throws IOException {
localStorageService.download(localStorageService.queryAll(criteria), response);
}
@PostMapping
@ApiOperation("上传文件")
@PreAuthorize("@el.check('storage:add')")
public ResponseEntity<Object> createFile(@RequestParam String name, @RequestParam("file") MultipartFile file){
localStorageService.create(name, file);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@ApiOperation("上传图片")
@PostMapping("/pictures")
public ResponseEntity<LocalStorage> uploadPicture(@RequestParam MultipartFile file){
// 判断文件是否为图片
String suffix = FileUtil.getExtensionName(file.getOriginalFilename());
if(!FileUtil.IMAGE.equals(FileUtil.getFileType(suffix))){
throw new BadRequestException("只能上传图片");
}
LocalStorage localStorage = localStorageService.create(null, file);
return new ResponseEntity<>(localStorage, HttpStatus.OK);
}
|
@PutMapping
@Log("修改文件")
@ApiOperation("修改文件")
@PreAuthorize("@el.check('storage:edit')")
public ResponseEntity<Object> updateFile(@Validated @RequestBody LocalStorage resources){
localStorageService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除文件")
@DeleteMapping
@ApiOperation("多选删除")
public ResponseEntity<Object> deleteFile(@RequestBody Long[] ids) {
localStorageService.deleteAll(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
}
|
repos\eladmin-master\eladmin-tools\src\main\java\me\zhengjie\rest\LocalStorageController.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getCurrentTimestampSelectString() {
return "select current_timestamp";
}
public boolean supportsUnionAll() {
return true;
}
public boolean hasAlterTable() {
return false; // As specify in NHibernate dialect
}
public boolean dropConstraints() {
return false;
}
public String getAddColumnString() {
return "add column";
}
public String getForUpdateString() {
return "";
}
public boolean supportsOuterJoinForUpdate() {
return false;
}
public String getDropForeignKeyString() {
throw new UnsupportedOperationException("No drop foreign key syntax supported by SQLiteDialect");
|
}
public String getAddForeignKeyConstraintString(String constraintName,
String[] foreignKey, String referencedTable, String[] primaryKey,
boolean referencesPrimaryKey) {
throw new UnsupportedOperationException("No add foreign key syntax supported by SQLiteDialect");
}
public String getAddPrimaryKeyConstraintString(String constraintName) {
throw new UnsupportedOperationException("No add primary key syntax supported by SQLiteDialect");
}
public boolean supportsIfExistsBeforeTableName() {
return true;
}
public boolean supportsCascadeDelete() {
return false;
}
}
|
repos\SpringBoot-vue-master\src\main\java\com\boylegu\springboot_vue\config\SQLiteDialect.java
| 2
|
请完成以下Java代码
|
public Date getCompletedBefore() {
return completedBefore;
}
public Date getCompletedAfter() {
return completedAfter;
}
public String getGroupBy() {
return groupby;
}
@CamundaQueryParam(value = "completedAfter", converter = DateConverter.class)
public void setCompletedAfter(Date completedAfter) {
this.completedAfter = completedAfter;
}
@CamundaQueryParam(value = "completedBefore", converter = DateConverter.class)
public void setCompletedBefore(Date completedBefore) {
this.completedBefore = completedBefore;
}
@CamundaQueryParam("groupBy")
public void setGroupBy(String groupby) {
this.groupby = groupby;
}
protected void applyFilters(HistoricTaskInstanceReport reportQuery) {
if (completedBefore != null) {
reportQuery.completedBefore(completedBefore);
}
if (completedAfter != null) {
reportQuery.completedAfter(completedAfter);
}
if(REPORT_TYPE_DURATION.equals(reportType)) {
if(periodUnit == null) {
|
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "periodUnit is null");
}
}
}
protected HistoricTaskInstanceReport createNewReportQuery(ProcessEngine engine) {
return engine.getHistoryService().createHistoricTaskInstanceReport();
}
public List<HistoricTaskInstanceReportResult> executeCompletedReport(ProcessEngine engine) {
HistoricTaskInstanceReport reportQuery = createNewReportQuery(engine);
applyFilters(reportQuery);
if(PROCESS_DEFINITION.equals(groupby)) {
return reportQuery.countByProcessDefinitionKey();
} else if( TASK_NAME.equals(groupby) ){
return reportQuery.countByTaskName();
} else {
throw new InvalidRequestException(Response.Status.BAD_REQUEST, "groupBy parameter has invalid value: " + groupby);
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricTaskInstanceReportQueryDto.java
| 1
|
请完成以下Java代码
|
public class GroupDto {
protected String id;
protected String name;
protected String type;
// Transformers ////////////////////////////////
public static GroupDto fromGroup(Group dbGroup) {
GroupDto groupDto = new GroupDto();
groupDto.setId(dbGroup.getId());
groupDto.setName(dbGroup.getName());
groupDto.setType(dbGroup.getType());
return groupDto;
}
public void update(Group dbGroup) {
dbGroup.setId(id);
dbGroup.setName(name);
dbGroup.setType(type);
}
public static List<GroupDto> fromGroupList(List<Group> dbGroupList) {
List<GroupDto> resultList = new ArrayList<GroupDto>();
for (Group group : dbGroupList) {
resultList.add(fromGroup(group));
}
return resultList;
}
|
// Getters / Setters ///////////////////////////
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\GroupDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable Cluster getCluster() {
DataRedisProperties.Cluster cluster = this.properties.getCluster();
return (cluster != null) ? new PropertiesCluster(cluster) : null;
}
@Override
public @Nullable MasterReplica getMasterReplica() {
DataRedisProperties.Masterreplica masterreplica = this.properties.getMasterreplica();
return (masterreplica != null) ? new PropertiesMasterReplica(masterreplica) : null;
}
private @Nullable DataRedisUrl getRedisUrl() {
return DataRedisUrl.of(this.properties.getUrl());
}
private List<Node> asNodes(@Nullable List<String> nodes) {
if (nodes == null) {
return Collections.emptyList();
}
return nodes.stream().map(this::asNode).toList();
}
private Node asNode(String node) {
int portSeparatorIndex = node.lastIndexOf(':');
String host = node.substring(0, portSeparatorIndex);
int port = Integer.parseInt(node.substring(portSeparatorIndex + 1));
return new Node(host, port);
}
/**
* {@link Cluster} implementation backed by properties.
*/
private class PropertiesCluster implements Cluster {
private final List<Node> nodes;
PropertiesCluster(DataRedisProperties.Cluster properties) {
this.nodes = asNodes(properties.getNodes());
}
@Override
public List<Node> getNodes() {
return this.nodes;
}
}
/**
* {@link MasterReplica} implementation backed by properties.
*/
private class PropertiesMasterReplica implements MasterReplica {
private final List<Node> nodes;
PropertiesMasterReplica(DataRedisProperties.Masterreplica properties) {
this.nodes = asNodes(properties.getNodes());
}
@Override
public List<Node> getNodes() {
return this.nodes;
}
}
/**
* {@link Sentinel} implementation backed by properties.
|
*/
private class PropertiesSentinel implements Sentinel {
private final int database;
private final DataRedisProperties.Sentinel properties;
PropertiesSentinel(int database, DataRedisProperties.Sentinel properties) {
this.database = database;
this.properties = properties;
}
@Override
public int getDatabase() {
return this.database;
}
@Override
public String getMaster() {
String master = this.properties.getMaster();
Assert.state(master != null, "'master' must not be null");
return master;
}
@Override
public List<Node> getNodes() {
return asNodes(this.properties.getNodes());
}
@Override
public @Nullable String getUsername() {
return this.properties.getUsername();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\PropertiesDataRedisConnectionDetails.java
| 2
|
请完成以下Java代码
|
public final class GroovyLanguage extends AbstractLanguage {
// See https://docs.groovy-lang.org/latest/html/documentation/#_keywords
private static final Set<String> KEYWORDS = Set.of("abstract", "assert", "break", "case", "catch", "class", "const",
"continue", "def", "default", "do", "else", "enum", "extends", "final", "finally", "for", "goto", "if",
"implements", "import", "instanceof", "interface", "native", "new", "null", "non-sealed", "package",
"public", "protected", "private", "return", "static", "strictfp", "super", "switch", "synchronized", "this",
"threadsafe", "throw", "throws", "transient", "try", "while");
/**
* Groovy {@link Language} identifier.
*/
public static final String ID = "groovy";
/**
* Creates a new instance with the JVM version {@value #DEFAULT_JVM_VERSION}.
*/
public GroovyLanguage() {
this(DEFAULT_JVM_VERSION);
}
/**
* Creates a new instance.
|
* @param jvmVersion the JVM version
*/
public GroovyLanguage(String jvmVersion) {
super(ID, jvmVersion, "groovy");
}
@Override
public boolean supportsEscapingKeywordsInPackage() {
return false;
}
@Override
public boolean isKeyword(String input) {
return KEYWORDS.contains(input);
}
}
|
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovyLanguage.java
| 1
|
请完成以下Java代码
|
public String toString() {
String regexp = config.getRegexp();
return filterToStringCreator(RewritePathGatewayFilterFactory.this)
.append(regexp != null ? regexp : "", replacement)
.toString();
}
};
}
public static class Config {
private @Nullable String regexp;
private @Nullable String replacement;
public @Nullable String getRegexp() {
return regexp;
}
public Config setRegexp(String regexp) {
Assert.hasText(regexp, "regexp must have a value");
this.regexp = regexp;
|
return this;
}
public @Nullable String getReplacement() {
return replacement;
}
public Config setReplacement(String replacement) {
Objects.requireNonNull(replacement, "replacement must not be null");
this.replacement = replacement;
return this;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RewritePathGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public void updateBPartnerAddress(final I_M_ReceiptSchedule sched)
{
final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class);
receiptScheduleBL.updateBPartnerAddress(sched);
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_NEW,
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = {
I_M_ReceiptSchedule.COLUMNNAME_C_Order_ID
})
public void updatePreparationTime(final I_M_ReceiptSchedule sched)
{
final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class);
receiptScheduleBL.updatePreparationTime(sched);
}
@ModelChange(timings = {
// ModelValidator.TYPE_BEFORE_NEW, // not needed because we don't set overwrites on NEW
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = {
I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_C_BP_Location_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_AD_User_Override_ID
})
public void updateBPartnerAddressOverride(final I_M_ReceiptSchedule sched)
{
final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class);
receiptScheduleBL.updateBPartnerAddressOverride(sched);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE })
public void updateHeaderAggregationKey(final I_M_ReceiptSchedule sched)
{
if (sched.isProcessed())
{
|
return;
}
final IAggregationKeyBuilder<I_M_ReceiptSchedule> headerAggregationKeyBuilder = receiptScheduleBL.getHeaderAggregationKeyBuilder();
final String headerAggregationKey = headerAggregationKeyBuilder.buildKey(sched);
sched.setHeaderAggregationKey(headerAggregationKey);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = { I_M_ReceiptSchedule.COLUMNNAME_IsActive,
I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_Override_ID,
I_M_ReceiptSchedule.COLUMNNAME_DeliveryRule_Override,
I_M_ReceiptSchedule.COLUMNNAME_PriorityRule_Override,
I_M_ReceiptSchedule.COLUMNNAME_QtyToMove_Override,
I_M_ReceiptSchedule.COLUMNNAME_AD_User_Override_ID,
I_M_ReceiptSchedule.COLUMNNAME_BPartnerAddress_Override,
I_M_ReceiptSchedule.COLUMNNAME_DeliveryViaRule_Override,
I_M_ReceiptSchedule.COLUMNNAME_IsBPartnerAddress_Override,
I_M_ReceiptSchedule.COLUMNNAME_ExportStatus })
public void updateCanBeExportedAfter(@NonNull final I_M_ReceiptSchedule sched)
{
receiptScheduleBL.updateCanBeExportedFrom(sched);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\M_ReceiptSchedule.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Flux<User> getUserByAgeStream(@PathVariable Integer from, @PathVariable Integer to) {
return userService.getUserByAge(from, to);
}
/**
* 根据用户名查找
*/
@GetMapping("/name/{name}")
public Flux<User> getUserByName(@PathVariable String name) {
return userService.getUserByName(name);
}
@GetMapping(value = "/stream/name/{name}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<User> getUserByNameStream(@PathVariable String name) {
return userService.getUserByName(name);
}
/**
* 根据用户描述模糊查找
*/
@GetMapping("/description/{description}")
public Flux<User> getUserByDescription(@PathVariable String description) {
return userService.getUserByDescription(description);
}
|
@GetMapping(value = "/stream/description/{description}", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
public Flux<User> getUserByDescriptionStream(@PathVariable String description) {
return userService.getUserByDescription(description);
}
/**
* 根据多个检索条件查询
*/
@GetMapping("/condition")
public Flux<User> getUserByCondition(int size, int page, User user) {
return userService.getUserByCondition(size, page, user);
}
@GetMapping("/condition/count")
public Mono<Long> getUserByConditionCount(User user) {
return userService.getUserByConditionCount(user);
}
}
|
repos\SpringAll-master\58.Spring-Boot-WebFlux-crud\src\main\java\com\example\webflux\controller\UserController.java
| 2
|
请完成以下Java代码
|
protected EventLoggerEventHandler instantiateEventHandler(
ActivitiEvent event,
Class<? extends EventLoggerEventHandler> eventHandlerClass
) {
try {
EventLoggerEventHandler eventHandler = eventHandlerClass.getDeclaredConstructor().newInstance();
eventHandler.setTimeStamp(clock.getCurrentTime());
eventHandler.setEvent(event);
eventHandler.setObjectMapper(objectMapper);
return eventHandler;
} catch (Exception e) {
logger.warn("Could not instantiate " + eventHandlerClass + ", this is most likely a programmatic error");
}
return null;
}
@Override
public boolean isFailOnException() {
return false;
}
public void addEventHandler(
ActivitiEventType eventType,
Class<? extends EventLoggerEventHandler> eventHandlerClass
) {
eventHandlers.put(eventType, eventHandlerClass);
}
public void addEventLoggerListener(EventLoggerListener listener) {
if (listeners == null) {
listeners = new ArrayList<EventLoggerListener>(1);
}
listeners.add(listener);
}
|
/**
* Subclasses that want something else than the database flusher should override this method
*/
protected EventFlusher createEventFlusher() {
return null;
}
public Clock getClock() {
return clock;
}
public void setClock(Clock clock) {
this.clock = clock;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public List<EventLoggerListener> getListeners() {
return listeners;
}
public void setListeners(List<EventLoggerListener> listeners) {
this.listeners = listeners;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\event\logger\EventLogger.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Hierarchy createForCustomer(@NonNull final BPartnerId bPartnerId, @NonNull final BPartnerId salesRepId)
{
if (bPartnerId.equals(salesRepId))
{
return createFor(salesRepId, Hierarchy.builder(), new HashSet<>());
}
final HierarchyBuilder hierarchyBuilder = Hierarchy.builder()
.addChildren(node(salesRepId), ImmutableList.of(node(bPartnerId)));
final HashSet<BPartnerId> seenBPartnerIds = new HashSet<>();
seenBPartnerIds.add(bPartnerId);
return createFor(
salesRepId/* starting point */,
hierarchyBuilder /* result builder */,
seenBPartnerIds /* helper to make sure we don't enter a cycle */
);
}
@NonNull
private Hierarchy createFor(
@NonNull final BPartnerId bPartnerId,
@NonNull final HierarchyBuilder hierarchyBuilder,
@NonNull final HashSet<BPartnerId> seenBPartnerIds)
{
if (!seenBPartnerIds.add(bPartnerId))
{
return hierarchyBuilder.build(); // there is a loop in our supposed tree; stoppping now, because we saw it all
}
final I_C_BPartner bPartnerRecord = loadOutOfTrx(bPartnerId, I_C_BPartner.class);
final BPartnerId parentBPartnerId = BPartnerId.ofRepoIdOrNull(bPartnerRecord.getC_BPartner_SalesRep_ID());
if (parentBPartnerId == null || seenBPartnerIds.contains(parentBPartnerId))
|
{
hierarchyBuilder.addChildren(node(bPartnerId), ImmutableList.of());
return hierarchyBuilder.build();
}
hierarchyBuilder.addChildren(node(parentBPartnerId), ImmutableList.of(node(bPartnerId)));
// recurse
createFor(parentBPartnerId, hierarchyBuilder, seenBPartnerIds);
return hierarchyBuilder.build();
}
private HierarchyNode node(@NonNull final BPartnerId bPartnerId)
{
return HierarchyNode.of(Beneficiary.of(bPartnerId));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\services\hierarchy\CommissionHierarchyFactory.java
| 2
|
请完成以下Java代码
|
public boolean isStockCandidateOfThisCandidate(@NonNull final Candidate potentialStockCandidate)
{
if (potentialStockCandidate.type != CandidateType.STOCK)
{
return false;
}
switch (type)
{
case DEMAND:
return potentialStockCandidate.getParentId().equals(id);
case SUPPLY:
return potentialStockCandidate.getId().equals(parentId);
default:
return false;
}
}
|
/**
* The qty is always stored as an absolute value on the candidate, but we're interested if the candidate is adding or subtracting qty to the stock.
*/
public BigDecimal getStockImpactPlannedQuantity()
{
switch (getType())
{
case DEMAND:
case UNEXPECTED_DECREASE:
case INVENTORY_DOWN:
return getQuantity().negate();
default:
return getQuantity();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\Candidate.java
| 1
|
请完成以下Java代码
|
public int getC_ProjectType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_ProjectType_ID);
}
@Override
public void setDescription (final java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setHelp (final java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
|
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setStandardQty (final BigDecimal StandardQty)
{
set_Value (COLUMNNAME_StandardQty, StandardQty);
}
@Override
public BigDecimal getStandardQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_StandardQty);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Phase.java
| 1
|
请完成以下Java代码
|
public @NonNull String getHandledTableName()
{
return I_M_ShipperTransportation.Table_Name;
}
@Override
public StandardDocumentReportType getStandardDocumentReportType()
{
return StandardDocumentReportType.SHIPPER_TRANSPORTATION;
}
@Override
public @NonNull DocumentReportInfo getDocumentReportInfo(
@NonNull final TableRecordReference recordRef,
@Nullable final PrintFormatId adPrintFormatToUseId, final AdProcessId reportProcessIdToUse)
{
final ShipperTransportationId shipperTransportationId = recordRef.getIdAssumingTableName(I_M_ShipperTransportation.Table_Name, ShipperTransportationId::ofRepoId);
final I_M_ShipperTransportation shipperTransportation = shipperTransportationDAO.getById(shipperTransportationId);
final BPartnerId shipperPartnerId = BPartnerId.ofRepoId(shipperTransportation.getShipper_BPartner_ID());
final I_C_BPartner shipperPartner = util.getBPartnerById(shipperPartnerId);
final DocTypeId docTypeId = DocTypeId.ofRepoId(shipperTransportation.getC_DocType_ID());
final I_C_DocType docType = util.getDocTypeById(docTypeId);
final Language language = util.getBPartnerLanguage(shipperPartner).orElse(null);
final BPPrintFormatQuery bpPrintFormatQuery = BPPrintFormatQuery.builder()
.adTableId(recordRef.getAdTableId())
|
.bpartnerId(shipperPartnerId)
.bPartnerLocationId(BPartnerLocationId.ofRepoId(shipperPartnerId, shipperTransportation.getShipper_Location_ID()))
.docTypeId(docTypeId)
.onlyCopiesGreaterZero(true)
.build();
return DocumentReportInfo.builder()
.recordRef(recordRef)
.reportProcessId(reportProcessIdToUse)
.copies(util.getDocumentCopies(docType, bpPrintFormatQuery))
.documentNo(shipperTransportation.getDocumentNo())
.bpartnerId(shipperPartnerId)
.docTypeId(docTypeId)
.language(language)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\shipping\ShipperTransportationReportAdvisor.java
| 1
|
请完成以下Java代码
|
private String getUserNameAttributeName(OAuth2UserRequest userRequest) {
if (!StringUtils
.hasText(userRequest.getClientRegistration().getProviderDetails().getUserInfoEndpoint().getUri())) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_INFO_URI_ERROR_CODE,
"Missing required UserInfo Uri in UserInfoEndpoint for Client Registration: "
+ userRequest.getClientRegistration().getRegistrationId(),
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
String userNameAttributeName = userRequest.getClientRegistration()
.getProviderDetails()
.getUserInfoEndpoint()
.getUserNameAttributeName();
if (!StringUtils.hasText(userNameAttributeName)) {
OAuth2Error oauth2Error = new OAuth2Error(MISSING_USER_NAME_ATTRIBUTE_ERROR_CODE,
"Missing required \"user name\" attribute name in UserInfoEndpoint for Client Registration: "
+ userRequest.getClientRegistration().getRegistrationId(),
null);
throw new OAuth2AuthenticationException(oauth2Error, oauth2Error.toString());
}
return userNameAttributeName;
}
private Collection<GrantedAuthority> getAuthorities(OAuth2AccessToken token, Map<String, Object> attributes,
String userNameAttributeName) {
Collection<GrantedAuthority> authorities = new LinkedHashSet<>();
authorities.add(new OAuth2UserAuthority(attributes, userNameAttributeName));
for (String authority : token.getScopes()) {
authorities.add(new SimpleGrantedAuthority("SCOPE_" + authority));
}
return authorities;
}
/**
|
* Sets the {@link Converter} used for converting the {@link OAuth2UserRequest} to a
* {@link RequestEntity} representation of the UserInfo Request.
* @param requestEntityConverter the {@link Converter} used for converting to a
* {@link RequestEntity} representation of the UserInfo Request
* @since 5.1
*/
public final void setRequestEntityConverter(Converter<OAuth2UserRequest, RequestEntity<?>> requestEntityConverter) {
Assert.notNull(requestEntityConverter, "requestEntityConverter cannot be null");
this.requestEntityConverter = requestEntityConverter;
}
/**
* Sets the {@link RestOperations} used when requesting the UserInfo resource.
*
* <p>
* <b>NOTE:</b> At a minimum, the supplied {@code restOperations} must be configured
* with the following:
* <ol>
* <li>{@link ResponseErrorHandler} - {@link OAuth2ErrorResponseErrorHandler}</li>
* </ol>
* @param restOperations the {@link RestOperations} used when requesting the UserInfo
* resource
* @since 5.1
*/
public final void setRestOperations(RestOperations restOperations) {
Assert.notNull(restOperations, "restOperations cannot be null");
this.restOperations = restOperations;
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\userinfo\DefaultOAuth2UserService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Menu findOne(Long id) {
Menu menu = menuRepository.findById(id).orElseGet(Menu::new);
ValidationUtil.isNull(menu.getId(),"Menu","id",id);
return menu;
}
@Override
public void download(List<MenuDto> menuDtos, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (MenuDto menuDTO : menuDtos) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("菜单标题", menuDTO.getTitle());
map.put("菜单类型", menuDTO.getType() == null ? "目录" : menuDTO.getType() == 1 ? "菜单" : "按钮");
map.put("权限标识", menuDTO.getPermission());
map.put("外链菜单", menuDTO.getIFrame() ? YES_STR : NO_STR);
map.put("菜单可见", menuDTO.getHidden() ? NO_STR : YES_STR);
map.put("是否缓存", menuDTO.getCache() ? YES_STR : NO_STR);
map.put("创建日期", menuDTO.getCreateTime());
list.add(map);
}
FileUtil.downloadExcel(list, response);
}
private void updateSubCnt(Long menuId){
if(menuId != null){
int count = menuRepository.countByPid(menuId);
menuRepository.updateSubCntById(count, menuId);
}
}
/**
* 清理缓存
* @param id 菜单ID
*/
public void delCaches(Long id){
List<User> users = userRepository.findByMenuId(id);
redisUtils.del(CacheKey.MENU_ID + id);
redisUtils.delByKeys(CacheKey.MENU_USER, users.stream().map(User::getId).collect(Collectors.toSet()));
// 清除 Role 缓存
List<Role> roles = roleService.findInMenuId(new ArrayList<Long>(){{
add(id);
}});
redisUtils.delByKeys(CacheKey.ROLE_ID, roles.stream().map(Role::getId).collect(Collectors.toSet()));
}
|
/**
* 构建前端路由
* @param menuDTO /
* @param menuVo /
* @return /
*/
private static MenuVo getMenuVo(MenuDto menuDTO, MenuVo menuVo) {
MenuVo menuVo1 = new MenuVo();
menuVo1.setMeta(menuVo.getMeta());
// 非外链
if(!menuDTO.getIFrame()){
menuVo1.setPath("index");
menuVo1.setName(menuVo.getName());
menuVo1.setComponent(menuVo.getComponent());
} else {
menuVo1.setPath(menuDTO.getPath());
}
return menuVo1;
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\MenuServiceImpl.java
| 2
|
请完成以下Java代码
|
public class AWindowSaveState
{
public static void createAndAdd(final APanel panel, final JMenu menu)
{
final AWindowSaveState app = new AWindowSaveState(panel);
final JMenuItem menuItem = app.getJMenuItem();
menu.add(menuItem);
}
private final AWindowSaveStateModel model = new AWindowSaveStateModel();
private final APanel parent;
private final AppsAction action;
public AWindowSaveState(final APanel parent)
{
super();
Check.assumeNotNull(parent, "parent not null");
this.parent = parent;
this.action = AppsAction.builder()
.setAction(model.getActionName())
.build();
action.setDelegate(new ActionListener()
{
@Override
public void actionPerformed(ActionEvent e)
{
save();
}
});
checkEnabled();
}
public JMenuItem getJMenuItem()
{
return action.getMenuItem();
}
private boolean checkEnabled()
{
final boolean enabled = model.isEnabled();
action.setEnabled(enabled);
final JMenuItem menuItem = action.getMenuItem();
menuItem.setEnabled(enabled);
menuItem.setVisible(enabled);
return enabled;
}
private void assertEnabled()
{
if (!checkEnabled())
{
throw new AdempiereException("Action is not enabled");
}
}
private void save()
{
assertEnabled();
final GridController gc = parent.getCurrentGridController();
save(gc);
|
for (final GridController child : gc.getChildGridControllers())
{
save(child);
}
}
private void save(final GridController gc)
{
Check.assumeNotNull(gc, "gc not null");
final GridTab gridTab = gc.getMTab();
final VTable table = gc.getVTable();
//
// Check CTable to GridTab synchronizer
final CTableColumns2GridTabSynchronizer synchronizer = CTableColumns2GridTabSynchronizer.get(table);
if (synchronizer == null)
{
// synchronizer does not exist, nothing to save
return;
}
//
// Make sure we have the latest values in GridTab
synchronizer.saveToGridTab();
//
// Ask model to settings to database
model.save(gridTab);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\AWindowSaveState.java
| 1
|
请完成以下Java代码
|
public java.math.BigDecimal getUnitsCycles ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_UnitsCycles);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Waiting Time.
@param WaitingTime
Workflow Simulation Waiting time
*/
@Override
public void setWaitingTime (int WaitingTime)
{
set_Value (COLUMNNAME_WaitingTime, Integer.valueOf(WaitingTime));
}
/** Get Waiting Time.
@return Workflow Simulation Waiting time
*/
@Override
public int getWaitingTime ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_WaitingTime);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Working Time.
@param WorkingTime
Workflow Simulation Execution Time
*/
@Override
public void setWorkingTime (int WorkingTime)
{
set_Value (COLUMNNAME_WorkingTime, Integer.valueOf(WorkingTime));
}
/** Get Working Time.
|
@return Workflow Simulation Execution Time
*/
@Override
public int getWorkingTime ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_WorkingTime);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Yield %.
@param Yield
The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent
*/
@Override
public void setYield (int Yield)
{
set_Value (COLUMNNAME_Yield, Integer.valueOf(Yield));
}
/** Get Yield %.
@return The Yield is the percentage of a lot that is expected to be of acceptable wuality may fall below 100 percent
*/
@Override
public int getYield ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Yield);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Workflow.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
@Override
public int hashCode() {
final int prime = 31;
|
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (obj instanceof EqualById) {
return ((EqualById) obj).getId().equals(getId());
}
return false;
}
}
|
repos\tutorials-master\persistence-modules\java-jpa-3\src\main\java\com\baeldung\jpa\equality\EqualById.java
| 1
|
请完成以下Java代码
|
public Void execute(CommandContext commandContext) {
if (deploymentId == null) {
throw new ActivitiIllegalArgumentException("deploymentId is null");
}
// Update all entities
DeploymentEntity deployment = commandContext.getDeploymentEntityManager().findById(deploymentId);
if (deployment == null) {
throw new ActivitiObjectNotFoundException(
"Could not find deployment with id " + deploymentId,
Deployment.class
);
}
executeInternal(commandContext, deployment);
return null;
}
protected void executeInternal(CommandContext commandContext, DeploymentEntity deployment) {
String oldTenantId = deployment.getTenantId();
deployment.setTenantId(newTenantId);
// Doing process instances, executions and tasks with direct SQL updates
// (otherwise would not be performant)
commandContext
.getProcessDefinitionEntityManager()
.updateProcessDefinitionTenantIdForDeployment(deploymentId, newTenantId);
commandContext.getExecutionEntityManager().updateExecutionTenantIdForDeployment(deploymentId, newTenantId);
commandContext.getTaskEntityManager().updateTaskTenantIdForDeployment(deploymentId, newTenantId);
commandContext.getJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId);
commandContext.getTimerJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId);
commandContext.getSuspendedJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId);
|
commandContext.getDeadLetterJobEntityManager().updateJobTenantIdForDeployment(deploymentId, newTenantId);
commandContext.getEventSubscriptionEntityManager().updateEventSubscriptionTenantId(oldTenantId, newTenantId);
// Doing process definitions in memory, cause we need to clear the process definition cache
List<ProcessDefinition> processDefinitions = new ProcessDefinitionQueryImpl().deploymentId(deploymentId).list();
for (ProcessDefinition processDefinition : processDefinitions) {
commandContext
.getProcessEngineConfiguration()
.getProcessDefinitionCache()
.remove(processDefinition.getId());
}
// Clear process definition cache
commandContext.getProcessEngineConfiguration().getProcessDefinitionCache().clear();
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\ChangeDeploymentTenantIdCmd.java
| 1
|
请完成以下Java代码
|
public PickingSlotQueues getNotEmptyQueues(@NonNull final PickingSlotQueueQuery query)
{
return pickingSlotQueueRepository.getNotEmptyQueues(query);
}
public PickingSlotQueue getPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId)
{
return pickingSlotQueueRepository.getPickingSlotQueue(pickingSlotId);
}
public void removeFromPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, @NonNull final Set<HuId> huIdsToRemove)
{
huPickingSlotBL.removeFromPickingSlotQueue(pickingSlotId, huIdsToRemove);
}
public List<PickingSlotReservation> getPickingSlotReservations(@NonNull Set<PickingSlotId> pickingSlotIds)
{
return pickingSlotRepository.getByIds(pickingSlotIds)
.stream()
.map(PickingSlotService::extractReservation)
.collect(ImmutableList.toImmutableList());
}
private static PickingSlotReservation extractReservation(final I_M_PickingSlot pickingSlot)
{
return PickingSlotReservation.builder()
.pickingSlotId(PickingSlotId.ofRepoId(pickingSlot.getM_PickingSlot_ID()))
.reservationValue(extractReservationValue(pickingSlot))
.build();
}
|
private static PickingSlotReservationValue extractReservationValue(final I_M_PickingSlot pickingSlot)
{
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(pickingSlot.getC_BPartner_ID());
return PickingSlotReservationValue.builder()
.bpartnerId(bpartnerId)
.bpartnerLocationId(BPartnerLocationId.ofRepoIdOrNull(bpartnerId, pickingSlot.getC_BPartner_Location_ID()))
.build();
}
public void addToPickingSlotQueue(@NonNull final PickingSlotId pickingSlotId, @NonNull final Set<HuId> huIds)
{
huPickingSlotBL.addToPickingSlotQueue(pickingSlotId, huIds);
}
public PickingSlotQueuesSummary getNotEmptyQueuesSummary(@NonNull final PickingSlotQueueQuery query)
{
return pickingSlotQueueRepository.getNotEmptyQueuesSummary(query);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\PickingSlotService.java
| 1
|
请完成以下Java代码
|
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Mark 1 Percent.
@param Mark1Percent
Percentage up to this color is used
*/
public void setMark1Percent (int Mark1Percent)
{
set_Value (COLUMNNAME_Mark1Percent, Integer.valueOf(Mark1Percent));
}
/** Get Mark 1 Percent.
@return Percentage up to this color is used
*/
public int getMark1Percent ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Mark1Percent);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Mark 2 Percent.
@param Mark2Percent
Percentage up to this color is used
*/
public void setMark2Percent (int Mark2Percent)
{
set_Value (COLUMNNAME_Mark2Percent, Integer.valueOf(Mark2Percent));
}
/** Get Mark 2 Percent.
@return Percentage up to this color is used
*/
public int getMark2Percent ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Mark2Percent);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Mark 3 Percent.
@param Mark3Percent
Percentage up to this color is used
*/
public void setMark3Percent (int Mark3Percent)
{
set_Value (COLUMNNAME_Mark3Percent, Integer.valueOf(Mark3Percent));
}
/** Get Mark 3 Percent.
@return Percentage up to this color is used
*/
public int getMark3Percent ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Mark3Percent);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Mark 4 Percent.
@param Mark4Percent
Percentage up to this color is used
*/
public void setMark4Percent (int Mark4Percent)
{
set_Value (COLUMNNAME_Mark4Percent, Integer.valueOf(Mark4Percent));
}
/** Get Mark 4 Percent.
@return Percentage up to this color is used
*/
public int getMark4Percent ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Mark4Percent);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
|
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Color Schema.
@param PA_ColorSchema_ID
Performance Color Schema
*/
public void setPA_ColorSchema_ID (int PA_ColorSchema_ID)
{
if (PA_ColorSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ColorSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ColorSchema_ID, Integer.valueOf(PA_ColorSchema_ID));
}
/** Get Color Schema.
@return Performance Color Schema
*/
public int getPA_ColorSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ColorSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ColorSchema.java
| 1
|
请完成以下Java代码
|
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model)
throws Exception {
String source = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_SOURCE);
String sourceExpression = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_SOURCE_EXPRESSION);
String target = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_TARGET);
if (
(StringUtils.isNotEmpty(source) || StringUtils.isNotEmpty(sourceExpression)) &&
StringUtils.isNotEmpty(target)
) {
IOParameter parameter = new IOParameter();
if (StringUtils.isNotEmpty(sourceExpression)) {
parameter.setSourceExpression(sourceExpression);
} else {
parameter.setSource(source);
}
parameter.setTarget(target);
((CallActivity) parentElement).getInParameters().add(parameter);
}
}
}
public class OutParameterParser extends BaseChildElementParser {
public String getElementName() {
return ELEMENT_CALL_ACTIVITY_OUT_PARAMETERS;
|
}
public void parseChildElement(XMLStreamReader xtr, BaseElement parentElement, BpmnModel model)
throws Exception {
String source = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_SOURCE);
String sourceExpression = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_SOURCE_EXPRESSION);
String target = xtr.getAttributeValue(null, ATTRIBUTE_IOPARAMETER_TARGET);
if (
(StringUtils.isNotEmpty(source) || StringUtils.isNotEmpty(sourceExpression)) &&
StringUtils.isNotEmpty(target)
) {
IOParameter parameter = new IOParameter();
if (StringUtils.isNotEmpty(sourceExpression)) {
parameter.setSourceExpression(sourceExpression);
} else {
parameter.setSource(source);
}
parameter.setTarget(target);
((CallActivity) parentElement).getOutParameters().add(parameter);
}
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\CallActivityXMLConverter.java
| 1
|
请完成以下Java代码
|
public class ProductProposalPrice
{
@Getter
private final BigDecimal userEnteredPriceValue;
@Getter
private final CurrencyCode currencyCode;
private final Amount priceListPrice;
private final ProductProposalCampaignPrice campaignPrice;
@Getter
private final boolean campaignPriceUsed;
@Getter
private final boolean priceListPriceUsed;
@Builder(toBuilder = true)
private ProductProposalPrice(
@NonNull final Amount priceListPrice,
@Nullable final ProductProposalCampaignPrice campaignPrice,
@Nullable final BigDecimal userEnteredPriceValue)
{
this.priceListPrice = priceListPrice;
this.campaignPrice = campaignPrice;
//
this.currencyCode = priceListPrice.getCurrencyCode();
if (campaignPrice != null && !currencyCode.equals(campaignPrice.getCurrencyCode()))
{
throw new AdempiereException("" + campaignPrice + " and " + priceListPrice + " shall have the same currency");
}
//
if (userEnteredPriceValue != null)
{
this.userEnteredPriceValue = userEnteredPriceValue;
}
else if (campaignPrice != null)
{
this.userEnteredPriceValue = campaignPrice.applyOn(priceListPrice).getAsBigDecimal();
}
else
|
{
this.userEnteredPriceValue = priceListPrice.getAsBigDecimal();
}
//
this.priceListPriceUsed = this.priceListPrice.valueComparingEqualsTo(this.userEnteredPriceValue);
this.campaignPriceUsed = this.campaignPrice != null
&& !priceListPriceUsed
&& this.campaignPrice.amountValueComparingEqualsTo(this.userEnteredPriceValue);
}
public Amount getUserEnteredPrice()
{
return Amount.of(getUserEnteredPriceValue(), getCurrencyCode());
}
public ProductProposalPrice withUserEnteredPriceValue(@NonNull final BigDecimal userEnteredPriceValue)
{
if (this.userEnteredPriceValue.equals(userEnteredPriceValue))
{
return this;
}
return toBuilder().userEnteredPriceValue(userEnteredPriceValue).build();
}
public ProductProposalPrice withPriceListPriceValue(@NonNull final BigDecimal priceListPriceValue)
{
return withPriceListPrice(Amount.of(priceListPriceValue, getCurrencyCode()));
}
public ProductProposalPrice withPriceListPrice(@NonNull final Amount priceListPrice)
{
if (this.priceListPrice.equals(priceListPrice))
{
return this;
}
return toBuilder().priceListPrice(priceListPrice).build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\model\ProductProposalPrice.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public float getScore(boolean normalized)
{
// if (normalized && actionHistory.size() > 0)
// return score / actionHistory.size();
return score;
}
public void addScore(float score)
{
this.score += score;
}
public void setScore(float score)
{
this.score = score;
}
public void addAction(int action)
{
actionHistory.add(action);
}
@Override
public int compareTo(Object o)
{
if (!(o instanceof Configuration))
return hashCode() - o.hashCode();
// may be unsafe
Configuration configuration = (Configuration) o;
float diff = getScore(true) - configuration.getScore(true);
if (diff > 0)
return (int) Math.ceil(diff);
else if (diff < 0)
return (int) Math.floor(diff);
else
return 0;
}
|
@Override
public boolean equals(Object o)
{
if (o instanceof Configuration)
{
Configuration configuration = (Configuration) o;
if (configuration.score != score)
return false;
if (configuration.actionHistory.size() != actionHistory.size())
return false;
for (int i = 0; i < actionHistory.size(); i++)
if (!actionHistory.get(i).equals(configuration.actionHistory.get(i)))
return false;
return true;
}
return false;
}
@Override
public Configuration clone()
{
Configuration configuration = new Configuration(sentence);
configuration.actionHistory = new ArrayList<Integer>(actionHistory);
configuration.score = score;
configuration.state = state.clone();
return configuration;
}
@Override
public int hashCode()
{
int hashCode = 0;
int i = 0;
for (int action : actionHistory)
hashCode += action << i++;
hashCode += score;
return hashCode;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dependency\perceptron\transition\configuration\Configuration.java
| 2
|
请完成以下Java代码
|
public static final TableResource ofAD_Table_ID(final int adTableId)
{
return new TableResource(adTableId);
}
private final int adTableId;
private TableResource(final int adTableId)
{
Check.assume(adTableId > 0, "AD_Table_ID > 0");
this.adTableId = adTableId;
}
/** "Any table" constructor */
private TableResource()
{
this.adTableId = -1;
|
}
@Override
public String toString()
{
if (this == ANY_TABLE)
{
return "@AD_Table_ID@=*";
}
else
{
return "@AD_Table_ID@=" + adTableId;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\TableResource.java
| 1
|
请完成以下Java代码
|
public JsonCreateIssueResponse createIssue(final @NonNull JsonError jsonError, final @NonNull PInstanceId pInstanceId)
{
final List<JsonCreateIssueResponseItem> adIssueIds = jsonError
.getErrors()
.stream()
.map(error -> createInsertRemoteIssueRequest(error, pInstanceId))
.map(errorManager::insertRemoteIssue)
.map(id -> JsonCreateIssueResponseItem.builder().issueId(JsonMetasfreshId.of(id.getRepoId())).build())
.collect(Collectors.toList());
return JsonCreateIssueResponse.builder()
.ids(adIssueIds)
.build();
}
public void storeExternalPinstanceLog(@NonNull final CreatePInstanceLogRequest request, @NonNull final PInstanceId pInstanceId)
{
try
{
final List<ProcessInfoLog> processInfoLogList = request.getLogs()
.stream()
.map(JsonPInstanceLog::getMessage)
.map(ProcessInfoLog::ofMessage)
.collect(Collectors.toList());
instanceDAO.saveProcessInfoLogs(pInstanceId, processInfoLogList);
}
catch (final Exception e)
{
final AdIssueId issueId = Services.get(IErrorManager.class).createIssue(e);
logger.error("Could not save the given model; message={}; AD_Issue_ID={}", e.getLocalizedMessage(), issueId);
throw e;
}
}
@NonNull
public Optional<ExternalSystemParentConfig> getByTypeAndValue(@NonNull final ExternalSystemType type, @NonNull final String childConfigValue)
{
return externalSystemConfigRepo.getByTypeAndValue(type, childConfigValue);
}
@NonNull
public Optional<ExternalSystemExportAudit> getMostRecentByTableReferenceAndSystem(
@NonNull final TableRecordReference tableRecordReference,
@NonNull final ExternalSystemType externalSystemType)
{
|
return externalSystemExportAuditRepo.getMostRecentByTableReferenceAndSystem(tableRecordReference, externalSystemType);
}
@NonNull
public ExternalSystemExportAudit createESExportAudit(@NonNull final CreateExportAuditRequest request)
{
return externalSystemExportAuditRepo.createESExportAudit(request);
}
@NonNull
private InsertRemoteIssueRequest createInsertRemoteIssueRequest(final JsonErrorItem jsonErrorItem, final PInstanceId pInstanceId)
{
return InsertRemoteIssueRequest.builder()
.issueCategory(jsonErrorItem.getIssueCategory())
.issueSummary(StringUtils.isEmpty(jsonErrorItem.getMessage()) ? DEFAULT_ISSUE_SUMMARY : jsonErrorItem.getMessage())
.sourceClassName(jsonErrorItem.getSourceClassName())
.sourceMethodName(jsonErrorItem.getSourceMethodName())
.stacktrace(jsonErrorItem.getStackTrace())
.errorCode(jsonErrorItem.getErrorCode())
.pInstance_ID(pInstanceId)
.orgId(RestUtils.retrieveOrgIdOrDefault(jsonErrorItem.getOrgCode()))
.build();
}
@Nullable
public ExternalSystemType getExternalSystemTypeByCodeOrNameOrNull(@Nullable final String value)
{
final ExternalSystem externalSystem = value != null
? externalSystemRepository.getByLegacyCodeOrValueOrNull(value)
: null;
return externalSystem != null
? externalSystem.getType()
: null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\externlasystem\dto\ExternalSystemService.java
| 1
|
请完成以下Spring Boot application配置
|
spring.datasource.url=jdbc:postgresql://localhost:5433/yugabyte
spring.datasource.username=yugabyte
spring.datasource.password=yugabyte
spring.jpa.hibernate.ddl-auto=cr
|
eate
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
|
repos\tutorials-master\persistence-modules\spring-data-yugabytedb\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public DeploymentQueryImpl deploymentWithoutTenantId() {
this.withoutTenantId = true;
return this;
}
public DeploymentQueryImpl processDefinitionKey(String key) {
if (key == null) {
throw new ActivitiIllegalArgumentException("key is null");
}
this.processDefinitionKey = key;
return this;
}
public DeploymentQueryImpl processDefinitionKeyLike(String keyLike) {
if (keyLike == null) {
throw new ActivitiIllegalArgumentException("keyLike is null");
}
this.processDefinitionKeyLike = keyLike;
return this;
}
public DeploymentQueryImpl latest() {
if (key == null) {
throw new ActivitiIllegalArgumentException("latest can only be used together with a deployment key");
}
this.latest = true;
return this;
}
@Override
public DeploymentQuery latestVersion() {
this.latestVersion = true;
return this;
}
// sorting ////////////////////////////////////////////////////////
public DeploymentQuery orderByDeploymentId() {
return orderBy(DeploymentQueryProperty.DEPLOYMENT_ID);
}
public DeploymentQuery orderByDeploymenTime() {
return orderBy(DeploymentQueryProperty.DEPLOY_TIME);
}
public DeploymentQuery orderByDeploymentName() {
return orderBy(DeploymentQueryProperty.DEPLOYMENT_NAME);
}
public DeploymentQuery orderByTenantId() {
return orderBy(DeploymentQueryProperty.DEPLOYMENT_TENANT_ID);
}
// results ////////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
|
checkQueryOk();
return commandContext.getDeploymentEntityManager().findDeploymentCountByQueryCriteria(this);
}
@Override
public List<Deployment> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getDeploymentEntityManager().findDeploymentsByQueryCriteria(this, page);
}
// getters ////////////////////////////////////////////////////////
public String getDeploymentId() {
return deploymentId;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public String getCategory() {
return category;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public String getProcessDefinitionKeyLike() {
return processDefinitionKeyLike;
}
public boolean isLatestVersion() {
return latestVersion;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\DeploymentQueryImpl.java
| 1
|
请完成以下Java代码
|
public Builder setUserElementString1(final String userElementString1)
{
setSegmentValue(AcctSegmentType.UserElementString1, userElementString1);
return this;
}
public Builder setUserElementString2(final String userElementString2)
{
setSegmentValue(AcctSegmentType.UserElementString2, userElementString2);
return this;
}
public Builder setUserElementString3(final String userElementString3)
{
setSegmentValue(AcctSegmentType.UserElementString3, userElementString3);
return this;
}
public Builder setUserElementString4(final String userElementString4)
{
setSegmentValue(AcctSegmentType.UserElementString4, userElementString4);
return this;
}
|
public Builder setUserElementString5(final String userElementString5)
{
setSegmentValue(AcctSegmentType.UserElementString5, userElementString5);
return this;
}
public Builder setUserElementString6(final String userElementString6)
{
setSegmentValue(AcctSegmentType.UserElementString6, userElementString6);
return this;
}
public Builder setUserElementString7(final String userElementString7)
{
setSegmentValue(AcctSegmentType.UserElementString7, userElementString7);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\AccountDimension.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WebController {
private PersonRepository personRepository;
private StudentRepository studentRepository;
public WebController(PersonRepository personRepository, StudentRepository studentRepository) {
this.personRepository = personRepository;
this.studentRepository = studentRepository;
}
@PostMapping("/person")
public Person save(@RequestBody Person person) {
return personRepository.save(person);
}
@GetMapping("/person")
public Person get(@PathParam("name") String name, @PathParam("searchLastName") String searchLastName) {
if (name != null)
return this.personRepository.findByName(name)
.orElseThrow(() -> new RuntimeException("person not found"));
if (searchLastName != null)
return this.personRepository.searchByLastName(searchLastName)
.orElseThrow(() -> new RuntimeException("person not found"));
return null;
}
// ---- Student Endpoints
@PostMapping("/student")
public Student saveStudent(@RequestBody Student student) {
return studentRepository.save(student);
}
|
@GetMapping("/student")
public Student getStudent(@PathParam("name") String name, @PathParam("searchLastName") String searchLastName) {
if (name != null)
return this.studentRepository.findByName(name)
.orElseThrow(() -> new RuntimeException("Student not found"));
if (searchLastName != null)
return this.studentRepository.searchByLastName(searchLastName)
.orElseThrow(() -> new RuntimeException("Student not found"));
return null;
}
@ExceptionHandler(value = RuntimeException.class)
public ResponseEntity handleError(RuntimeException e) {
return ResponseEntity
.status(HttpStatus.NOT_FOUND)
.body(e.getMessage());
}
}
|
repos\springboot-demo-master\RedisSearch\src\main\java\com\et\controller\WebController.java
| 2
|
请完成以下Java代码
|
public java.lang.String getSkonto()
{
return get_ValueAsString(COLUMNNAME_Skonto);
}
@Override
public void setUmsatz (final @Nullable java.lang.String Umsatz)
{
set_Value (COLUMNNAME_Umsatz, Umsatz);
}
@Override
public java.lang.String getUmsatz()
{
return get_ValueAsString(COLUMNNAME_Umsatz);
}
@Override
public void setZI_Art (final @Nullable java.lang.String ZI_Art)
{
set_Value (COLUMNNAME_ZI_Art, ZI_Art);
}
@Override
|
public java.lang.String getZI_Art()
{
return get_ValueAsString(COLUMNNAME_ZI_Art);
}
@Override
public void setZI_Inhalt (final @Nullable java.lang.String ZI_Inhalt)
{
set_Value (COLUMNNAME_ZI_Inhalt, ZI_Inhalt);
}
@Override
public java.lang.String getZI_Inhalt()
{
return get_ValueAsString(COLUMNNAME_ZI_Inhalt);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_DatevAcctExportLine.java
| 1
|
请完成以下Java代码
|
public class IntentEventListenerActivityBehaviour extends CoreCmmnTriggerableActivityBehavior implements PlanItemActivityBehavior {
protected IntentEventListener intentEventListener;
public IntentEventListenerActivityBehaviour(IntentEventListener intentEventListener) {
this.intentEventListener = intentEventListener;
}
@Override
public void onStateTransition(CommandContext commandContext, DelegatePlanItemInstance planItemInstance, String transition) {
// No logic is needed
}
@Override
public void execute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
// Nothing to do, logic happens on state transition
}
@Override
|
public void trigger(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
RepetitionRule repetitionRule = ExpressionUtil.getRepetitionRule(planItemInstanceEntity);
if (repetitionRule != null && ExpressionUtil.evaluateRepetitionRule(commandContext, planItemInstanceEntity, planItemInstanceEntity.getStagePlanItemInstanceEntity())) {
PlanItemInstanceEntity eventPlanItemInstanceEntity = PlanItemInstanceUtil.copyAndInsertPlanItemInstance(commandContext, planItemInstanceEntity, false, false);
CmmnEngineAgenda agenda = CommandContextUtil.getAgenda(commandContext);
agenda.planCreatePlanItemInstanceWithoutEvaluationOperation(eventPlanItemInstanceEntity);
agenda.planOccurPlanItemInstanceOperation(eventPlanItemInstanceEntity);
CommandContextUtil.getCmmnEngineConfiguration(commandContext).getListenerNotificationHelper().executeLifecycleListeners(
commandContext, planItemInstanceEntity, PlanItemInstanceState.ACTIVE, PlanItemInstanceState.AVAILABLE);
} else {
CommandContextUtil.getAgenda(commandContext).planOccurPlanItemInstanceOperation(planItemInstanceEntity);
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\IntentEventListenerActivityBehaviour.java
| 1
|
请完成以下Java代码
|
public String getBom() {
return this.bom;
}
public void setBom(String bom) {
this.bom = bom;
}
/**
* Return the default repository to associate to all dependencies of this group unless
* specified otherwise.
* @return the repository
*/
public String getRepository() {
return this.repository;
}
public void setRepository(String repository) {
this.repository = repository;
}
|
/**
* Return the {@link Dependency dependencies} of this group.
* @return the content
*/
public List<Dependency> getContent() {
return this.content;
}
/**
* Create a new {@link DependencyGroup} instance with the given name.
* @param name the name of the group
* @return a new {@link DependencyGroup} instance
*/
public static DependencyGroup create(String name) {
DependencyGroup group = new DependencyGroup();
group.setName(name);
return group;
}
}
|
repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\DependencyGroup.java
| 1
|
请完成以下Java代码
|
private TsKvEntry getValueWithTs(TsKvEntry tsKvEntry) {
var mapper = TbMsgSource.DATA.equals(fetchTo) ? JacksonUtil.OBJECT_MAPPER : JacksonUtil.ALLOW_UNQUOTED_FIELD_NAMES_MAPPER;
var value = JacksonUtil.newObjectNode(mapper);
value.put(TS, tsKvEntry.getTs());
JacksonUtil.addKvEntry(value, tsKvEntry, VALUE, mapper);
return new BasicTsKvEntry(tsKvEntry.getTs(), new JsonDataEntry(tsKvEntry.getKey(), value.toString()));
}
private String getPrefix(String scope) {
var prefix = "";
switch (scope) {
case CLIENT_SCOPE:
prefix = "cs_";
break;
case SHARED_SCOPE:
prefix = "shared_";
break;
case SERVER_SCOPE:
prefix = "ss_";
break;
}
|
return prefix;
}
private List<String> getNonExistentKeys(List<AttributeKvEntry> existingAttributesKvEntry, List<String> allKeys) {
List<String> existingKeys = existingAttributesKvEntry.stream().map(KvEntry::getKey).collect(Collectors.toList());
return allKeys.stream().filter(key -> !existingKeys.contains(key)).collect(Collectors.toList());
}
private RuntimeException reportFailures(Set<TbPair<String, List<String>>> failuresPairSet) {
var errorMessage = new StringBuilder("The following attribute/telemetry keys is not present in the DB: ").append("\n");
failuresPairSet.forEach(failurePair -> {
String scope = failurePair.getFirst();
List<String> nonExistentKeys = failurePair.getSecond();
errorMessage.append("\t").append("[").append(scope).append("]:").append(nonExistentKeys.toString()).append("\n");
});
failuresPairSet.clear();
return new RuntimeException(errorMessage.toString());
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\metadata\TbAbstractGetAttributesNode.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getGLN() {
return gln;
}
/**
* Sets the value of the gln property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGLN(String value) {
this.gln = value;
}
/**
* Further contact details.
*
* @return
* possible object is
* {@link ContactType }
*
*/
public ContactType getContact() {
return contact;
}
/**
* Sets the value of the contact property.
*
* @param value
* allowed object is
* {@link ContactType }
*
*/
public void setContact(ContactType value) {
this.contact = value;
|
}
/**
* Address details of the party.
*
* @return
* possible object is
* {@link AddressType }
*
*/
public AddressType getAddress() {
return address;
}
/**
* Sets the value of the address property.
*
* @param value
* allowed object is
* {@link AddressType }
*
*/
public void setAddress(AddressType value) {
this.address = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\BusinessEntityType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Iterator<ConfigDataEnvironmentContributor> iterator() {
return this.root.iterator();
}
/**
* {@link ConfigDataLocationResolverContext} for a contributor.
*/
private static class ContributorDataLoaderContext implements ConfigDataLoaderContext {
private final ConfigDataEnvironmentContributors contributors;
ContributorDataLoaderContext(ConfigDataEnvironmentContributors contributors) {
this.contributors = contributors;
}
@Override
public ConfigurableBootstrapContext getBootstrapContext() {
return this.contributors.getBootstrapContext();
}
}
/**
* {@link ConfigDataLocationResolverContext} for a contributor.
*/
private static class ContributorConfigDataLocationResolverContext implements ConfigDataLocationResolverContext {
private final ConfigDataEnvironmentContributors contributors;
private final ConfigDataEnvironmentContributor contributor;
private final @Nullable ConfigDataActivationContext activationContext;
private volatile @Nullable Binder binder;
ContributorConfigDataLocationResolverContext(ConfigDataEnvironmentContributors contributors,
ConfigDataEnvironmentContributor contributor, @Nullable ConfigDataActivationContext activationContext) {
this.contributors = contributors;
this.contributor = contributor;
this.activationContext = activationContext;
}
@Override
public Binder getBinder() {
Binder binder = this.binder;
if (binder == null) {
binder = this.contributors.getBinder(this.activationContext);
this.binder = binder;
}
return binder;
}
|
@Override
public @Nullable ConfigDataResource getParent() {
return this.contributor.getResource();
}
@Override
public ConfigurableBootstrapContext getBootstrapContext() {
return this.contributors.getBootstrapContext();
}
}
private class InactiveSourceChecker implements BindHandler {
private final @Nullable ConfigDataActivationContext activationContext;
InactiveSourceChecker(@Nullable ConfigDataActivationContext activationContext) {
this.activationContext = activationContext;
}
@Override
public Object onSuccess(ConfigurationPropertyName name, Bindable<?> target, BindContext context,
Object result) {
for (ConfigDataEnvironmentContributor contributor : ConfigDataEnvironmentContributors.this) {
if (!contributor.isActive(this.activationContext)) {
InactiveConfigDataAccessException.throwIfPropertyFound(contributor, name);
}
}
return result;
}
}
/**
* Binder options that can be used with
* {@link ConfigDataEnvironmentContributors#getBinder(ConfigDataActivationContext, BinderOption...)}.
*/
enum BinderOption {
/**
* Throw an exception if an inactive contributor contains a bound value.
*/
FAIL_ON_BIND_TO_INACTIVE_SOURCE
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\config\ConfigDataEnvironmentContributors.java
| 2
|
请完成以下Java代码
|
public static DistributionFacetId ofProductId(@NonNull ProductId productId)
{
return ofRepoId(DistributionFacetGroupType.PRODUCT, productId);
}
private static DistributionFacetId ofRepoId(@NonNull DistributionFacetGroupType groupType, @NonNull RepoIdAware id)
{
final WorkflowLaunchersFacetId workflowLaunchersFacetId = WorkflowLaunchersFacetId.ofId(groupType.toWorkflowLaunchersFacetGroupId(), id);
return ofWorkflowLaunchersFacetId(workflowLaunchersFacetId);
}
@SuppressWarnings("SameParameterValue")
private static DistributionFacetId ofLocalDate(@NonNull DistributionFacetGroupType groupType, @NonNull LocalDate localDate)
{
final WorkflowLaunchersFacetId workflowLaunchersFacetId = WorkflowLaunchersFacetId.ofLocalDate(groupType.toWorkflowLaunchersFacetGroupId(), localDate);
return ofWorkflowLaunchersFacetId(workflowLaunchersFacetId);
}
public static DistributionFacetId ofQuantity(@NonNull Quantity qty)
{
return ofWorkflowLaunchersFacetId(
WorkflowLaunchersFacetId.ofQuantity(
DistributionFacetGroupType.QUANTITY.toWorkflowLaunchersFacetGroupId(),
qty.toBigDecimal(),
qty.getUomId()
)
);
|
}
public static DistributionFacetId ofPlantId(@NonNull final ResourceId plantId)
{
return ofRepoId(DistributionFacetGroupType.PLANT_RESOURCE_ID, plantId);
}
private static Quantity getAsQuantity(final @NonNull WorkflowLaunchersFacetId workflowLaunchersFacetId)
{
final ImmutablePair<BigDecimal, Integer> parts = workflowLaunchersFacetId.getAsQuantity();
return Quantitys.of(parts.getLeft(), UomId.ofRepoId(parts.getRight()));
}
public WorkflowLaunchersFacetId toWorkflowLaunchersFacetId() {return workflowLaunchersFacetId;}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetId.java
| 1
|
请完成以下Java代码
|
public void onMsg(TbContext ctx, TbMsg msg) {
var tbMsg = ackIfNeeded(ctx, msg);
httpClient.processMessage(ctx, tbMsg,
m -> tellSuccess(ctx, m),
(m, t) -> tellFailure(ctx, m, t));
}
@Override
public void destroy() {
if (this.httpClient != null) {
this.httpClient.destroy();
}
}
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
boolean hasChanges = false;
switch (fromVersion) {
case 0:
if (!oldConfiguration.has(PARSE_TO_PLAIN_TEXT) && oldConfiguration.has(TRIM_DOUBLE_QUOTES)) {
hasChanges = true;
((ObjectNode) oldConfiguration).put(PARSE_TO_PLAIN_TEXT, oldConfiguration.get(TRIM_DOUBLE_QUOTES).booleanValue());
((ObjectNode) oldConfiguration).remove(TRIM_DOUBLE_QUOTES);
}
case 1:
|
if (oldConfiguration.has("useRedisQueueForMsgPersistence")) {
hasChanges = true;
((ObjectNode) oldConfiguration).remove(List.of("useRedisQueueForMsgPersistence", "trimQueue", "maxQueueSize"));
}
case 2:
if (!oldConfiguration.has(MAX_IN_MEMORY_BUFFER_SIZE_IN_KB)) {
hasChanges = true;
((ObjectNode) oldConfiguration).put(MAX_IN_MEMORY_BUFFER_SIZE_IN_KB, 256);
}
break;
default:
break;
}
return new TbPair<>(hasChanges, oldConfiguration);
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\rest\TbRestApiCallNode.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_AD_Table getAD_Table_Source() throws RuntimeException
{
return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name)
.getPO(getAD_Table_Source_ID(), get_TrxName()); }
/** Set Quell-Tabelle.
@param AD_Table_Source_ID Quell-Tabelle */
public void setAD_Table_Source_ID (int AD_Table_Source_ID)
{
if (AD_Table_Source_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_Source_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_Source_ID, Integer.valueOf(AD_Table_Source_ID));
}
/** Get Quell-Tabelle.
@return Quell-Tabelle */
public int getAD_Table_Source_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_Source_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.compiere.model.I_AD_Table getAD_Table_Target() throws RuntimeException
{
return (org.compiere.model.I_AD_Table)MTable.get(getCtx(), org.compiere.model.I_AD_Table.Table_Name)
.getPO(getAD_Table_Target_ID(), get_TrxName()); }
/** Set Ziel-Tabelle.
@param AD_Table_Target_ID Ziel-Tabelle */
public void setAD_Table_Target_ID (int AD_Table_Target_ID)
{
if (AD_Table_Target_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_Target_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_Target_ID, Integer.valueOf(AD_Table_Target_ID));
}
/** Get Ziel-Tabelle.
@return Ziel-Tabelle */
public int getAD_Table_Target_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_Target_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Quell-Datensatz-ID.
@param Record_Source_ID Quell-Datensatz-ID */
public void setRecord_Source_ID (int Record_Source_ID)
{
if (Record_Source_ID < 1)
set_ValueNoCheck (COLUMNNAME_Record_Source_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_Source_ID, Integer.valueOf(Record_Source_ID));
|
}
/** Get Quell-Datensatz-ID.
@return Quell-Datensatz-ID */
public int getRecord_Source_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_Source_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Ziel-Datensatz-ID.
@param Record_Target_ID Ziel-Datensatz-ID */
public void setRecord_Target_ID (int Record_Target_ID)
{
if (Record_Target_ID < 1)
set_ValueNoCheck (COLUMNNAME_Record_Target_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_Target_ID, Integer.valueOf(Record_Target_ID));
}
/** Get Ziel-Datensatz-ID.
@return Ziel-Datensatz-ID */
public int getRecord_Target_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_Target_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Relation_Explicit_v1.java
| 1
|
请完成以下Java代码
|
protected Boolean coerceToBoolean(Object value) {
if (value instanceof Boolean) {
return (Boolean) value;
}
else {
throw LOG.unableToConvertValue(value, Boolean.class);
}
}
@Override
protected BigDecimal coerceToBigDecimal(Object value) {
if (value instanceof BigDecimal) {
return (BigDecimal)value;
}
else if (value instanceof BigInteger) {
return new BigDecimal((BigInteger)value);
}
else if (value instanceof Number) {
return new BigDecimal(((Number)value).doubleValue());
}
else {
throw LOG.unableToConvertValue(value, BigDecimal.class);
}
}
@Override
protected BigInteger coerceToBigInteger(Object value) {
if (value instanceof BigInteger) {
return (BigInteger)value;
}
else if (value instanceof BigDecimal) {
return ((BigDecimal)value).toBigInteger();
}
else if (value instanceof Number) {
return BigInteger.valueOf(((Number)value).longValue());
}
else {
throw LOG.unableToConvertValue(value, BigInteger.class);
}
}
@Override
protected Double coerceToDouble(Object value) {
if (value instanceof Double) {
return (Double)value;
}
else if (value instanceof Number) {
return ((Number) value).doubleValue();
}
else {
throw LOG.unableToConvertValue(value, Double.class);
}
}
@Override
|
protected Long coerceToLong(Object value) {
if (value instanceof Long) {
return (Long)value;
}
else if (value instanceof Number && isLong((Number) value)) {
return ((Number) value).longValue();
}
else {
throw LOG.unableToConvertValue(value, Long.class);
}
}
@Override
protected String coerceToString(Object value) {
if (value instanceof String) {
return (String)value;
}
else if (value instanceof Enum<?>) {
return ((Enum<?>)value).name();
}
else {
throw LOG.unableToConvertValue(value, String.class);
}
}
@Override
public <T> T convert(Object value, Class<T> type) throws ELException {
try {
return super.convert(value, type);
}
catch (ELException e) {
throw LOG.unableToConvertValue(value, type, e);
}
}
protected boolean isLong(Number value) {
double doubleValue = value.doubleValue();
return doubleValue == (long) doubleValue;
}
}
|
repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\el\FeelTypeConverter.java
| 1
|
请完成以下Java代码
|
private String computeESRHashAndCheckForDuplicates(@NonNull final OrgId orgId, final byte[] fileContent)
{
final String esrHash = esrImportBL.computeMD5Checksum(fileContent);
//
// Check for duplicates
final Boolean preventDuplicates = sysConfigBL.getBooleanValue(ESRConstants.SYSCONFIG_PreventDuplicateImportFiles, true);
if (preventDuplicates)
{
final Iterator<I_ESR_ImportFile> esrImportFiles = esrImportDAO.retrieveActiveESRImportFiles(orgId);
// throw exception if another identical hash was seen in the list of esr imports
while (esrImportFiles.hasNext())
{
final I_ESR_ImportFile esrImportFile = esrImportFiles.next();
if (esrHash.equals(esrImportFile.getHash()))
{
throw new AdempiereException("File not imported - identical with previous file: " + esrImportFile.getFileName());
}
}
}
return esrHash;
}
private Properties getCtx()
{
return ctx;
}
public ESRImportEnqueuer esrImport(final I_ESR_Import esrImport)
{
this.esrImport = esrImport;
return this;
}
@NonNull
private I_ESR_Import getEsrImport()
{
return esrImport;
}
public ESRImportEnqueuer asyncBatchName(final String asyncBatchName)
{
this.asyncBatchName = asyncBatchName;
return this;
}
private String getAsyncBatchName()
{
return asyncBatchName;
}
public ESRImportEnqueuer asyncBatchDesc(final String asyncBatchDesc)
{
this.asyncBatchDesc = asyncBatchDesc;
return this;
}
private String getAsyncBatchDesc()
{
return asyncBatchDesc;
}
public ESRImportEnqueuer pinstanceId(@Nullable final PInstanceId pinstanceId)
{
this.pinstanceId = pinstanceId;
return this;
}
private PInstanceId getPinstanceId()
{
return pinstanceId;
|
}
public ESRImportEnqueuer fromDataSource(final ESRImportEnqueuerDataSource fromDataSource)
{
this.fromDataSource = fromDataSource;
return this;
}
@NonNull
private ESRImportEnqueuerDataSource getFromDataSource()
{
return fromDataSource;
}
public ESRImportEnqueuer loggable(@NonNull final ILoggable loggable)
{
this.loggable = loggable;
return this;
}
private void addLog(final String msg, final Object... msgParameters)
{
loggable.addLog(msg, msgParameters);
}
private static class ZipFileResource extends AbstractResource
{
private final byte[] data;
private final String filename;
@Builder
private ZipFileResource(
@NonNull final byte[] data,
@NonNull final String filename)
{
this.data = data;
this.filename = filename;
}
@Override
public String getFilename()
{
return filename;
}
@Override
public String getDescription()
{
return null;
}
@Override
public InputStream getInputStream()
{
return new ByteArrayInputStream(data);
}
public byte[] getData()
{
return data;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\dataimporter\ESRImportEnqueuer.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 9000
servlet:
session:
cookie:
name: sentinel_dashboard_cookie
encoding:
charset: UTF-8
enabled: true
force: true
spring:
mvc:
#Spring Boot 2.6+\u540E\u6620\u5C04\u5339\u914D\u7684\u9ED8\u8BA4\u7B56\u7565\u5DF2\u4ECEAntPathMatcher\u66F4\u6539\u4E3APathPatternParser,\u9700\u8981\u624B\u52A8\u6307\u5B9A\u4E3Aant-path-matcher
pathmatch:
matching-strategy: ant_path_matcher
#auth settings
auth:
filter:
exclude-url-suffixes: htm,html,js,css,map,ico,ttf,woff,png
exclude-urls: /,/auth/login,/auth/logout,/registry/machine,/version
logging:
level:
org:
springframework:
web: INFO
p
|
attern:
file: '%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n'
file:
name: ${user.home}/logs/csp/sentinel-dashboard.log
nacos:
server:
ip: @config.server-addr@
sentinel:
dashboard:
version: 1.8.2
auth:
username: sentinel
password: sentinel
|
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public class TicketId {
private String venue;
private String date;
public TicketId() {
}
public String getVenue() {
return venue;
}
public void setVenue(String venue) {
this.venue = venue;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((date == null) ? 0 : date.hashCode());
result = prime * result + ((venue == null) ? 0 : venue.hashCode());
|
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
TicketId other = (TicketId) obj;
if (date == null) {
if (other.date != null)
return false;
} else if (!date.equals(other.date))
return false;
if (venue == null) {
if (other.venue != null)
return false;
} else if (!venue.equals(other.venue))
return false;
return true;
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\composite\key\data\TicketId.java
| 1
|
请完成以下Java代码
|
public boolean updateStatusByIdAndRecipientId(TenantId tenantId, UserId recipientId, NotificationId notificationId, NotificationStatus status) {
return notificationRepository.updateStatusByIdAndRecipientId(notificationId.getId(), recipientId.getId(), status) != 0;
}
/**
* For this hot method, the partial index `idx_notification_recipient_id_unread` was introduced since 3.6.0
* */
@Override
public int countUnreadByDeliveryMethodAndRecipientId(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId) {
return notificationRepository.countByDeliveryMethodAndRecipientIdAndStatusNot(deliveryMethod, recipientId.getId(), NotificationStatus.READ);
}
@Override
public boolean deleteByIdAndRecipientId(TenantId tenantId, UserId recipientId, NotificationId notificationId) {
return notificationRepository.deleteByIdAndRecipientId(notificationId.getId(), recipientId.getId()) != 0;
}
@Override
public int updateStatusByDeliveryMethodAndRecipientId(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId, NotificationStatus status) {
return notificationRepository.updateStatusByDeliveryMethodAndRecipientIdAndStatusNot(deliveryMethod, recipientId.getId(), status);
}
@Override
public void deleteByRequestId(TenantId tenantId, NotificationRequestId requestId) {
notificationRepository.deleteByRequestId(requestId.getId());
}
@Override
public void deleteByRecipientId(TenantId tenantId, UserId recipientId) {
|
notificationRepository.deleteByRecipientId(recipientId.getId());
}
@Override
public void createPartition(NotificationEntity entity) {
partitioningRepository.createPartitionIfNotExists(ModelConstants.NOTIFICATION_TABLE_NAME,
entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours));
}
@Override
protected Class<NotificationEntity> getEntityClass() {
return NotificationEntity.class;
}
@Override
protected JpaRepository<NotificationEntity, UUID> getRepository() {
return notificationRepository;
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationDao.java
| 1
|
请完成以下Java代码
|
public static JSch setUpJsch() throws JSchException {
JSch jsch = new JSch();
jsch.addIdentity(PRIVATE_KEY);
return jsch;
}
public static Session createSession(JSch jsch) throws JSchException {
Session session = jsch.getSession(USER, HOST, PORT);
session.setConfig("StrictHostKeyChecking", "no");
session.connect();
return session;
}
public static int tunnelNetwork(Session session) throws JSchException {
int portForwarding = session.setPortForwardingL(0, DATABASE_HOST, DATABASE_PORT);
return portForwarding;
}
public static Connection databaseConnection(int port) throws SQLException {
String databaseUrl = "jdbc:mysql://" + DATABASE_HOST + ":" + port + "/baeldung";
Connection connection = DriverManager.getConnection(databaseUrl, DATABASE_USERNAME, DATABASE_PASSWORD);
return connection;
}
public static void createTable(Connection connection, String tableName) throws SQLException {
String createTableSQL = "CREATE TABLE " + tableName + " (id INT, data VARCHAR(255))";
try (Statement statement = connection.createStatement()) {
statement.execute(createTableSQL);
}
}
public static void insertData(Connection connection, String tableName) throws SQLException {
String insertDataSQL = "INSERT INTO " + tableName + " (id, data) VALUES (1, 'test data')";
try (Statement statement = connection.createStatement()) {
|
statement.execute(insertDataSQL);
}
}
public static boolean isTableExists(Connection connection, String tableName) throws SQLException {
try (Statement statement = connection.createStatement()) {
ResultSet resultSet = statement.executeQuery("SHOW TABLES LIKE '" + tableName + "'");
return resultSet.next();
}
}
public static void disconnect(Session session, Connection connection) throws SQLException {
session.disconnect();
connection.close();
}
}
|
repos\tutorials-master\persistence-modules\jdbc-mysql\src\main\java\com\baeldung\connectingtoremotemysqlssh\RemoteMysqlConnection.java
| 1
|
请完成以下Java代码
|
private static ADMessageAndParams extractOrderCompletedADMessageAndParams(final I_C_Order order)
{
final I_C_BPartner bpartner = Services.get(IOrderBL.class).getBPartner(order);
return ADMessageAndParams.builder()
.adMessage(order.isSOTrx() ? MSG_SalesOrderCompleted : MSG_PurchaseOrderCompleted)
.param(TableRecordReference.of(order))
.param(bpartner.getValue())
.param(bpartner.getName())
.build();
}
private static Set<UserId> extractRecipientUserIdsFromOrder(final I_C_Order order)
{
final Integer createdBy = InterfaceWrapperHelper.getValueOrNull(order, "CreatedBy");
final UserId recipientUserId = createdBy == null ? null : UserId.ofRepoIdOrNull(createdBy);
return recipientUserId != null ? ImmutableSet.of(recipientUserId) : ImmutableSet.of();
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
Services.get(INotificationBL.class).sendAfterCommit(notifications);
|
}
@Value
@Builder
public static class NotificationRequest
{
@NonNull
I_C_Order order;
@Nullable
Set<UserId> recipientUserIds;
@Nullable
ADMessageAndParams adMessageAndParams;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\event\OrderUserNotifications.java
| 1
|
请完成以下Java代码
|
public void setGO_RequestSenderId (java.lang.String GO_RequestSenderId)
{
set_Value (COLUMNNAME_GO_RequestSenderId, GO_RequestSenderId);
}
/** Get Request Sender ID.
@return Request Sender ID */
@Override
public java.lang.String getGO_RequestSenderId ()
{
return (java.lang.String)get_Value(COLUMNNAME_GO_RequestSenderId);
}
/** Set Request Username.
@param GO_RequestUsername Request Username */
@Override
public void setGO_RequestUsername (java.lang.String GO_RequestUsername)
{
set_Value (COLUMNNAME_GO_RequestUsername, GO_RequestUsername);
}
/** Get Request Username.
@return Request Username */
@Override
public java.lang.String getGO_RequestUsername ()
{
return (java.lang.String)get_Value(COLUMNNAME_GO_RequestUsername);
}
/** Set GO Shipper Configuration.
@param GO_Shipper_Config_ID GO Shipper Configuration */
@Override
public void setGO_Shipper_Config_ID (int GO_Shipper_Config_ID)
{
if (GO_Shipper_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_GO_Shipper_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GO_Shipper_Config_ID, Integer.valueOf(GO_Shipper_Config_ID));
}
/** Get GO Shipper Configuration.
@return GO Shipper Configuration */
@Override
public int getGO_Shipper_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GO_Shipper_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set GO URL.
@param GO_URL GO URL */
@Override
public void setGO_URL (java.lang.String GO_URL)
{
set_Value (COLUMNNAME_GO_URL, GO_URL);
|
}
/** Get GO URL.
@return GO URL */
@Override
public java.lang.String getGO_URL ()
{
return (java.lang.String)get_Value(COLUMNNAME_GO_URL);
}
@Override
public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
@Override
public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
}
/** Set Lieferweg.
@param M_Shipper_ID
Methode oder Art der Warenlieferung
*/
@Override
public void setM_Shipper_ID (int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID));
}
/** Get Lieferweg.
@return Methode oder Art der Warenlieferung
*/
@Override
public int getM_Shipper_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-gen\de\metas\shipper\gateway\go\model\X_GO_Shipper_Config.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getCurrencyCode() {
return currencyCode;
}
/**
* Sets the value of the currencyCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCurrencyCode(String value) {
this.currencyCode = value;
}
/**
* Gets the value of the exchangeRate property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getExchangeRate() {
return exchangeRate;
}
/**
* Sets the value of the exchangeRate property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setExchangeRate(BigDecimal value) {
this.exchangeRate = value;
}
|
/**
* Gets the value of the exchangeDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getExchangeDate() {
return exchangeDate;
}
/**
* Sets the value of the exchangeDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setExchangeDate(XMLGregorianCalendar value) {
this.exchangeDate = 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\TargetCurrencyType.java
| 2
|
请完成以下Java代码
|
protected String resolve(String value) {
if (embeddedValueResolver != null) {
return embeddedValueResolver.resolveStringValue(value);
} else {
return value;
}
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
if (beanFactory instanceof ConfigurableBeanFactory) {
this.embeddedValueResolver = new EmbeddedValueResolver((ConfigurableBeanFactory) beanFactory);
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
@Override
public void onApplicationEvent(ContextRefreshedEvent event) {
if (event.getApplicationContext() == this.applicationContext) {
this.contextRefreshed = true;
}
}
public JmsOperations getJmsOperations() {
return jmsOperations;
|
}
public void setJmsOperations(JmsOperations jmsOperations) {
this.jmsOperations = jmsOperations;
}
public JmsListenerEndpointRegistry getEndpointRegistry() {
return endpointRegistry;
}
public void setEndpointRegistry(JmsListenerEndpointRegistry endpointRegistry) {
this.endpointRegistry = endpointRegistry;
}
public String getContainerFactoryBeanName() {
return containerFactoryBeanName;
}
public void setContainerFactoryBeanName(String containerFactoryBeanName) {
this.containerFactoryBeanName = containerFactoryBeanName;
}
public JmsListenerContainerFactory<?> getContainerFactory() {
return containerFactory;
}
public void setContainerFactory(JmsListenerContainerFactory<?> containerFactory) {
this.containerFactory = containerFactory;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry-spring\src\main\java\org\flowable\eventregistry\spring\jms\JmsChannelModelProcessor.java
| 1
|
请完成以下Java代码
|
void setEnable(Set<String> enable) {
if (enable != null) {
this.routeFilterConfigProvided = true;
this.routeEnabledHeaders = enable.stream()
.map(String::toLowerCase)
.collect(Collectors.toUnmodifiableSet());
}
}
/**
* @return the route specific/opt-in header names to enable, in lower case.
*/
Set<String> getRouteEnabledHeaders() {
return routeEnabledHeaders;
}
/**
* bind the route specific/opt-out header names to disable, in lower case.
*/
void setDisable(Set<String> disable) {
if (disable != null) {
this.routeFilterConfigProvided = true;
this.routeDisabledHeaders = disable.stream()
.map(String::toLowerCase)
.collect(Collectors.toUnmodifiableSet());
}
}
/**
* @return the route specific/opt-out header names to disable, in lower case
*/
Set<String> getRouteDisabledHeaders() {
|
return routeDisabledHeaders;
}
/**
* @return the route specific/opt-out permission policies.
*/
protected @Nullable String getRoutePermissionsPolicyHeaderValue() {
return routePermissionsPolicyHeaderValue;
}
/**
* bind the route specific/opt-out permissions policy.
*/
void setPermissionsPolicy(@Nullable String permissionsPolicy) {
this.routeFilterConfigProvided = true;
this.routePermissionsPolicyHeaderValue = permissionsPolicy;
}
/**
* @return flag whether route specific arguments were bound.
*/
boolean isRouteFilterConfigProvided() {
return routeFilterConfigProvided;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SecureHeadersGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public void setIcon(Icon defaultIcon)
{
((MetalComboBoxButton)arrowButton).setComboIcon(defaultIcon);
} // setIcon
/**
* Create Popup
*
* @return {@link AdempiereComboPopup}
*/
@Override
protected ComboPopup createPopup()
{
final AdempiereComboPopup popup = new AdempiereComboPopup(comboBox);
popup.getAccessibleContext().setAccessibleParent(comboBox);
return popup;
}
public ComboPopup getComboPopup()
{
return popup;
}
public static final ComboPopup getComboPopup(final JComboBox<?> comboBox)
{
final ComboBoxUI comboBoxUI = comboBox.getUI();
if (comboBoxUI instanceof AdempiereComboBoxUI)
{
return ((AdempiereComboBoxUI)comboBoxUI).getComboPopup();
}
//
// Fallback:
// Back door our way to finding the inner JList.
//
// it is unknown whether this functionality will work outside of Sun's
// implementation, but the code is safe and will "fail gracefully" on
// other systems
//
// see javax.swing.plaf.basic.BasicComboBoxUI.getAccessibleChild(JComponent, int)
final Accessible a = comboBoxUI.getAccessibleChild(comboBox, 0);
if (a instanceof ComboPopup)
{
return (ComboPopup)a;
}
else
{
return null;
}
}
public static class AdempiereComboPopup extends BasicComboPopup
{
private static final long serialVersionUID = 3226003169560939486L;
public AdempiereComboPopup(final JComboBox<Object> combo)
|
{
super(combo);
}
@Override
protected int getPopupHeightForRowCount(final int maxRowCount)
{
// ensure the combo box sized for the amount of data to be displayed
final int itemCount = comboBox.getItemCount();
int rows = itemCount < maxRowCount ? itemCount : maxRowCount;
if (rows <= 0)
rows = 1;
return super.getPopupHeightForRowCount(1) * rows;
}
@Override
protected void configureScroller()
{
super.configureScroller();
// In case user scrolls inside a combobox popup, we want to prevent closing the popup no matter if it could be scrolled or not.
scroller.putClientProperty(AdempiereScrollPaneUI.PROPERTY_DisableWheelEventForwardToParent, true);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereComboBoxUI.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getParentTaskId() {
return parentTaskId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public String getFormKey() {
return formKey;
}
|
@Override
public Set<? extends IdentityLinkInfo> getIdentityLinks() {
return identityLinks;
}
@Override
public String getScopeId() {
return this.scopeId;
}
@Override
public String getScopeType() {
return this.scopeType;
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\BaseTaskBuilderImpl.java
| 2
|
请完成以下Java代码
|
public void setPageContext(PageContext pageContext) {
super.setPageContext(pageContext);
ServletContext servletContext = pageContext.getServletContext();
ApplicationContext context = SecurityWebApplicationContextUtils
.findRequiredWebApplicationContext(servletContext);
String[] names = context.getBeanNamesForType(SecurityContextHolderStrategy.class);
if (names.length == 1) {
SecurityContextHolderStrategy strategy = context.getBean(SecurityContextHolderStrategy.class);
this.securityContextHolderStrategy = strategy;
}
}
@Override
public int doStartTag() throws JspException {
return super.doStartTag();
}
@Override
public int doEndTag() throws JspException {
Object result = null;
// determine the value by...
if (this.property != null) {
SecurityContext context = this.securityContextHolderStrategy.getContext();
if ((context == null) || !(context instanceof SecurityContext) || (context.getAuthentication() == null)) {
return Tag.EVAL_PAGE;
}
Authentication auth = context.getAuthentication();
if (auth.getPrincipal() == null) {
return Tag.EVAL_PAGE;
}
try {
BeanWrapperImpl wrapper = new BeanWrapperImpl(auth);
result = wrapper.getPropertyValue(this.property);
}
catch (BeansException ex) {
throw new JspException(ex);
}
}
if (this.var != null) {
/*
* Store the result, letting an IllegalArgumentException propagate back if the
* scope is invalid (e.g., if an attempt is made to store something in the
* session without any HttpSession existing).
*/
if (result != null) {
this.pageContext.setAttribute(this.var, result, this.scope);
}
else {
if (this.scopeSpecified) {
this.pageContext.removeAttribute(this.var, this.scope);
}
else {
this.pageContext.removeAttribute(this.var);
}
}
}
else {
if (this.htmlEscape) {
writeMessage(TextEscapeUtils.escapeEntities(String.valueOf(result)));
}
else {
|
writeMessage(String.valueOf(result));
}
}
return EVAL_PAGE;
}
protected void writeMessage(String msg) throws JspException {
try {
this.pageContext.getOut().write(String.valueOf(msg));
}
catch (IOException ioe) {
throw new JspException(ioe);
}
}
/**
* Set HTML escaping for this tag, as boolean value.
*/
public void setHtmlEscape(String htmlEscape) {
this.htmlEscape = Boolean.parseBoolean(htmlEscape);
}
/**
* Return the HTML escaping setting for this tag, or the default setting if not
* overridden.
*/
protected boolean isHtmlEscape() {
return this.htmlEscape;
}
}
|
repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\AuthenticationTag.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ProdIdCountMapTransferComponent extends BaseDataTransferComponent {
@Autowired
private OrderDAO orderDAO;
@Override
protected void transfer(OrderProcessContext orderProcessContext) {
// 获取订单ID 和 购买者ID
String orderId = orderProcessContext.getOrderProcessReq().getOrderId();
String buyerId = orderProcessContext.getOrderProcessReq().getUserId();
// 构造查询请求
OrderQueryReq orderQueryReq = buildOrderQueryReq(orderId, buyerId);
// 查询该笔订单
OrdersEntity ordersEntity = query(orderQueryReq);
// 构建prodIdCountMap
Map<String, Integer> prodIdCountMap = buildProdIdCountMap(ordersEntity);
// 装入context
setIntoContext(prodIdCountMap, ordersEntity.getPayModeEnum(), orderProcessContext);
}
/**
* 订单查询
* @param orderQueryReq 订单查询请求
* @return 订单结果
*/
private OrdersEntity query(OrderQueryReq orderQueryReq) {
List<OrdersEntity> ordersEntityList = orderDAO.findOrders(orderQueryReq);
if (CollectionUtils.isEmpty(ordersEntityList)) {
throw new CommonBizException(ExpCodeEnum.ORDER_NULL);
}
return ordersEntityList.get(0);
}
/**
* 构造订单查询请求
* @param orderId 订单ID
* @param buyerId 购买者ID
* @return 订单查询请求
*/
private OrderQueryReq buildOrderQueryReq(String orderId, String buyerId) {
OrderQueryReq orderQueryReq = new OrderQueryReq();
orderQueryReq.setId(orderId);
orderQueryReq.setBuyerId(buyerId);
return orderQueryReq;
}
/**
* 构建prodIdCountMap
* @param ordersEntity 订单详情
* @return prodIdCountMap
*/
private Map<String, Integer> buildProdIdCountMap(OrdersEntity ordersEntity) {
// 初始化结果集
Map<String, Integer> prodIdCountMap = Maps.newHashMap();
|
// 获取产品列表
List<ProductOrderEntity> productOrderList = ordersEntity.getProductOrderList();
// 构造结果集
for (ProductOrderEntity productOrderEntity : productOrderList) {
// 产品ID
String prodId = productOrderEntity.getProductEntity().getId();
// 购买数量
Integer count = productOrderEntity.getCount();
prodIdCountMap.put(prodId, count);
}
return prodIdCountMap;
}
/**
* 将prodIdCountMap装入Context
* @param prodIdCountMap
* @param payModeEnum
* @param orderProcessContext
*/
private void setIntoContext(Map<String, Integer> prodIdCountMap, PayModeEnum payModeEnum, OrderProcessContext orderProcessContext) {
// 构造 订单插入请求
OrderInsertReq orderInsertReq = new OrderInsertReq();
// 插入prodIdCountMap
orderInsertReq.setProdIdCountMap(prodIdCountMap);
// 插入支付方式
orderInsertReq.setPayModeCode(payModeEnum.getCode());
orderProcessContext.getOrderProcessReq().setReqData(orderInsertReq);
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\component\datatransfer\ProdIdCountMapTransferComponent.java
| 2
|
请完成以下Java代码
|
public @Nullable RateLimiter getRateLimiter() {
return rateLimiter;
}
public Config setRateLimiter(RateLimiter rateLimiter) {
this.rateLimiter = rateLimiter;
return this;
}
public HttpStatus getStatusCode() {
return statusCode;
}
public Config setStatusCode(HttpStatus statusCode) {
this.statusCode = statusCode;
return this;
}
public @Nullable Boolean getDenyEmptyKey() {
return denyEmptyKey;
}
public Config setDenyEmptyKey(Boolean denyEmptyKey) {
this.denyEmptyKey = denyEmptyKey;
return this;
}
public @Nullable String getEmptyKeyStatus() {
return emptyKeyStatus;
}
|
public Config setEmptyKeyStatus(String emptyKeyStatus) {
this.emptyKeyStatus = emptyKeyStatus;
return this;
}
@Override
public void setRouteId(String routeId) {
this.routeId = routeId;
}
@Override
public @Nullable String getRouteId() {
return this.routeId;
}
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RequestRateLimiterGatewayFilterFactory.java
| 1
|
请完成以下Java代码
|
public class MProductCategoryTreeSupport extends DefaultPOTreeSupport
{
@Override
public int getAD_Tree_ID(PO po)
{
return UNKNOWN_TreeID;
}
@Override
public int getParent_ID(PO po)
{
if (I_M_Product_Category.Table_Name.equals(po.get_TableName()))
{
I_M_Product_Category pc = InterfaceWrapperHelper.create(po, I_M_Product_Category.class);
return pc.getM_Product_Category_Parent_ID();
}
return UNKNOWN_ParentID;
}
@Override
public String getWhereClause(MTree_Base tree)
{
return null;
}
@Override
public void setParent_ID(MTree_Base tree, int nodeId, int parentId, String trxName)
{
final MTable table = MTable.get(tree.getCtx(), tree.getAD_Table_ID());
if (I_M_Product_Category.Table_Name.equals(table.getTableName()))
{
final I_M_Product_Category pc = InterfaceWrapperHelper.create(table.getPO(nodeId, trxName), I_M_Product_Category.class);
pc.setM_Product_Category_Parent_ID(parentId);
InterfaceWrapperHelper.save(pc);
}
}
@Override
public boolean isParentChanged(PO po)
{
return po.is_ValueChanged(I_M_Product_Category.COLUMNNAME_M_Product_Category_Parent_ID);
}
|
@Override
public int getOldParent_ID(PO po)
{
return po.get_ValueOldAsInt(I_M_Product_Category.COLUMNNAME_M_Product_Category_Parent_ID);
}
@Override
public String getParentIdSQL()
{
return I_M_Product_Category.COLUMNNAME_M_Product_Category_Parent_ID;
}
@Override
public MTreeNode getNodeInfo(GridTab gridTab)
{
MTreeNode info = super.getNodeInfo(gridTab);
info.setAllowsChildren(true); // we always allow children because IsSummary field will be automatically
// maintained
return info;
}
@Override
public MTreeNode loadNodeInfo(MTree tree, ResultSet rs) throws SQLException
{
MTreeNode info = super.loadNodeInfo(tree, rs);
info.setAllowsChildren(true); // we always allow children because IsSummary field will be automatically
info.setImageIndicator(I_M_Product_Category.Table_Name);
return info;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\tree\spi\impl\MProductCategoryTreeSupport.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void deleteNotificationTargetById(@PathVariable UUID id) throws Exception {
NotificationTargetId notificationTargetId = new NotificationTargetId(id);
NotificationTarget notificationTarget = checkNotificationTargetId(notificationTargetId, Operation.DELETE);
doDeleteAndLog(EntityType.NOTIFICATION_TARGET, notificationTarget, notificationTargetService::deleteNotificationTargetById);
}
private void checkTargetUsers(SecurityUser user, NotificationTargetConfig targetConfig) throws ThingsboardException {
if (user.isSystemAdmin()) {
return;
}
// PE: generic permission for users
UsersFilter usersFilter = ((PlatformUsersNotificationTargetConfig) targetConfig).getUsersFilter();
switch (usersFilter.getType()) {
case USER_LIST:
for (UUID recipientId : ((UserListFilter) usersFilter).getUsersIds()) {
checkUserId(new UserId(recipientId), Operation.READ);
}
break;
case CUSTOMER_USERS:
|
CustomerId customerId = new CustomerId(((CustomerUsersFilter) usersFilter).getCustomerId());
checkEntityId(customerId, Operation.READ);
break;
case TENANT_ADMINISTRATORS:
if (CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantsIds()) ||
CollectionUtils.isNotEmpty(((TenantAdministratorsFilter) usersFilter).getTenantProfilesIds())) {
throw new AccessDeniedException("");
}
break;
case SYSTEM_ADMINISTRATORS:
throw new AccessDeniedException("");
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\NotificationTargetController.java
| 2
|
请完成以下Java代码
|
private static String toJson(final HuId huId, final ProductId storageProductId, final HuId topLevelHUId)
{
// IMPORTANT: top level row shall be perfectly convertible to integers, else, a lot of APIs could fail
final String idStrPart;
if (storageProductId != null)
{
idStrPart = huId.getRepoId() + ID_SEPARATOR + storageProductId.getRepoId();
}
else
{
idStrPart = String.valueOf(huId.getRepoId());
}
final String topLevelHUIdPart = topLevelHUId != null ? PREFIX_TopLevelHUId + topLevelHUId.getRepoId() : null;
return PARTS_JOINER.join(idStrPart, topLevelHUIdPart);
}
public DocumentId toDocumentId()
{
DocumentId documentId = _documentId;
if (documentId == null)
{
documentId = _documentId = DocumentId.of(toJson());
}
return documentId;
}
public boolean isTopLevel()
{
return huId != null && topLevelHUId == null && storageProductId == null;
}
public boolean isHU()
{
return storageProductId == null;
}
public HuId getHuId()
{
return huId;
}
|
public HUEditorRowId toTopLevelRowId()
{
if (isTopLevel())
{
return this;
}
final HuId huId = getTopLevelHUId();
final ProductId storageProductId = null;
final HuId topLevelHUId = null;
final String json = null;
final DocumentId documentId = null;
return new HUEditorRowId(huId, storageProductId, topLevelHUId, json, documentId);
}
public HuId getTopLevelHUId()
{
if (topLevelHUId != null)
{
return topLevelHUId;
}
return huId;
}
public ProductId getStorageProductId()
{
return storageProductId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRowId.java
| 1
|
请完成以下Java代码
|
private Iterator<InvoiceCandidateId> createInvoiceCandidateIdIterator(@NonNull final IQueryFilter<I_C_Invoice_Candidate> selectedICsFilter)
{
final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder = queryBL
.createQueryBuilder(I_C_Invoice_Candidate.class)
.addOnlyActiveRecordsFilter()
.filter(selectedICsFilter);
final Iterator<InvoiceCandidateId> icIds = queryBuilder
.create()
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, true)
.setOption(IQuery.OPTION_IteratorBufferSize, 1000)
.iterateIds(InvoiceCandidateId::ofRepoId);
return icIds;
}
private Result processInvoiceCandidates(@NonNull final Iterator<InvoiceCandidateId> invoiceCandidateIds)
{
int counter = 0;
boolean anyException = false;
while (invoiceCandidateIds.hasNext())
{
final InvoiceCandidateId invoiceCandidateId = invoiceCandidateIds.next();
try (final MDCCloseable ignore = TableRecordMDC.putTableRecordReference(I_C_Invoice_Candidate.Table_Name, invoiceCandidateId))
{
trxManager.runInNewTrx(() -> {
logger.debug("Processing invoiceCandidate");
final I_C_Invoice_Candidate invoiceCandidateRecord = invoiceCandDAO.getById(invoiceCandidateId);
invoiceCandidateFacadeService.syncICToCommissionInstance(invoiceCandidateRecord, false/* candidateDeleted */);
});
counter++;
}
catch (final RuntimeException e)
{
anyException = true;
|
final AdIssueId adIssueId = errorManager.createIssue(e);
Loggables.withLogger(logger, Level.DEBUG)
.addLog("C_Invoice_Candidate_ID={}: Caught {} and created AD_Issue_ID={}; exception-message={}",
invoiceCandidateId.getRepoId(), e.getClass(), adIssueId.getRepoId(), e.getLocalizedMessage());
}
}
return new Result(counter, anyException);
}
@Value
private static class Result
{
int counter;
boolean anyException;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\process\C_Invoice_Candidate_CreateOrUpdateCommissionInstance.java
| 1
|
请完成以下Java代码
|
public static AlarmStatusFilter empty() {
return EMPTY;
}
public boolean hasAnyFilter() {
return clearFilter.isPresent() || ackFilter.isPresent();
}
public boolean hasClearFilter() {
return clearFilter.isPresent();
}
public boolean hasAckFilter() {
return ackFilter.isPresent();
}
public boolean getClearFilter() {
return clearFilter.orElseThrow(() -> new RuntimeException("Clear filter is not set! Use `hasClearFilter` to check."));
}
public boolean getAckFilter() {
return ackFilter.orElseThrow(() -> new RuntimeException("Ack filter is not set! Use `hasAckFilter` to check."));
}
|
public static AlarmStatusFilter from(Collection<AlarmSearchStatus> statuses) {
if (statuses == null || statuses.isEmpty() || statuses.contains(AlarmSearchStatus.ANY)) {
return EMPTY;
}
boolean clearFilter = statuses.contains(AlarmSearchStatus.CLEARED);
boolean activeFilter = statuses.contains(AlarmSearchStatus.ACTIVE);
Optional<Boolean> clear = Optional.empty();
if (clearFilter && !activeFilter || !clearFilter && activeFilter) {
clear = Optional.of(clearFilter);
}
boolean ackFilter = statuses.contains(AlarmSearchStatus.ACK);
boolean unackFilter = statuses.contains(AlarmSearchStatus.UNACK);
Optional<Boolean> ack = Optional.empty();
if (ackFilter && !unackFilter || !ackFilter && unackFilter) {
ack = Optional.of(ackFilter);
}
return new AlarmStatusFilter(clear, ack);
}
public boolean matches(Alarm alarm) {
return ackFilter.map(ackFilter -> ackFilter.equals(alarm.isAcknowledged())).orElse(true) &&
clearFilter.map(clearedFilter -> clearedFilter.equals(alarm.isCleared())).orElse(true);
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\alarm\AlarmStatusFilter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Queue syncOrderRequestEventsQueue()
{
return new Queue(QUEUENAME_SyncOrderRequestEvents);
}
@Bean(name = QUEUENAME_SyncOrderResponseEvents)
public Queue syncOrderResponseEventsQueue()
{
return new Queue(QUEUENAME_SyncOrderResponseEvents);
}
// Note: with spring boot-2 this somehow didn't work anymore. It didn't create the queues in rabbitmq, so i added the code above, which works.
// @Bean
// List<Declarable> queuesAndBindings()
// {
// return ImmutableList.<Declarable> builder()
// .addAll(createQueueExchangeAndBinding(QUEUENAME_MSV3ServerRequests))
|
// .addAll(createQueueExchangeAndBinding(QUEUENAME_UserChangedEvents))
// .addAll(createQueueExchangeAndBinding(QUEUENAME_StockAvailabilityUpdatedEvent))
// .addAll(createQueueExchangeAndBinding(QUEUENAME_ProductExcludeUpdatedEvents))
// .addAll(createQueueExchangeAndBinding(QUEUENAME_SyncOrderRequestEvents))
// .addAll(createQueueExchangeAndBinding(QUEUENAME_SyncOrderResponseEvents))
// .build();
// }
// private static List<Declarable> createQueueExchangeAndBinding(final String queueName)
// {
// final Queue queue = QueueBuilder.nonDurable(queueName).build();
// final TopicExchange exchange = new TopicExchange(queueName + "-exchange");
// final Binding binding = BindingBuilder.bind(queue).to(exchange).with(queueName);
// return ImmutableList.<Declarable> of(queue, exchange, binding);
// }
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server-peer\src\main\java\de\metas\vertical\pharma\msv3\server\peer\RabbitMQConfig.java
| 2
|
请完成以下Java代码
|
public String amt(@NonNull final ICalloutField calloutField)
{
if (isCalloutActive())
{// prevent recursive
return NO_ERROR;
}
if (isDoInvocation(calloutField))
{
return new CalloutOrder().amt(calloutField);
}
return NO_ERROR;
}
/**
* This callout "interposes" {@link CalloutOrder#qty(ICalloutField)}
*
* and decides whether that callout should be executed. If no subscription is selected or this is invoked for
* another field than 'QtyEntered' that callout is executed, otherwise not.
*/
public String qty(final ICalloutField calloutField)
{
if (isCalloutActive())
{// prevent recursive
return NO_ERROR;
}
if (isDoInvocation(calloutField))
{
return new CalloutOrder().qty(calloutField);
}
return NO_ERROR;
}
private boolean isDoInvocation(final ICalloutField calloutField)
{
if (!I_C_OrderLine.COLUMNNAME_QtyEntered.equals(calloutField.getColumnName()))
{
// execute the callout
return true;
}
final I_C_OrderLine ol = calloutField.getModel(I_C_OrderLine.class);
// don't execute the callout
if(subscriptionBL.isSubscription(ol))
{
return false;
}
//execute the callout
return true;
}
// metas
public String subscriptionLocation(final ICalloutField calloutField)
{
final I_C_OrderLine ol = calloutField.getModel(I_C_OrderLine.class);
final I_C_Order order = ol.getC_Order();
final boolean IsSOTrx = order.isSOTrx();
final boolean isSubscription = ol.isSubscription();
if (IsSOTrx && !isSubscription)
{
final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class);
final Quantity qty = orderLineBL.getQtyEntered(ol);
final BigDecimal qtyOrdered = orderLineBL.convertQtyEnteredToStockUOM(ol).toBigDecimal();
ol.setQtyOrdered(qtyOrdered);
orderLineBL.updatePrices(OrderLinePriceUpdateRequest.builder()
|
.orderLine(ol)
.qtyOverride(qty)
.resultUOM(ResultUOM.CONTEXT_UOM)
.updatePriceEnteredAndDiscountOnlyIfNotAlreadySet(true)
.updateLineNetAmt(true)
.build());
}
if (IsSOTrx && isSubscription)
{
final int C_BPartner_ID = order.getC_BPartner_ID();
PreparedStatement pstmt = null;
ResultSet rs = null;
final String sql = "SELECT C_BPartner_Location_ID FROM C_BPartner_Location "
+ " WHERE C_BPartner_ID = ? "
+ " ORDER BY IsSubscriptionToDefault DESC";
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, C_BPartner_ID);
rs = pstmt.executeQuery();
if (rs.next())
{
final int bpartnerLocationId = rs.getInt(1);
order.setC_BPartner_Location_ID(bpartnerLocationId);
log.debug("C_BPartner_Location_ID for Subscription changed -> " + bpartnerLocationId);
}
}
catch (final SQLException e)
{
log.error(sql, e);
return e.getLocalizedMessage();
}
finally
{
DB.close(rs, pstmt);
}
}
return NO_ERROR;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\callout\OrderLine.java
| 1
|
请完成以下Java代码
|
public void setInitial(Boolean isInitial) {
this.isInitial = isInitial;
}
public Boolean isInitial() {
return isInitial;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[variableName=" + variableName
+ ", variableInstanceId=" + variableInstanceId
+ ", revision=" + revision
+ ", serializerName=" + serializerName
+ ", longValue=" + longValue
+ ", doubleValue=" + doubleValue
+ ", textValue=" + textValue
+ ", textValue2=" + textValue2
+ ", byteArrayId=" + byteArrayId
|
+ ", activityInstanceId=" + activityInstanceId
+ ", scopeActivityInstanceId=" + scopeActivityInstanceId
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", id=" + id
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", taskId=" + taskId
+ ", timestamp=" + timestamp
+ ", tenantId=" + tenantId
+ ", isInitial=" + isInitial
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricVariableUpdateEventEntity.java
| 1
|
请完成以下Java代码
|
protected void prepare() {
// Nothing to to
}
String recurringRun(final int adClientId, final String trxName) {
int count = 0;
int thisTime = 0;
while ((thisTime = run(adClientId, trxName)) != 0) {
count += thisTime;
}
return "Performed " + count + " recurring runs";
}
private int run(final int adClientId, final String trxName) {
|
final IRecurringPA recurringPA = Services.get(IRecurringPA.class);
final IRecurringBL recurringBL = Services.get(IRecurringBL.class);
// get recurring docs that need to run today.
final Collection<I_C_Recurring> recurringDocs = recurringPA
.retrieveForToday(adClientId, trxName);
for (final I_C_Recurring recurring : recurringDocs) {
recurringBL.recurringRun(recurring);
}
return recurringDocs.size();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\document\process\RecurringAuto.java
| 1
|
请完成以下Java代码
|
private static TokenResponse parse(Map<String, Object> json) {
try {
return TokenResponse.parse(new JSONObject(json));
}
catch (ParseException ex) {
OAuth2Error oauth2Error = invalidTokenResponse(
"An error occurred parsing the Access Token response: " + ex.getMessage());
throw new OAuth2AuthorizationException(oauth2Error, ex);
}
}
private static OAuth2Error invalidTokenResponse(String message) {
return new OAuth2Error(INVALID_TOKEN_RESPONSE_ERROR_CODE, message, null);
}
private static Mono<AccessTokenResponse> oauth2AccessTokenResponse(TokenResponse tokenResponse) {
if (tokenResponse.indicatesSuccess()) {
return Mono.just(tokenResponse).cast(AccessTokenResponse.class);
}
TokenErrorResponse tokenErrorResponse = (TokenErrorResponse) tokenResponse;
ErrorObject errorObject = tokenErrorResponse.getErrorObject();
OAuth2Error oauth2Error = getOAuth2Error(errorObject);
return Mono.error(new OAuth2AuthorizationException(oauth2Error));
}
private static OAuth2Error getOAuth2Error(ErrorObject errorObject) {
if (errorObject == null) {
return new OAuth2Error(OAuth2ErrorCodes.SERVER_ERROR);
}
String code = (errorObject.getCode() != null) ? errorObject.getCode() : OAuth2ErrorCodes.SERVER_ERROR;
String description = errorObject.getDescription();
String uri = (errorObject.getURI() != null) ? errorObject.getURI().toString() : null;
return new OAuth2Error(code, description, uri);
}
private static OAuth2AccessTokenResponse oauth2AccessTokenResponse(AccessTokenResponse accessTokenResponse) {
AccessToken accessToken = accessTokenResponse.getTokens().getAccessToken();
OAuth2AccessToken.TokenType accessTokenType = null;
if (OAuth2AccessToken.TokenType.BEARER.getValue().equalsIgnoreCase(accessToken.getType().getValue())) {
accessTokenType = OAuth2AccessToken.TokenType.BEARER;
}
|
long expiresIn = accessToken.getLifetime();
Set<String> scopes = (accessToken.getScope() != null)
? new LinkedHashSet<>(accessToken.getScope().toStringList()) : Collections.emptySet();
String refreshToken = null;
if (accessTokenResponse.getTokens().getRefreshToken() != null) {
refreshToken = accessTokenResponse.getTokens().getRefreshToken().getValue();
}
Map<String, Object> additionalParameters = new LinkedHashMap<>(accessTokenResponse.getCustomParameters());
// @formatter:off
return OAuth2AccessTokenResponse.withToken(accessToken.getValue())
.tokenType(accessTokenType)
.expiresIn(expiresIn)
.scopes(scopes)
.refreshToken(refreshToken)
.additionalParameters(additionalParameters)
.build();
// @formatter:on
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\web\reactive\function\OAuth2AccessTokenResponseBodyExtractor.java
| 1
|
请完成以下Java代码
|
public int getM_InOutLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getM_InOutLine_ID()));
}
public I_M_InventoryLine getM_InventoryLine() throws RuntimeException
{
return (I_M_InventoryLine)MTable.get(getCtx(), I_M_InventoryLine.Table_Name)
.getPO(getM_InventoryLine_ID(), get_TrxName()); }
/** Set Phys.Inventory Line.
@param M_InventoryLine_ID
Unique line in an Inventory document
*/
public void setM_InventoryLine_ID (int M_InventoryLine_ID)
{
if (M_InventoryLine_ID < 1)
set_Value (COLUMNNAME_M_InventoryLine_ID, null);
else
set_Value (COLUMNNAME_M_InventoryLine_ID, Integer.valueOf(M_InventoryLine_ID));
}
/** Get Phys.Inventory Line.
@return Unique line in an Inventory document
*/
public int getM_InventoryLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLine_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;
}
|
/** Set Scrapped Quantity.
@param ScrappedQty
The Quantity scrapped due to QA issues
*/
public void setScrappedQty (BigDecimal ScrappedQty)
{
set_Value (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Scrapped Quantity.
@return The Quantity scrapped due to QA issues
*/
public BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Target Quantity.
@param TargetQty
Target Movement Quantity
*/
public void setTargetQty (BigDecimal TargetQty)
{
set_ValueNoCheck (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Target Quantity.
@return Target Movement Quantity
*/
public BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutLineConfirm.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public I_C_InvoiceLine createInvoiceLine(final org.compiere.model.I_C_Invoice invoice)
{
final MInvoice invoicePO = LegacyAdapters.convertToPO(invoice);
final MInvoiceLine invoiceLinePO = new MInvoiceLine(invoicePO);
return InterfaceWrapperHelper.create(invoiceLinePO, I_C_InvoiceLine.class);
}
@Override
public I_C_InvoiceLine createInvoiceLine(final String trxName)
{
return InterfaceWrapperHelper.create(Env.getCtx(), I_C_InvoiceLine.class, trxName);
}
@Override
public List<I_C_LandedCost> retrieveLandedCosts(
final I_C_InvoiceLine invoiceLine, final String whereClause,
final String trxName)
{
final List<I_C_LandedCost> list = new ArrayList<>();
String sql = "SELECT * FROM C_LandedCost WHERE C_InvoiceLine_ID=? ";
if (whereClause != null)
{
sql += whereClause;
}
final PreparedStatement pstmt = DB.prepareStatement(sql, trxName);
ResultSet rs = null;
try
{
pstmt.setInt(1, invoiceLine.getC_InvoiceLine_ID());
rs = pstmt.executeQuery();
while (rs.next())
{
MLandedCost lc = new MLandedCost(Env.getCtx(), rs, trxName);
list.add(lc);
}
}
catch (Exception e)
{
logger.error("getLandedCost", e);
}
finally
{
DB.close(rs, pstmt);
}
|
return list;
} // getLandedCost
@Override
public I_C_LandedCost createLandedCost(String trxName)
{
return new MLandedCost(Env.getCtx(), 0, trxName);
}
@Override
public List<I_C_InvoiceTax> retrieveTaxes(org.compiere.model.I_C_Invoice invoice)
{
final MInvoice invoicePO = LegacyAdapters.convertToPO(invoice);
final MInvoiceTax[] resultArray = invoicePO.getTaxes(true);
final List<I_C_InvoiceTax> result = new ArrayList<>();
for (final MInvoiceTax tax : resultArray)
{
result.add(tax);
}
// NOTE: make sure we are returning a read-write list because some API rely on this (doing sorting)
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\service\impl\InvoiceDAO.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.