instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public PlanItemInstanceResponse performPlanItemInstanceAction(@ApiParam(name = "planItemInstanceId") @PathVariable String planItemInstanceId,
@RequestBody RestActionRequest actionRequest, HttpServletResponse response) {
PlanItemInstance planItemInstance = getPlanItemInstanceFromRequest(planItemInstanceId);
if (restApiInterceptor != null) {
restApiInterceptor.doPlanItemInstanceAction(planItemInstance, actionRequest);
}
if (RestActionRequest.TRIGGER.equals(actionRequest.getAction())) {
runtimeService.triggerPlanItemInstance(planItemInstance.getId());
} else if (RestActionRequest.ENABLE.equals(actionRequest.getAction())) {
runtimeService.startPlanItemInstance(planItemInstanceId);
} else if (RestActionRequest.DISABLE.equals(actionRequest.getAction())) {
runtimeService.disablePlanItemInstance(planItemInstanceId);
|
} else if (RestActionRequest.START.equals(actionRequest.getAction())) {
runtimeService.startPlanItemInstance(planItemInstanceId);
} else {
throw new FlowableIllegalArgumentException("Invalid action: '" + actionRequest.getAction() + "'.");
}
// Re-fetch the execution, could have changed due to action or even completed
planItemInstance = runtimeService.createPlanItemInstanceQuery().planItemInstanceId(planItemInstance.getId()).singleResult();
if (planItemInstance == null) {
// Execution is finished, return empty body to inform user
response.setStatus(HttpStatus.NO_CONTENT.value());
return null;
} else {
return restResponseFactory.createPlanItemInstanceResponse(planItemInstance);
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\planitem\PlanItemInstanceResource.java
| 2
|
请完成以下Java代码
|
public void setM_HU_PI_Item_ID (final int M_HU_PI_Item_ID)
{
if (M_HU_PI_Item_ID < 1)
set_Value (COLUMNNAME_M_HU_PI_Item_ID, null);
else
set_Value (COLUMNNAME_M_HU_PI_Item_ID, M_HU_PI_Item_ID);
}
@Override
public int getM_HU_PI_Item_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_ID);
}
@Override
public void setM_HU_PI_Item_Product_ID (final int M_HU_PI_Item_Product_ID)
{
if (M_HU_PI_Item_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_HU_PI_Item_Product_ID, M_HU_PI_Item_Product_ID);
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_HU_PI_Item_Product_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (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 @Nullable java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setQty (final BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
|
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUPC (final @Nullable java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
@Override
public java.lang.String getUPC()
{
return get_ValueAsString(COLUMNNAME_UPC);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI_Item_Product.java
| 1
|
请完成以下Spring Boot application配置
|
datasource.security.driver-class-name=com.mysql.jdbc.Driver
datasource.security.url=jdbc:mysql://localhost:3306/test
datasource.security.username=root
datasource.security.password=root
datasource.security.initialize=true
datasource.orders.driver-class-name=com.mysql.jdbc.Driver
datasource.orders.url=jdbc:mysql://localhost:3306/orders
datasource.
|
orders.username=root
datasource.orders.password=root
datasource.orders.initialize=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true
|
repos\Spring-Boot-Advanced-Projects-main\springboot-multiple-datasources\src\main\resources\application-prod.properties
| 2
|
请完成以下Java代码
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(@NonNull final IProcessPreconditionsContext context)
{
return checkBankStatementIsDraftOrInProcessOrCompleted(context)
.and(() -> checkSingleLineSelectedWhichIsNotReconciled(context));
}
@Override
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
if (PARAM_C_BPartner_ID.contentEquals(parameter.getColumnName()))
{
final I_C_BankStatementLine bankStatementLine = getSingleSelectedBankStatementLine();
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(bankStatementLine.getC_BPartner_ID());
if (bpartnerId != null)
{
return bpartnerId;
}
}
return DEFAULT_VALUE_NOTAVAILABLE;
}
@ProcessParamLookupValuesProvider(parameterName = PARAM_C_Payment_ID, numericKey = true, lookupSource = DocumentLayoutElementFieldDescriptor.LookupSource.lookup, lookupTableName = I_C_Payment.Table_Name)
private LookupValuesList paymentLookupProvider()
{
if (bpartnerId == null)
{
return LookupValuesList.EMPTY;
}
final I_C_BankStatementLine bankStatementLine = getSingleSelectedBankStatementLine();
final int limit = 20;
final Set<PaymentId> paymentIds = bankStatementPaymentBL.findEligiblePaymentIds(
bankStatementLine,
bpartnerId,
ImmutableSet.of(), // excludePaymentIds
limit);
return lookupDataSourceFactory.searchInTableLookup(I_C_Payment.Table_Name).findByIdsOrdered(paymentIds);
}
@Override
protected String doIt()
{
final I_C_BankStatement bankStatement = getSelectedBankStatement();
final I_C_BankStatementLine bankStatementLine = getSingleSelectedBankStatementLine();
bankStatementLine.setC_BPartner_ID(bpartnerId.getRepoId());
if (paymentId != null)
|
{
bankStatementPaymentBL.linkSinglePayment(bankStatement, bankStatementLine, paymentId);
}
else
{
final Set<PaymentId> eligiblePaymentIds = bankStatementPaymentBL.findEligiblePaymentIds(
bankStatementLine,
bpartnerId,
ImmutableSet.of(), // excludePaymentIds
2 // limit
);
if (eligiblePaymentIds.isEmpty())
{
bankStatementPaymentBL.createSinglePaymentAndLink(bankStatement, bankStatementLine);
}
else if (eligiblePaymentIds.size() == 1)
{
PaymentId eligiblePaymentId = eligiblePaymentIds.iterator().next();
bankStatementPaymentBL.linkSinglePayment(bankStatement, bankStatementLine, eligiblePaymentId);
}
else
{
throw new FillMandatoryException(PARAM_C_Payment_ID);
}
}
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\banking\process\C_BankStatement_ReconcileWithSinglePayment.java
| 1
|
请完成以下Java代码
|
public boolean hasKey()
{
return m_value instanceof NamePair;
} // hasKey
/**
* String representation with key info
* @return info
*/
public String toStringX()
{
if (m_value instanceof NamePair)
{
NamePair pp = (NamePair)m_value;
StringBuffer sb = new StringBuffer(m_columnName);
sb.append("(").append(pp.getID()).append(")")
.append("=").append(pp.getName());
if (m_isPKey)
sb.append("(PK)");
|
return sb.toString();
}
else
return toString();
} // toStringX
public String getM_formatPattern() {
return m_formatPattern;
}
public void setM_formatPattern(String pattern) {
m_formatPattern = pattern;
}
} // PrintDataElement
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataElement.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringSecurity extends WebSecurityConfigurerAdapter {
private UserPrincipalDetailsService userPrincipalDetailsService;
public SpringSecurity(UserPrincipalDetailsService userPrincipalDetailsService){
this.userPrincipalDetailsService = userPrincipalDetailsService;
}
@Override
protected void configure(AuthenticationManagerBuilder auth){
auth.authenticationProvider(authenticationProvider());
}
@Override
protected void configure(HttpSecurity http) throws Exception{
http
.authorizeRequests()
.antMatchers("/index.html").permitAll()
.antMatchers("/profile/**").hasRole("ADMIN")
.antMatchers("/admin/**").hasAnyRole("ADMIN", "MANAGER")
.antMatchers("/api/public/test1").hasAuthority("ACCESS_TEST1")
.antMatchers("/api/public/test2").hasAuthority("ACCESS_TEST1")
.antMatchers("/api/public/users").hasRole("ADMIN")
.and()
.formLogin()
.loginProcessingUrl("/signin")
.loginPage("/login").permitAll()
.usernameParameter("txtUsername")
.passwordParameter("txtPassword")
.and()
|
.logout().logoutRequestMatcher(new AntPathRequestMatcher("/logout")).logoutSuccessUrl("/login")
.and()
.rememberMe().tokenValiditySeconds(2592000).key("mySecret!").rememberMeParameter("checkRememberMe");
/** */
}
@Bean
DaoAuthenticationProvider authenticationProvider(){
DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
daoAuthenticationProvider.setPasswordEncoder(passwordEncoder());
daoAuthenticationProvider.setUserDetailsService((UserDetailsService) this.userPrincipalDetailsService);
return daoAuthenticationProvider;
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\10.SpringCustomLogin\src\main\java\spring\custom\security\SpringSecurity.java
| 2
|
请完成以下Java代码
|
private Object createDefaultVariableValue(VariableDefinition variableDefinition) {
// take a default from the variable definition in the proc extensions
return variableParsingService.parse(variableDefinition);
}
private Set<String> checkRequiredVariables(
Map<String, Object> variables,
Map<String, VariableDefinition> variableDefinitionMap
) {
Set<String> missingRequiredVars = new HashSet<>();
variableDefinitionMap.forEach((k, v) -> {
if (!variables.containsKey(v.getName()) && v.isRequired()) {
missingRequiredVars.add(v.getName());
}
});
return missingRequiredVars;
}
private Set<String> validateVariablesAgainstDefinitions(
Map<String, Object> variables,
Map<String, VariableDefinition> variableDefinitionMap
) {
Set<String> mismatchedVars = new HashSet<>();
variableDefinitionMap.forEach((k, v) -> {
//if we have definition for this variable then validate it
if (variables.containsKey(v.getName())) {
if (!variableValidationService.validate(variables.get(v.getName()), v)) {
mismatchedVars.add(v.getName());
}
}
});
return mismatchedVars;
}
|
public void startProcessInstance(
ExecutionEntity processInstance,
CommandContext commandContext,
Map<String, Object> variables,
FlowElement initialFlowElement,
Map<String, Object> transientVariables,
String linkedProcessInstanceId,
String linkedProcessInstanceType
) {
ProcessDefinition processDefinition = ProcessDefinitionUtil.getProcessDefinition(
processInstance.getProcessDefinitionId()
);
Map<String, Object> calculatedVariables = calculateOutputVariables(
variables,
processDefinition,
initialFlowElement
);
super.startProcessInstance(
processInstance,
commandContext,
calculatedVariables,
initialFlowElement,
transientVariables,
linkedProcessInstanceId,
linkedProcessInstanceType
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\spring\process\ProcessVariablesInitiator.java
| 1
|
请完成以下Java代码
|
public int getAD_Tree_ID()
{
return getWebProject().getAD_TreeCMM_ID();
} // getAD_Tree_ID;
/**
* Before Save
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave (boolean newRecord)
{
if (isSummary())
{
setMediaType(null);
setAD_Image_ID(0);
}
return true;
} // beforeSave
/**
* After Save.
* Insert
* - create tree
* @param newRecord insert
* @param success save success
* @return true if saved
*/
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
if (!success)
return success;
if (newRecord)
{
StringBuffer sb = new StringBuffer ("INSERT INTO AD_TreeNodeCMM "
+ "(AD_Client_ID,AD_Org_ID, IsActive,Created,CreatedBy,Updated,UpdatedBy, "
+ "AD_Tree_ID, Node_ID, Parent_ID, SeqNo) "
+ "VALUES (")
.append(getAD_Client_ID()).append(",0, 'Y', now(), 0, now(), 0,")
.append(getAD_Tree_ID()).append(",").append(get_ID())
.append(", 0, 999)");
int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString(), get_TrxName());
if (no > 0)
log.debug("#" + no + " - TreeType=CMM");
else
log.warn("#" + no + " - TreeType=CMM");
return no > 0;
}
return success;
} // afterSave
/**
* After Delete
* @param success
* @return deleted
*/
@Override
protected boolean afterDelete (boolean success)
{
|
if (!success)
return success;
//
StringBuffer sb = new StringBuffer ("DELETE FROM AD_TreeNodeCMM ")
.append(" WHERE Node_ID=").append(get_IDOld())
.append(" AND AD_Tree_ID=").append(getAD_Tree_ID());
int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString(), get_TrxName());
if (no > 0)
log.debug("#" + no + " - TreeType=CMM");
else
log.warn("#" + no + " - TreeType=CMM");
return no > 0;
} // afterDelete
/**
* Get File Name
* @return file name return ID
*/
public String getFileName()
{
return get_ID() + getExtension();
} // getFileName
/**
* Get Extension with .
* @return extension
*/
public String getExtension()
{
String mt = getMediaType();
if (MEDIATYPE_ApplicationPdf.equals(mt))
return ".pdf";
if (MEDIATYPE_ImageGif.equals(mt))
return ".gif";
if (MEDIATYPE_ImageJpeg.equals(mt))
return ".jpg";
if (MEDIATYPE_ImagePng.equals(mt))
return ".png";
if (MEDIATYPE_TextCss.equals(mt))
return ".css";
// Unknown
return ".dat";
} // getExtension
/**
* Get Image
* @return image or null
*/
public MImage getImage()
{
if (getAD_Image_ID() != 0)
return MImage.get(getCtx(), getAD_Image_ID());
return null;
} // getImage
} // MMedia
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MMedia.java
| 1
|
请完成以下Java代码
|
public void setIsPOBoxNum (final boolean IsPOBoxNum)
{
set_Value (COLUMNNAME_IsPOBoxNum, IsPOBoxNum);
}
@Override
public boolean isPOBoxNum()
{
return get_ValueAsBoolean(COLUMNNAME_IsPOBoxNum);
}
@Override
public void setIsPostalValidated (final boolean IsPostalValidated)
{
set_ValueNoCheck (COLUMNNAME_IsPostalValidated, IsPostalValidated);
}
@Override
public boolean isPostalValidated()
{
return get_ValueAsBoolean(COLUMNNAME_IsPostalValidated);
}
@Override
public void setLatitude (final @Nullable BigDecimal Latitude)
{
set_Value (COLUMNNAME_Latitude, Latitude);
}
@Override
public BigDecimal getLatitude()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Latitude);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setLongitude (final @Nullable BigDecimal Longitude)
{
set_Value (COLUMNNAME_Longitude, Longitude);
}
@Override
public BigDecimal getLongitude()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Longitude);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPOBox (final @Nullable java.lang.String POBox)
{
set_ValueNoCheck (COLUMNNAME_POBox, POBox);
}
@Override
public java.lang.String getPOBox()
{
return get_ValueAsString(COLUMNNAME_POBox);
}
@Override
public void setPostal (final @Nullable java.lang.String Postal)
|
{
set_ValueNoCheck (COLUMNNAME_Postal, Postal);
}
@Override
public java.lang.String getPostal()
{
return get_ValueAsString(COLUMNNAME_Postal);
}
@Override
public void setPostal_Add (final @Nullable java.lang.String Postal_Add)
{
set_ValueNoCheck (COLUMNNAME_Postal_Add, Postal_Add);
}
@Override
public java.lang.String getPostal_Add()
{
return get_ValueAsString(COLUMNNAME_Postal_Add);
}
@Override
public void setRegionName (final @Nullable java.lang.String RegionName)
{
set_ValueNoCheck (COLUMNNAME_RegionName, RegionName);
}
@Override
public java.lang.String getRegionName()
{
return get_ValueAsString(COLUMNNAME_RegionName);
}
@Override
public void setStreet (final @Nullable java.lang.String Street)
{
set_Value (COLUMNNAME_Street, Street);
}
@Override
public java.lang.String getStreet()
{
return get_ValueAsString(COLUMNNAME_Street);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Location.java
| 1
|
请完成以下Java代码
|
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
|
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return "[firstName=" + firstName + ", middleName="
+ middleName + ", lastName=" + lastName + "]";
}
}
|
repos\SpringBootBucket-master\springboot-echarts\src\main\java\com\xncoding\benchmark\json\model\FullName.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public QueryVariableOperation getVariableOperation() {
if (operation == null) {
return null;
}
return QueryVariableOperation.forFriendlyName(operation);
}
@ApiModelProperty(allowableValues = "equals, notEquals, equalsIgnoreCase, notEqualsIgnoreCase, like, likeIgnoreCase, greaterThan, greaterThanOrEquals, lessThan, lessThanOrEquals")
public void setOperation(String operation) {
this.operation = operation;
}
public String getOperation() {
return operation;
}
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public enum QueryVariableOperation {
EQUALS("equals"), NOT_EQUALS("notEquals"), EQUALS_IGNORE_CASE("equalsIgnoreCase"), NOT_EQUALS_IGNORE_CASE("notEqualsIgnoreCase"), LIKE("like"), LIKE_IGNORE_CASE("likeIgnoreCase"), GREATER_THAN("greaterThan"), GREATER_THAN_OR_EQUALS(
"greaterThanOrEquals"), LESS_THAN("lessThan"), LESS_THAN_OR_EQUALS("lessThanOrEquals");
private final String friendlyName;
|
private QueryVariableOperation(String friendlyName) {
this.friendlyName = friendlyName;
}
public String getFriendlyName() {
return friendlyName;
}
public static QueryVariableOperation forFriendlyName(String friendlyName) {
for (QueryVariableOperation type : values()) {
if (type.friendlyName.equals(friendlyName)) {
return type;
}
}
throw new FlowableIllegalArgumentException("Unsupported variable query operation: " + friendlyName);
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\engine\variable\QueryVariable.java
| 2
|
请完成以下Java代码
|
default Collection<? extends IViewRow> getIncludedRows() { return ImmutableList.of(); }
// @formatter:on
//
// Attributes
// @formatter:off
default boolean hasAttributes() { return false; }
default IViewRowAttributes getAttributes() { throw new EntityNotFoundException("Row does not support attributes"); }
// @formatter:on
//
// IncludedView
// @formatter:off
default ViewId getIncludedViewId() { return null; }
// @formatter:on
//
// Single column row
// @formatter:off
/** @return true if frontend shall display one single column */
|
default boolean isSingleColumn() { return false; }
/** @return text to be displayed if {@link #isSingleColumn()} */
default ITranslatableString getSingleColumnCaption() { return TranslatableStrings.empty(); }
// @formatter:on
/**
* @return a stream of given row and all it's included rows recursively
*/
default Stream<IViewRow> streamRecursive()
{
return this.getIncludedRows()
.stream()
.map(IViewRow::streamRecursive)
.reduce(Stream.of(this), Stream::concat);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\IViewRow.java
| 1
|
请完成以下Java代码
|
private static void updateRecord(final I_C_POS record, final @NonNull POSTerminal from)
{
record.setC_POS_Journal_ID(POSCashJournalId.toRepoId(from.getCashJournalId()));
record.setCashLastBalance(from.getCashLastBalance().toBigDecimal());
}
@Nullable
private static POSTerminalPaymentProcessorConfig extractPaymentProcessorConfig(final I_C_POS record)
{
final POSPaymentProcessorType type = POSPaymentProcessorType.ofNullableCode(record.getPOSPaymentProcessor());
if (type == null)
{
return null;
}
return POSTerminalPaymentProcessorConfig.builder()
.type(type)
.sumUpConfigId(SumUpConfigId.ofRepoIdOrNull(record.getSUMUP_Config_ID()))
.build();
}
private POSShipFrom extractShipFrom(final I_C_POS record)
{
final WarehouseId shipFromWarehouseId = WarehouseId.ofRepoId(record.getM_Warehouse_ID());
return POSShipFrom.builder()
.warehouseId(shipFromWarehouseId)
.clientAndOrgId(warehouseBL.getWarehouseClientAndOrgId(shipFromWarehouseId))
.countryId(warehouseBL.getCountryId(shipFromWarehouseId))
.build();
}
private @NonNull BPartnerLocationAndCaptureId extractWalkInCustomerShipTo(final I_C_POS record)
{
|
final BPartnerId walkInCustomerId = BPartnerId.ofRepoId(record.getC_BPartnerCashTrx_ID());
return BPartnerLocationAndCaptureId.ofRecord(
bpartnerDAO.retrieveBPartnerLocation(BPartnerLocationQuery.builder()
.type(BPartnerLocationQuery.Type.SHIP_TO)
.bpartnerId(walkInCustomerId)
.build())
);
}
public POSTerminal updateById(@NonNull final POSTerminalId posTerminalId, @NonNull final UnaryOperator<POSTerminal> updater)
{
return trxManager.callInThreadInheritedTrx(() -> {
final I_C_POS record = retrieveRecordById(posTerminalId);
final POSTerminal posTerminalBeforeChange = fromRecord(record);
final POSTerminal posTerminal = updater.apply(posTerminalBeforeChange);
if (Objects.equals(posTerminal, posTerminalBeforeChange))
{
return posTerminalBeforeChange;
}
updateRecord(record, posTerminal);
InterfaceWrapperHelper.save(record);
return posTerminal;
});
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSTerminalService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
// 分组信息
.groupName("默认分组")
.enable(swaggerEnable)
.select()
.apis(RequestHandlerSelectors.basePackage(SWAGGER_SCAN_BASE_PACKAGE))
// 可以根据url路径设置哪些请求加入文档,这里可以配置不需要显示的文档
.paths(PathSelectors.any())
//paths: 这里是控制哪些路径的api会被显示出来,比如下方的参数就是除了/user以外的其它路径都会生成api文档
// .paths((String a) ->
// !a.equals("/user"))
.build();
}
|
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
//设置文档的标题
.title("用户信息文档")
// 设置文档的描述
.description("文档描述信息或者特殊说明信息")
// 设置文档的版本信息-> 1.0.0 Version information
.version(VERSION)
// 设置文档的License信息->1.3 License information
.termsOfServiceUrl("http://www.baidu.com")
// 设置联系人
.contact(new Contact("汪雨浩", "http://www.baidu.com", "xxx@163.com"))
.build();
}
}
|
repos\spring-boot-student-master\spring-boot-student-swagger\src\main\java\com\xiaolyuh\config\SwaggerConfig.java
| 2
|
请完成以下Java代码
|
public String modelChange(PO po, int type) throws Exception
{
if (I_AD_Table_MView.Table_Name.equals(po.get_TableName()))
{
processMetadataChanges(po, type);
}
else if (TYPE_AFTER_NEW == type || TYPE_AFTER_CHANGE == type || TYPE_AFTER_DELETE == type)
{
refreshFromSource(po, type);
}
return null;
}
private void processMetadataChanges(PO po, int type)
{
final I_AD_Table_MView mview = InterfaceWrapperHelper.create(po, I_AD_Table_MView.class);
if (TYPE_AFTER_NEW == type
|| (TYPE_AFTER_CHANGE == type && po.is_ValueChanged(I_AD_Table_MView.COLUMNNAME_IsValid) && mview.isValid()))
{
addMView(mview, false);
}
}
private void refreshFromSource(PO sourcePO, int changeType)
{
final String sourceTableName = sourcePO.get_TableName();
final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class);
for (I_AD_Table_MView mview : mviewBL.fetchAll(Env.getCtx()))
{
MViewMetadata mdata = mviewBL.getMetadata(mview);
if (mdata == null)
{
mview.setIsValid(false);
InterfaceWrapperHelper.save(mview);
log.info("No metadata found for " + mview + " [SKIP]");
continue;
}
if (!mdata.getSourceTables().contains(sourceTableName))
{
// not relevant PO for this MView
continue;
}
if (!mviewBL.isSourceChanged(mdata, sourcePO, changeType))
{
// no relevant changes for this view
continue;
}
refreshFromSource(mdata, sourcePO, new RefreshMode[] { RefreshMode.Partial });
}
}
|
public void refreshFromSource(MViewMetadata mdata, PO sourcePO, RefreshMode[] refreshModes)
{
final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class);
final I_AD_Table_MView mview = mviewBL.fetchForTableName(sourcePO.getCtx(), mdata.getTargetTableName(), sourcePO.get_TrxName());
boolean staled = true;
for (RefreshMode refreshMode : refreshModes)
{
if (mviewBL.isAllowRefresh(mview, sourcePO, refreshMode))
{
mviewBL.refresh(mview, sourcePO, refreshMode, sourcePO.get_TrxName());
staled = false;
break;
}
}
//
// We should do a complete refresh => marking mview as staled
if (staled)
{
mviewBL.setStaled(mview);
}
}
private boolean addMView(I_AD_Table_MView mview, boolean invalidateIfNecessary)
{
final ITableMViewBL mviewBL = Services.get(ITableMViewBL.class);
MViewMetadata mdata = mviewBL.getMetadata(mview);
if (mdata == null)
{
// no metadata found => IGNORE
if (invalidateIfNecessary)
{
mview.setIsValid(false);
InterfaceWrapperHelper.save(mview);
}
return false;
}
for (String sourceTableName : mdata.getSourceTables())
{
engine.addModelChange(sourceTableName, this);
}
registeredTables.add(mview.getAD_Table_ID());
return true;
}
@Override
public String docValidate(PO po, int timing)
{
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\engine\MViewModelValidator.java
| 1
|
请完成以下Java代码
|
public class Customer implements Serializable {
private int id;
@NotBlank
private String name;
@NotBlank
private String email;
@NotBlank
private String address;
public Customer() {
}
public Customer(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
|
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", address=" + address +
'}';
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-http-3\src\main\java\com\baeldung\bulkandbatchapi\request\Customer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String getLocationExternalIdentifier(@NonNull final BPartnerRow bPartnerRow)
{
return buildExternalIdentifier(bPartnerRow.getPartnerCode().getRawPartnerCode(), bPartnerRow.getSection());
}
@NonNull
private static JsonRequestBPartnerUpsertItem buildSectionGroupJsonRequestBPartnerUpsertItem(
@NonNull final BPartnerRow bPartnerRow,
@NonNull final String orgCode,
@NonNull final JsonMetasfreshId externalSystemConfigId
)
{
final JsonRequestBPartner jsonRequestBPartner = new JsonRequestBPartner();
jsonRequestBPartner.setCode(bPartnerRow.getPartnerCode().getPartnerCode());
jsonRequestBPartner.setCompanyName(bPartnerRow.getName1());
jsonRequestBPartner.setName(bPartnerRow.getName1());
|
jsonRequestBPartner.setName2(bPartnerRow.getName2());
jsonRequestBPartner.setDescription(bPartnerRow.getSearchTerm());
final JsonRequestComposite.JsonRequestCompositeBuilder jsonRequestCompositeBuilder = JsonRequestComposite.builder()
.bpartner(jsonRequestBPartner)
.orgCode(orgCode);
return JsonRequestBPartnerUpsertItem.builder()
.bpartnerComposite(jsonRequestCompositeBuilder.build())
.bpartnerIdentifier(ExternalIdentifierFormat.formatExternalId(bPartnerRow.getPartnerCode().getPartnerCode()))
.externalSystemConfigId(externalSystemConfigId)
.isReadOnlyInMetasfresh(true)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-sap-file-import\src\main\java\de\metas\camel\externalsystems\sap\bpartner\UpsertBPartnerRequestBuilder.java
| 2
|
请完成以下Java代码
|
public class CaseTaskExport extends AbstractChildTaskExport<CaseTask> {
@Override
protected Class<CaseTask> getExportablePlanItemDefinitionClass() {
return CaseTask.class;
}
@Override
protected String getPlanItemDefinitionXmlElementValue(CaseTask caseTask) {
return ELEMENT_CASE_TASK;
}
@Override
protected void writePlanItemDefinitionSpecificAttributes(CaseTask caseTask, XMLStreamWriter xtw) throws Exception {
super.writePlanItemDefinitionSpecificAttributes(caseTask, xtw);
TaskExport.writeCommonTaskAttributes(caseTask, xtw);
if (caseTask.getFallbackToDefaultTenant() != null) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_FALLBACK_TO_DEFAULT_TENANT, caseTask.getFallbackToDefaultTenant().toString());
}
if (caseTask.isSameDeployment()) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_SAME_DEPLOYMENT, "true");
}
if (StringUtils.isNotEmpty(caseTask.getCaseInstanceIdVariableName())) {
xtw.writeAttribute(FLOWABLE_EXTENSIONS_PREFIX, FLOWABLE_EXTENSIONS_NAMESPACE, ATTRIBUTE_ID_VARIABLE_NAME, caseTask.getCaseInstanceIdVariableName());
}
}
@Override
protected void writePlanItemDefinitionBody(CmmnModel model, CaseTask caseTask, XMLStreamWriter xtw, CmmnXmlConverterOptions options) throws Exception {
|
super.writePlanItemDefinitionBody(model, caseTask, xtw, options);
// Always export the case reference as an expression, even if the caseRef is set
if (StringUtils.isNotEmpty(caseTask.getCaseRef()) || StringUtils.isNotEmpty(caseTask.getCaseRefExpression())) {
xtw.writeStartElement(ELEMENT_CASE_REF_EXPRESSION);
xtw.writeCData(
StringUtils.isNotEmpty(caseTask.getCaseRef()) ?
caseTask.getCaseRef() :
caseTask.getCaseRefExpression()
);
xtw.writeEndElement();
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\export\CaseTaskExport.java
| 1
|
请完成以下Java代码
|
public class RepositoryCacheWriter<T, ID> extends RepositoryCacheLoaderWriterSupport<T, ID> {
public RepositoryCacheWriter(CrudRepository<T, ID> repository) {
super(repository);
}
@Override
public void beforeCreate(EntryEvent<ID, T> event) throws CacheWriterException {
doRepositoryOp(event.getNewValue(), getRepository()::save);
}
@Override
public void beforeUpdate(EntryEvent<ID, T> event) throws CacheWriterException {
doRepositoryOp(event.getNewValue(), getRepository()::save);
}
@Override
public void beforeDestroy(EntryEvent<ID, T> event) throws CacheWriterException {
//doRepositoryOp(event.getOldValue(), FunctionUtils.toNullReturningFunction(getRepository()::delete));
doRepositoryOp(event.getKey(), FunctionUtils.toNullReturningFunction(getRepository()::deleteById));
}
|
@Override
public void beforeRegionClear(RegionEvent<ID, T> event) throws CacheWriterException {
if (isNukeAndPaveEnabled()) {
doRepositoryOp(null, FunctionUtils.toNullReturningFunction(it -> getRepository().deleteAll()));
}
}
@Override
public void beforeRegionDestroy(RegionEvent<ID, T> event) throws CacheWriterException {
// TODO: perhaps implement by releasing external data source resources
// (i.e. destroy database object(s), e.g. DROP TABLE)
}
@Override
protected CacheRuntimeException newCacheRuntimeException(Supplier<String> messageSupplier, Throwable cause) {
return new CacheWriterException(messageSupplier.get(), cause);
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\cache\RepositoryCacheWriter.java
| 1
|
请完成以下Java代码
|
public static ITranslatableString checkEMailValid(@Nullable final EMailAddress email)
{
if (email == null)
{
return TranslatableStrings.constant("no email");
}
return checkEMailValid(email.getAsString());
}
@Nullable
public static ITranslatableString checkEMailValid(@Nullable final String email)
{
if (email == null || Check.isBlank(email))
{
return TranslatableStrings.constant("no email");
}
try
{
final InternetAddress ia = new InternetAddress(email, true);
ia.validate(); // throws AddressException
if (ia.getAddress() == null)
{
return TranslatableStrings.constant("invalid email");
}
return null; // OK
}
catch (final AddressException ex)
{
logger.warn("Invalid email address: {}", email, ex);
return TranslatableStrings.constant(ex.getLocalizedMessage());
}
}
private static final Logger logger = LogManager.getLogger(EMailAddress.class);
private final String emailStr;
|
private EMailAddress(@NonNull final String emailStr)
{
this.emailStr = emailStr.trim();
if (this.emailStr.isEmpty())
{
throw new AdempiereException("Empty email address is not valid");
}
}
@JsonValue
public String getAsString()
{
return emailStr;
}
@Nullable
public static String toStringOrNull(@Nullable final EMailAddress emailAddress)
{
return emailAddress != null ? emailAddress.getAsString() : null;
}
@Deprecated
@Override
public String toString()
{
return getAsString();
}
public InternetAddress toInternetAddress() throws AddressException
{
return new InternetAddress(emailStr, true);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\EMailAddress.java
| 1
|
请完成以下Java代码
|
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
|
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", name=" + name
+ ", deploymentId=" + deploymentId
+ ", tenantId=" + tenantId
+ ", type=" + type
+ ", createTime=" + createTime
+ ", rootProcessInstanceId=" + rootProcessInstanceId
+ ", removalTime=" + removalTime
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ByteArrayEntity.java
| 1
|
请完成以下Java代码
|
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
ImmutableMoney other = (ImmutableMoney) obj;
if (amount != other.amount)
return false;
if (currency == null) {
if (other.currency != null)
return false;
} else if (!currency.equals(other.currency))
return false;
return true;
|
}
public long getAmount() {
return amount;
}
public String getCurrency() {
return currency;
}
@Override
public String toString() {
return "ImmutableMoney [amount=" + amount + ", currency=" + currency + "]";
}
}
|
repos\tutorials-master\google-auto-project\src\main\java\com\baeldung\autovalue\ImmutableMoney.java
| 1
|
请完成以下Java代码
|
public class ReceiptScheduleKeyValueHandler implements IAggregationKeyValueHandler<I_M_ReceiptSchedule>
{
@Override
public List<Object> getValues(@NonNull final I_M_ReceiptSchedule rs)
{
final IReceiptScheduleBL receiptScheduleBL = Services.get(IReceiptScheduleBL.class);
final List<Object> values = new ArrayList<>();
values.add(rs.getC_DocType_ID());
values.add(receiptScheduleBL.getC_BPartner_Effective_ID(rs));
values.add(receiptScheduleBL.getC_BPartner_Location_Effective_ID(rs));
values.add(receiptScheduleBL.getWarehouseEffectiveId(rs).getRepoId());
final BPartnerContactId bPartnerContactID = receiptScheduleBL.getBPartnerContactID(rs);
if (bPartnerContactID != null)
{
values.add(bPartnerContactID);
}
values.add(rs.getAD_Org_ID());
values.add(rs.getDateOrdered());
values.add(rs.getC_Order_ID());
|
if (Check.isNotBlank(rs.getExternalResourceURL()))
{
//remove any `org.compiere.util.Util.ArrayKey.SEPARATOR` that may be present in the URL
final String externalResourceURL = rs.getExternalResourceURL().replaceAll(SEPARATOR, "");
values.add(externalResourceURL);
}
values.add(rs.getExternalHeaderId());
if (rs.getExternalSystem_ID() > 0)
{
values.add(rs.getExternalSystem_ID());
}
return values;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\agg\key\impl\ReceiptScheduleKeyValueHandler.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
rabbitmq:
first:
host: 192.168.68.11
port: 5672
username: tbddev
password: tbddev!#%2017
virtual-host: /tbddev
second:
host: 192.168.68.11
port: 5672
username: tbdrc
password: tbdrc!#%2017
virtual-host: /tbdrc
rabbit:
mq:
queue0: tbd_resume_id_dev_0
queue1
|
: tbd_resume_id_dev_1
queue2: tbd_resume_id_dev_2
queue3: tbd_resume_id_dev_3
queue4: tbd_resume_id_dev_4
queue5: tbd_resume_id_dev_5
|
repos\spring-boot-quick-master\quick-multi-rabbitmq\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public String getProcessMsg()
{
return m_processMsg;
}
@Override
public int getDoc_User_ID()
{
return getAD_User_ID();
}
@Override
public int getC_Currency_ID()
{
final I_M_PriceList pl = Services.get(IPriceListDAO.class).getById(getM_PriceList_ID());
return pl.getC_Currency_ID();
}
/**
* Get Document Approval Amount
*
* @return amount
*/
@Override
public BigDecimal getApprovalAmt()
{
return getTotalLines();
}
|
private String getUserName()
{
return Services.get(IUserDAO.class).retrieveUserOrNull(getCtx(), getAD_User_ID()).getName();
}
/**
* @return true if CO, CL or RE
*/
public boolean isComplete()
{
final String ds = getDocStatus();
return DOCSTATUS_Completed.equals(ds)
|| DOCSTATUS_Closed.equals(ds)
|| DOCSTATUS_Reversed.equals(ds);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MRequisition.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Duration getQuietPeriod() {
return this.quietPeriod;
}
public void setQuietPeriod(Duration quietPeriod) {
this.quietPeriod = quietPeriod;
}
public @Nullable String getTriggerFile() {
return this.triggerFile;
}
public void setTriggerFile(@Nullable String triggerFile) {
this.triggerFile = triggerFile;
}
public List<File> getAdditionalPaths() {
return this.additionalPaths;
}
public void setAdditionalPaths(List<File> additionalPaths) {
this.additionalPaths = additionalPaths;
}
public boolean isLogConditionEvaluationDelta() {
return this.logConditionEvaluationDelta;
}
public void setLogConditionEvaluationDelta(boolean logConditionEvaluationDelta) {
this.logConditionEvaluationDelta = logConditionEvaluationDelta;
}
}
/**
|
* LiveReload properties.
*/
public static class Livereload {
/**
* Whether to enable a livereload.com-compatible server.
*/
private boolean enabled;
/**
* Server port.
*/
private int port = 35729;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public int getPort() {
return this.port;
}
public void setPort(int port) {
this.port = port;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-devtools\src\main\java\org\springframework\boot\devtools\autoconfigure\DevToolsProperties.java
| 2
|
请完成以下Java代码
|
public int getY() {
return y;
}
@Override
public void setY(int y) {
this.y = y;
}
@Override
public int getWidth() {
return width;
}
@Override
|
public void setWidth(int width) {
this.width = width;
}
@Override
public int getHeight() {
return height;
}
@Override
public void setHeight(int height) {
this.height = height;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ParticipantProcess.java
| 1
|
请完成以下Java代码
|
public void markOccurrence(String name, long times) {
CommandCounter counter = commands.get(name);
if (counter == null) {
synchronized (commands) {
if (counter == null) {
counter = new CommandCounter(name);
commands.put(name, counter);
}
}
}
counter.mark(times);
}
public synchronized void addWebapp(String webapp) {
if (!webapps.contains(webapp)) {
webapps.add(webapp);
|
}
}
public void clearCommandCounts() {
commands.clear();
}
public void clear() {
commands.clear();
licenseKey = null;
applicationServer = null;
webapps.clear();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\diagnostics\DiagnosticsRegistry.java
| 1
|
请完成以下Java代码
|
final String constructNextPageUri(final UriComponentsBuilder uriBuilder, final int page, final int size) {
return uriBuilder.replaceQueryParam(PAGE, page + 1)
.replaceQueryParam("size", size)
.build()
.encode()
.toUriString();
}
final String constructPrevPageUri(final UriComponentsBuilder uriBuilder, final int page, final int size) {
return uriBuilder.replaceQueryParam(PAGE, page - 1)
.replaceQueryParam("size", size)
.build()
.encode()
.toUriString();
}
final String constructFirstPageUri(final UriComponentsBuilder uriBuilder, final int size) {
return uriBuilder.replaceQueryParam(PAGE, 0)
.replaceQueryParam("size", size)
.build()
.encode()
.toUriString();
}
final String constructLastPageUri(final UriComponentsBuilder uriBuilder, final int totalPages, final int size) {
return uriBuilder.replaceQueryParam(PAGE, totalPages)
.replaceQueryParam("size", size)
.build()
.encode()
.toUriString();
}
final boolean hasNextPage(final int page, final int totalPages) {
return page < (totalPages - 1);
|
}
final boolean hasPreviousPage(final int page) {
return page > 0;
}
final boolean hasFirstPage(final int page) {
return hasPreviousPage(page);
}
final boolean hasLastPage(final int page, final int totalPages) {
return (totalPages > 1) && hasNextPage(page, totalPages);
}
// template
protected void plural(final UriComponentsBuilder uriBuilder, final Class clazz) {
final String resourceName = clazz.getSimpleName()
.toLowerCase() + "s";
uriBuilder.path("/" + resourceName);
}
}
|
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\web\hateoas\listener\PaginatedResultsRetrievedDiscoverabilityListener.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class TimeLimiterDemoController {
@Autowired
private TimeLimiterService timeLimiterService;
@GetMapping("/get_user")
public String getUser(@RequestParam("id") Integer id) throws ExecutionException, InterruptedException {
return timeLimiterService.getUser0(id).get();
}
@Service
public static class TimeLimiterService {
private Logger logger = LoggerFactory.getLogger(TimeLimiterService.class);
@Bulkhead(name = "backendD", type = Bulkhead.Type.THREADPOOL)
|
@TimeLimiter(name = "backendF", fallbackMethod = "getUserFallback")
public CompletableFuture<String> getUser0(Integer id) throws InterruptedException {
logger.info("[getUser][id({})]", id);
Thread.sleep(10 * 1000L); // sleep 10 秒
return CompletableFuture.completedFuture("User:" + id);
}
public CompletableFuture<String> getUserFallback(Integer id, Throwable throwable) {
logger.info("[getUserFallback][id({}) exception({})]", id, throwable.getClass().getSimpleName());
return CompletableFuture.completedFuture("mock:User:" + id);
}
}
}
|
repos\SpringBoot-Labs-master\lab-59\lab-59-resilience4j-actuator\src\main\java\cn\iocoder\springboot\lab59\resillience4jdemo\controller\TimeLimiterDemoController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public List<RestIdentityLink> getIdentityLinksForFamily(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "family") @PathVariable("family") String family) {
Task task = getTaskFromRequestWithoutAccessCheck(taskId);
if (family == null || (!CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_GROUPS.equals(family) && !CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS.equals(family))) {
throw new FlowableIllegalArgumentException("Identity link family should be 'users' or 'groups'.");
}
if (restApiInterceptor != null) {
restApiInterceptor.accessTaskIdentityLinks(task);
}
boolean isUser = family.equals(CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS);
List<RestIdentityLink> results = new ArrayList<>();
|
List<IdentityLink> allLinks = taskService.getIdentityLinksForTask(task.getId());
for (IdentityLink link : allLinks) {
boolean match = false;
if (isUser) {
match = link.getUserId() != null;
} else {
match = link.getGroupId() != null;
}
if (match) {
results.add(restResponseFactory.createRestIdentityLink(link));
}
}
return results;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskIdentityLinkFamilyResource.java
| 2
|
请完成以下Java代码
|
public void onSuccess(TransportProtos.GetOtaPackageResponseMsg msg) {
String title = exchange.getQueryParameter("title");
String version = exchange.getQueryParameter("version");
if (msg.getResponseStatus().equals(TransportProtos.ResponseStatus.SUCCESS)) {
String firmwareId = new UUID(msg.getOtaPackageIdMSB(), msg.getOtaPackageIdLSB()).toString();
if ((title == null || msg.getTitle().equals(title)) && (version == null || msg.getVersion().equals(version))) {
String strChunkSize = exchange.getQueryParameter("size");
String strChunk = exchange.getQueryParameter("chunk");
int chunkSize = StringUtils.isEmpty(strChunkSize) ? 0 : Integer.parseInt(strChunkSize);
int chunk = StringUtils.isEmpty(strChunk) ? 0 : Integer.parseInt(strChunk);
respondOtaPackage(exchange, transportContext.getOtaPackageDataCache().get(firmwareId, chunkSize, chunk));
} else {
exchange.respond(CoAP.ResponseCode.BAD_REQUEST);
}
} else {
exchange.respond(CoAP.ResponseCode.NOT_FOUND);
}
}
@Override
public void onError(Throwable e) {
log.warn("Failed to process request", e);
|
exchange.respond(CoAP.ResponseCode.INTERNAL_SERVER_ERROR);
}
}
private void respondOtaPackage(CoapExchange exchange, byte[] data) {
Response response = new Response(CoAP.ResponseCode.CONTENT);
if (data != null && data.length > 0) {
response.setPayload(data);
if (exchange.getRequestOptions().getBlock2() != null) {
int chunkSize = exchange.getRequestOptions().getBlock2().getSzx();
int blockNum = exchange.getRequestOptions().getBlock2().getNum();
boolean lastFlag = data.length <= chunkSize;
response.getOptions().setBlock2(chunkSize, lastFlag, blockNum);
}
transportContext.getExecutor().submit(() -> exchange.respond(response));
}
}
}
|
repos\thingsboard-master\common\transport\coap\src\main\java\org\thingsboard\server\transport\coap\OtaPackageTransportResource.java
| 1
|
请完成以下Java代码
|
public void sendDelayMsg() {
rocketMQTemplate.syncSend( "Topic-Delay",
MessageBuilder.withPayload( "Hello MQ".getBytes() ).build(),
3000,
//设置延时等级3,这个消息将在10s之后发送(现在只支持固定的几个时间,详看delayTimeLevel)
//messageDelayLevel = "1s 5s 10s 30s 1m 2m 3m 4m 5m 6m 7m 8m 9m 10m 20m 30m 1h 2h";
3 );
}
/**
* 批量消息
*/
public void sendBatchMsg(List<Message> messages) {
rocketMQTemplate.syncSend( "springboot-rocketmq", messages );
}
/**
|
* 事务消息
*/
public void sendTransactionMsg(){
TransactionSendResult transactionSendResult = rocketMQTemplate.sendMessageInTransaction(
"Topic-Tx:TagA",
MessageBuilder.withPayload( "Hello MQ transaction===".getBytes() ).build(),
null );
SendStatus sendStatus = transactionSendResult.getSendStatus();
LocalTransactionState localTransactionState = transactionSendResult.getLocalTransactionState();
System.out.println( new Date() + " Send mq message status "+ sendStatus +" , localTransactionState "+ localTransactionState );
}
}
|
repos\SpringBootLearning-master (1)\springboot-rocketmq-message\src\main\java\com\itwolfed\msg\Producer.java
| 1
|
请完成以下Java代码
|
private String buildAuthorizationRequestUri() {
Map<String, Object> parameters = getParameters(); // Not encoded
this.parametersConsumer.accept(parameters);
MultiValueMap<String, String> queryParams = new LinkedMultiValueMap<>();
parameters.forEach((k, v) -> {
String key = encodeQueryParam(k);
if (v instanceof Iterable) {
((Iterable<?>) v).forEach((value) -> queryParams.add(key, encodeQueryParam(String.valueOf(value))));
}
else if (v != null && v.getClass().isArray()) {
Object[] values = (Object[]) v;
for (Object value : values) {
queryParams.add(key, encodeQueryParam(String.valueOf(value)));
}
}
else {
queryParams.set(key, encodeQueryParam(String.valueOf(v)));
}
});
UriBuilder uriBuilder = this.uriBuilderFactory.uriString(this.authorizationUri).queryParams(queryParams);
return this.authorizationRequestUriFunction.apply(uriBuilder).toString();
}
protected Map<String, Object> getParameters() {
Map<String, Object> parameters = new LinkedHashMap<>();
parameters.put(OAuth2ParameterNames.RESPONSE_TYPE, this.responseType.getValue());
parameters.put(OAuth2ParameterNames.CLIENT_ID, this.clientId);
if (!CollectionUtils.isEmpty(this.scopes)) {
parameters.put(OAuth2ParameterNames.SCOPE, StringUtils.collectionToDelimitedString(this.scopes, " "));
}
if (this.state != null) {
|
parameters.put(OAuth2ParameterNames.STATE, this.state);
}
if (this.redirectUri != null) {
parameters.put(OAuth2ParameterNames.REDIRECT_URI, this.redirectUri);
}
parameters.putAll(this.additionalParameters);
return parameters;
}
// Encode query parameter value according to RFC 3986
private static String encodeQueryParam(String value) {
return UriUtils.encodeQueryParam(value, StandardCharsets.UTF_8);
}
}
}
|
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\OAuth2AuthorizationRequest.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private <T> List<T> transformQueryResult(@NonNull final GetQueryResultsResponse queryResultsResponse,
@NonNull final Class<T> targetClass) {
final var response = new ArrayList<T>();
final var rows = queryResultsResponse.resultSet().rows();
if (rows.isEmpty()) {
return Collections.emptyList();
}
final var headers = rows.get(0).data().stream()
.map(Datum::varCharValue)
.toList();
rows.stream()
.skip(1)
.forEach(row -> {
final var element = new JSONObject();
final var data = row.data();
|
for (int i = 0; i < headers.size(); i++) {
final var key = headers.get(i);
final var value = data.get(i).varCharValue();
element.put(key, value);
}
final var obj = OBJECT_MAPPER.convertValue(element, targetClass);
response.add(obj);
});
return response;
}
public record User(Integer id, String name, Integer age, String city) {};
}
|
repos\tutorials-master\aws-modules\amazon-athena\src\main\java\com\baeldung\athena\service\QueryService.java
| 2
|
请完成以下Java代码
|
public class UserDO {
/** 用户编号 **/
private Integer id;
/** 用户名 **/
private String username;
/** 密码 **/
private String password;
public Integer getId() {
return id;
}
public UserDO setId(Integer id) {
this.id = id;
return this;
}
public String getUsername() {
return username;
}
|
public UserDO setUsername(String username) {
this.username = username;
return this;
}
public String getPassword() {
return password;
}
public UserDO setPassword(String password) {
this.password = password;
return this;
}
}
|
repos\SpringBoot-Labs-master\lab-55\lab-55-mapstruct-demo\src\main\java\cn\iocoder\springboot\lab55\mapstructdemo\dataobject\UserDO.java
| 1
|
请完成以下Java代码
|
public List<MilestoneInstance> findMilestoneInstancesByQueryCriteria(MilestoneInstanceQuery query) {
return dataManager.findMilestoneInstancesByQueryCriteria((MilestoneInstanceQueryImpl) query);
}
@Override
public long findMilestoneInstanceCountByQueryCriteria(MilestoneInstanceQuery query) {
return dataManager.findMilestoneInstancesCountByQueryCriteria((MilestoneInstanceQueryImpl) query);
}
@Override
public void updateMilestoneInstancesCaseDefinitionId(String caseInstanceId, String caseDefinitionId) {
MilestoneInstanceQuery milestoneQuery = new MilestoneInstanceQueryImpl()
.milestoneInstanceCaseInstanceId(caseInstanceId);
List<MilestoneInstance> milestoneInstances = findMilestoneInstancesByQueryCriteria(milestoneQuery);
if (milestoneInstances != null && !milestoneInstances.isEmpty()) {
for (MilestoneInstance milestoneInstance : milestoneInstances) {
MilestoneInstanceEntity milestoneInstanceEntity = (MilestoneInstanceEntity) milestoneInstance;
milestoneInstanceEntity.setCaseDefinitionId(caseDefinitionId);
update(milestoneInstanceEntity);
|
}
}
}
@Override
public void deleteByCaseDefinitionId(String caseDefinitionId) {
dataManager.deleteByCaseDefinitionId(caseDefinitionId);
}
@Override
public void deleteByCaseInstanceId(String caseInstanceId) {
dataManager.deleteByCaseInstanceId(caseInstanceId);
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\MilestoneInstanceEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public static MessageBuilder withBody(byte[] body, int from, int to) {
Assert.notNull(body, BODY_CANNOT_BE_NULL);
return new MessageBuilder(Arrays.copyOfRange(body, from, to));
}
/**
* The final message body will be a direct reference to the message
* body, the MessageProperties will be a shallow copy.
* @param message The message.
* @return The builder.
*/
public static MessageBuilder fromMessage(Message message) {
Assert.notNull(message, MESSAGE_CANNOT_BE_NULL);
return new MessageBuilder(message);
}
/**
* The final message will have a copy of the message
* body, the MessageProperties will be cloned (top level only).
* @param message The message.
* @return The builder.
*/
public static MessageBuilder fromClonedMessage(Message message) {
Assert.notNull(message, MESSAGE_CANNOT_BE_NULL);
byte[] body = message.getBody();
Assert.notNull(body, BODY_CANNOT_BE_NULL);
return new MessageBuilder(Arrays.copyOf(body, body.length), message.getMessageProperties());
}
private MessageBuilder(byte[] body) { //NOSONAR
this.body = body;
}
private MessageBuilder(Message message) {
this(message.getBody(), message.getMessageProperties());
}
private MessageBuilder(byte[] body, MessageProperties properties) { //NOSONAR
|
this.body = body;
this.copyProperties(properties);
}
/**
* Makes this builder's properties builder use a reference to properties.
* @param properties The properties.
* @return this.
*/
public MessageBuilder andProperties(MessageProperties properties) {
this.setProperties(properties);
return this;
}
@Override
public Message build() {
return new Message(this.body, this.buildProperties());
}
}
|
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\MessageBuilder.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("name", name)
.add("executor", executor)
.toString();
}
@Override
public void shutdownExecutor()
{
shutdownLock.lock();
try
{
shutdown0();
}
finally
{
shutdownLock.unlock();
}
}
@Override
protected void executeTask(@NonNull final WorkpackageProcessorTask task)
{
logger.debug("Going to submit task={} to executor={}", task, executor);
executor.execute(task);
logger.debug("Done submitting task");
}
private void shutdown0()
{
logger.info("shutdown - Shutdown started for executor={}", executor);
executor.shutdown();
int retryCount = 5;
boolean terminated = false;
|
while (!terminated && retryCount > 0)
{
logger.info("shutdown - waiting for executor to be terminated; retries left={}; executor={}", retryCount, executor);
try
{
terminated = executor.awaitTermination(5 * 1000, TimeUnit.MICROSECONDS);
}
catch (final InterruptedException e)
{
logger.warn("Failed shutting down executor for " + name + ". Retry " + retryCount + " more times.");
terminated = false;
}
retryCount--;
}
executor.shutdownNow();
logger.info("Shutdown finished");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\ThreadPoolQueueProcessor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean deleteRole(String roleid) {
//1.删除角色和用户关系
sysRoleMapper.deleteRoleUserRelation(roleid);
//2.删除角色和权限关系
sysRoleMapper.deleteRolePermissionRelation(roleid);
//3.删除角色
this.removeById(roleid);
return true;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean deleteBatchRole(String[] roleIds) {
//1.删除角色和用户关系
sysUserMapper.deleteBathRoleUserRelation(roleIds);
//2.删除角色和权限关系
sysUserMapper.deleteBathRolePermissionRelation(roleIds);
//3.删除角色
this.removeByIds(Arrays.asList(roleIds));
return true;
|
}
@Override
public Long getRoleCountByTenantId(String id, Integer tenantId) {
return sysRoleMapper.getRoleCountByTenantId(id,tenantId);
}
@Override
public void checkAdminRoleRejectDel(String ids) {
LambdaQueryWrapper<SysRole> query = new LambdaQueryWrapper<>();
query.in(SysRole::getId,Arrays.asList(ids.split(SymbolConstant.COMMA)));
query.eq(SysRole::getRoleCode,"admin");
Long adminRoleCount = sysRoleMapper.selectCount(query);
if(adminRoleCount>0){
throw new JeecgBootException("admin角色,不允许删除!");
}
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysRoleServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getLocale() {
return locale;
}
public String getCaseDefinitionKey() {
return caseDefinitionKey;
}
public String getCaseDefinitionKeyLike() {
return caseDefinitionKeyLike;
}
public String getCaseDefinitionKeyLikeIgnoreCase() {
return caseDefinitionKeyLikeIgnoreCase;
}
public Collection<String> getCaseDefinitionKeys() {
return caseDefinitionKeys;
}
public boolean isWithLocalizationFallback() {
return withLocalizationFallback;
}
public List<HistoricTaskInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public List<List<String>> getSafeCandidateGroups() {
return safeCandidateGroups;
}
public void setSafeCandidateGroups(List<List<String>> safeCandidateGroups) {
|
this.safeCandidateGroups = safeCandidateGroups;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public Set<String> getScopeIds() {
return scopeIds;
}
public List<List<String>> getSafeScopeIds() {
return safeScopeIds;
}
public void setSafeScopeIds(List<List<String>> safeScopeIds) {
this.safeScopeIds = safeScopeIds;
}
}
|
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\HistoricTaskInstanceQueryImpl.java
| 2
|
请完成以下Java代码
|
public String forgetBreakInSwitch(String animal) {
String result;
switch (animal) {
case "DOG":
LOGGER.debug("domestic animal");
result = "domestic animal";
default:
LOGGER.debug("unknown animal");
result = "unknown animal";
}
return result;
|
}
public String constantCaseValue(String animal) {
String result = "";
final String dog = "DOG";
switch (animal) {
case dog:
result = "domestic animal";
}
return result;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-syntax\src\main\java\com\baeldung\switchstatement\SwitchStatement.java
| 1
|
请完成以下Java代码
|
public Collection<EventPayloadInstance> extractPayload(EventModel eventModel, JsonNode payload) {
return eventModel.getPayload().stream()
.filter(payloadDefinition -> payloadDefinition.isFullPayload() || payload.has(payloadDefinition.getName()))
.map(payloadDefinition -> new EventPayloadInstanceImpl(payloadDefinition, getPayloadValue(payload,
payloadDefinition.getName(), payloadDefinition.getType(), payloadDefinition.isFullPayload())))
.collect(Collectors.toList());
}
protected Object getPayloadValue(JsonNode event, String definitionName, String definitionType, boolean isFullPayload) {
if (isFullPayload) {
return event;
}
JsonNode parameterNode = event.get(definitionName);
Object value = null;
if (EventPayloadTypes.STRING.equals(definitionType)) {
value = parameterNode.asString();
} else if (EventPayloadTypes.BOOLEAN.equals(definitionType)) {
value = parameterNode.booleanValue(false);
} else if (EventPayloadTypes.INTEGER.equals(definitionType)) {
|
value = parameterNode.intValue(0);
} else if (EventPayloadTypes.DOUBLE.equals(definitionType)) {
value = parameterNode.doubleValue(0.0d);
} else if (EventPayloadTypes.LONG.equals(definitionType)) {
value = parameterNode.longValue(0L);
} else if (EventPayloadTypes.JSON.equals(definitionType)) {
value = parameterNode;
} else {
LOGGER.warn("Unsupported payload type: {} ", definitionType);
value = parameterNode.asString();
}
return value;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\payload\JsonFieldToMapPayloadExtractor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getHandleValue() {
return handleValue;
}
public void setHandleValue(String handleValue) {
this.handleValue = handleValue == null ? null : handleValue.trim();
}
public String getHandleRemark() {
return handleRemark;
}
public void setHandleRemark(String handleRemark) {
this.handleRemark = handleRemark == null ? null : handleRemark.trim();
}
|
public String getOperatorName() {
return operatorName;
}
public void setOperatorName(String operatorName) {
this.operatorName = operatorName == null ? null : operatorName.trim();
}
public String getOperatorAccountNo() {
return operatorAccountNo;
}
public void setOperatorAccountNo(String operatorAccountNo) {
this.operatorAccountNo = operatorAccountNo == null ? null : operatorAccountNo.trim();
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\entity\RpAccountCheckMistake.java
| 2
|
请完成以下Java代码
|
class AllocableHU
{
private final IHUStorageFactory storageFactory;
private final QuantityUOMConverter uomConverter;
@Getter
@NonNull private final I_M_HU topLevelHU;
@Getter
@NonNull private final ProductId productId;
@Getter
@NonNull private final LocatorId locatorId;
private Quantity _storageQtyInHuUom; // lazy
private Quantity qtyAllocatedInHuUom;
public AllocableHU(
@NonNull final IHUStorageFactory storageFactory,
@NonNull final QuantityUOMConverter uomConverter,
@NonNull final I_M_HU topLevelHU,
@NonNull final ProductId productId)
{
this.storageFactory = storageFactory;
this.uomConverter = uomConverter;
this.topLevelHU = topLevelHU;
this.productId = productId;
this.locatorId = IHandlingUnitsBL.extractLocatorId(topLevelHU);
}
public HuId getHuId() {return HuId.ofRepoId(getTopLevelHU().getM_HU_ID());}
public Quantity getQtyAvailableToAllocate(final UomId uomId)
{
return uomConverter.convertQuantityTo(getQtyAvailableToAllocateInHuUom(), productId, uomId);
}
public Quantity getQtyAvailableToAllocateInHuUom()
{
final Quantity qtyStorageInHuUom = getStorageQtyInHuUom();
return qtyAllocatedInHuUom != null
? qtyStorageInHuUom.subtract(qtyAllocatedInHuUom)
: qtyStorageInHuUom;
}
private Quantity getStorageQtyInHuUom()
{
Quantity storageQtyInHuUom = this._storageQtyInHuUom;
if (storageQtyInHuUom == null)
{
|
storageQtyInHuUom = this._storageQtyInHuUom = storageFactory.getStorage(topLevelHU).getProductStorage(productId).getQty();
}
return storageQtyInHuUom;
}
public void addQtyAllocated(@NonNull final Quantity qtyAllocatedToAdd0)
{
final Quantity storageQtyInHuUom = getStorageQtyInHuUom();
final Quantity qtyAllocatedToAddInHuUom = uomConverter.convertQuantityTo(qtyAllocatedToAdd0, productId, storageQtyInHuUom.getUomId());
final Quantity newQtyAllocatedInHuUom = this.qtyAllocatedInHuUom != null
? this.qtyAllocatedInHuUom.add(qtyAllocatedToAddInHuUom)
: qtyAllocatedToAddInHuUom;
if (newQtyAllocatedInHuUom.isGreaterThan(storageQtyInHuUom))
{
throw new AdempiereException("Over-allocating is not allowed")
.appendParametersToMessage()
.setParameter("this.qtyAllocated", this.qtyAllocatedInHuUom)
.setParameter("newQtyAllocated", newQtyAllocatedInHuUom)
.setParameter("storageQty", storageQtyInHuUom);
}
this.qtyAllocatedInHuUom = newQtyAllocatedInHuUom;
}
public boolean hasQtyAvailable()
{
return getQtyAvailableToAllocateInHuUom().signum() > 0;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\manufacturing\issue\plan\AllocableHU.java
| 1
|
请完成以下Java代码
|
public caption removeElement (String hashcode)
{
removeElementFromRegistry (hashcode);
return (this);
}
/**
* The onclick event occurs when the pointing device button is clicked over
* an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnClick (String script)
{
addAttribute ("onclick", script);
}
/**
* The ondblclick event occurs when the pointing device button is double
* clicked over an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnDblClick (String script)
{
addAttribute ("ondblclick", script);
}
/**
* The onmousedown event occurs when the pointing device button is pressed
* over an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseDown (String script)
{
addAttribute ("onmousedown", script);
}
/**
* The onmouseup event occurs when the pointing device button is released
* over an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseUp (String script)
{
addAttribute ("onmouseup", script);
}
/**
* The onmouseover event occurs when the pointing device is moved onto an
* element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseOver (String script)
{
addAttribute ("onmouseover", script);
}
/**
* The onmousemove event occurs when the pointing device is moved while it
|
* is over an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseMove (String script)
{
addAttribute ("onmousemove", script);
}
/**
* The onmouseout event occurs when the pointing device is moved away from
* an element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnMouseOut (String script)
{
addAttribute ("onmouseout", script);
}
/**
* The onkeypress event occurs when a key is pressed and released over an
* element. This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnKeyPress (String script)
{
addAttribute ("onkeypress", script);
}
/**
* The onkeydown event occurs when a key is pressed down over an element.
* This attribute may be used with most elements.
*
* @param script The script
*/
public void setOnKeyDown (String script)
{
addAttribute ("onkeydown", script);
}
/**
* The onkeyup event occurs when a key is released over an element. This
* attribute may be used with most elements.
*
* @param script The script
*/
public void setOnKeyUp (String script)
{
addAttribute ("onkeyup", script);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\caption.java
| 1
|
请完成以下Java代码
|
public static void addFieldToExistingBsonFilter() {
Bson existingFilter = and(eq("type", "Dog"), eq("gender", "Male"));
Bson newFilter = and(existingFilter, gt("age", 5));
FindIterable<Document> documents = collection.find(newFilter);
MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
public static void addFieldToExistingBsonFilterUsingBsonDocument() {
Bson existingFilter = eq("type", "Dog");
BsonDocument existingBsonDocument = existingFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
Bson newFilter = gt("age", 5);
BsonDocument newBsonDocument = newFilter.toBsonDocument(BsonDocument.class, MongoClient.getDefaultCodecRegistry());
existingBsonDocument.append("age", newBsonDocument.get("age"));
FindIterable<Document> documents = collection.find(existingBsonDocument);
|
MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
public static void main(String args[]) {
setUp();
addFieldToExistingBsonFilter();
addFieldToExistingBsonFilterUsingBsonDocument();
}
}
|
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\insert\InsertFieldIntoFilter.java
| 1
|
请完成以下Java代码
|
final public boolean isValidRecordForImport(@NonNull final I_I_Replenish importRecord)
{
return (importRecord.getM_Product_ID() > 0)
&& (importRecord.getM_Warehouse_ID() > 0)
&& (importRecord.getLevel_Max() != null)
&& (importRecord.getLevel_Min() != null)
&& (!Check.isEmpty(importRecord.getReplenishType(), true));
}
final public I_M_Replenish createNewReplenish(@NonNull final I_I_Replenish importRecord)
{
final I_M_Replenish replenish = InterfaceWrapperHelper.newInstance(I_M_Replenish.class, importRecord);
setReplenishmenttValueFields(importRecord, replenish);
return replenish;
}
final public I_M_Replenish uppdateReplenish(@NonNull final I_I_Replenish importRecord)
{
final I_M_Replenish replenish = importRecord.getM_Replenish();
setReplenishmenttValueFields(importRecord, replenish);
return replenish;
}
private void setReplenishmenttValueFields(@NonNull final I_I_Replenish importRecord, @NonNull final I_M_Replenish replenish)
{
// mandatory fields
replenish.setAD_Org_ID(importRecord.getAD_Org_ID());
|
replenish.setM_Product_ID(importRecord.getM_Product_ID());
replenish.setM_Warehouse_ID(importRecord.getM_Warehouse_ID());
replenish.setLevel_Max(importRecord.getLevel_Max());
replenish.setLevel_Min(importRecord.getLevel_Min());
replenish.setReplenishType(importRecord.getReplenishType());
replenish.setTimeToMarket(importRecord.getTimeToMarket());
// optional fields
if (importRecord.getM_Locator_ID() > 0)
{
replenish.setM_Locator_ID(importRecord.getM_Locator_ID());
}
if (importRecord.getC_Period_ID() > 0)
{
replenish.setC_Period_ID(importRecord.getC_Period_ID());
replenish.setC_Calendar_ID(getCalendar(importRecord.getC_Period()));
}
}
private int getCalendar(final I_C_Period period)
{
return period.getC_Year().getC_Calendar_ID();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\replenishment\impexp\ReplenishImportHelper.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JwtSecurityConfiguration {
@Bean
SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(
auth -> {
auth.anyRequest().authenticated();
});
http.sessionManagement(
session ->
session.sessionCreationPolicy(
SessionCreationPolicy.STATELESS)
);
http.httpBasic(withDefaults());
http.csrf(csrf -> csrf.disable());
http.headers(headers -> headers.frameOptions(frameOptionsConfig-> frameOptionsConfig.disable()));
http.oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()));
return http.build();
}
@Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder()
.setType(EmbeddedDatabaseType.H2)
.addScript(JdbcDaoImpl.DEFAULT_USER_SCHEMA_DDL_LOCATION)
.build();
}
@Bean
public UserDetailsService userDetailService(DataSource dataSource) {
var user = User.withUsername("in28minutes")
//.password("{noop}dummy")
.password("dummy")
.passwordEncoder(str -> passwordEncoder().encode(str))
.roles("USER")
.build();
var admin = User.withUsername("admin")
//.password("{noop}dummy")
.password("dummy")
.passwordEncoder(str -> passwordEncoder().encode(str))
.roles("ADMIN", "USER")
.build();
var jdbcUserDetailsManager = new JdbcUserDetailsManager(dataSource);
jdbcUserDetailsManager.createUser(user);
jdbcUserDetailsManager.createUser(admin);
return jdbcUserDetailsManager;
}
|
@Bean
public BCryptPasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
@Bean
public KeyPair keyPair() {
try {
var keyPairGenerator = KeyPairGenerator.getInstance("RSA");
keyPairGenerator.initialize(2048);
return keyPairGenerator.generateKeyPair();
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
@Bean
public RSAKey rsaKey(KeyPair keyPair) {
return new RSAKey
.Builder((RSAPublicKey)keyPair.getPublic())
.privateKey(keyPair.getPrivate())
.keyID(UUID.randomUUID().toString())
.build();
}
@Bean
public JWKSource<SecurityContext> jwkSource(RSAKey rsaKey) {
var jwkSet = new JWKSet(rsaKey);
return (jwkSelector, context) -> jwkSelector.select(jwkSet);
}
@Bean
public JwtDecoder jwtDecoder(RSAKey rsaKey) throws JOSEException {
return NimbusJwtDecoder
.withPublicKey(rsaKey.toRSAPublicKey())
.build();
}
@Bean
public JwtEncoder jwtEncoder(JWKSource<SecurityContext> jwkSource) {
return new NimbusJwtEncoder(jwkSource);
}
}
|
repos\master-spring-and-spring-boot-main\71-spring-security\src\main\java\com\in28minutes\learnspringsecurity\jwt\JwtSecurityConfiguration.java
| 2
|
请完成以下Spring Boot application配置
|
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
hikari:
pool-name: hikari-pool
url: jdbc:mysql://localhost:3306/baeldung?verifyServerCertificate=false&useSSL=false&requireSSL=false
username: root
jpa:
|
hibernate:
ddl-auto: create
properties:
globally_quoted_identifiers: true
|
repos\tutorials-master\persistence-modules\spring-data-rest-querydsl\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public void after(JoinPoint joinPoint) {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 after:" + log.value());
}
@AfterReturning(value = "pointCutMethod() || pointCutType()", returning = "result")
public void afterReturning(JoinPoint joinPoint, Object result) {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 afterReturning:" + log.value() + ":::" + JSON.toJSONString(result));
}
@AfterThrowing(value = "pointCutMethod() || pointCutType()", throwing = "t")
public void afterThrowing(JoinPoint joinPoint, Throwable t) {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 afterThrowing:" + log.value() + ":::" + JSON.toJSONString(t.getStackTrace()));
|
}
// @Around(value = "pointCutMethod() || pointCutType()")
public Object around(ProceedingJoinPoint joinPoint) throws Throwable {
// 通过反射可以获得注解上的属性,然后做日志记录相关的操作
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
Log log = method.getAnnotation(Log.class);
System.out.println("日志切面 Around before:" + log.value() + ":::" + JSON.toJSONString(joinPoint.getArgs()));
Object result = joinPoint.proceed();
System.out.println("日志切面 Around after:" + log.value() + ":::" + JSON.toJSONString(result));
return result;
}
}
|
repos\spring-boot-student-master\spring-boot-student-spring\src\main\java\com\xiaolyuh\aop\aspect\LogAspect.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonResponseSalesRepContact
{
public static final String SALES_REP_VALUE = "salesRepValue";
public static final String SALES_REP_ID = "salesRepId";
public static final String SALES_REP_PHONE = "salesRepPhone";
public static final String SALES_REP_EMAIL = "salesRepEmail";
public static final String SALES_REP_LASTNAME = "salesRepLastName";
public static final String SALES_REP_FIRSTNAME = "salesRepFirstName";
public static final String SALES_REP_NAME = "salesRepName";
@ApiModelProperty(required = true, value = "This translates to `AD_User.AD_User_ID`.")
@JsonProperty(SALES_REP_ID)
JsonMetasfreshId salesRepId;
@ApiModelProperty(required = true, value = "This translates to `AD_User.Value`.")
@JsonProperty(SALES_REP_VALUE)
String salesRepValue;
@ApiModelProperty(required = true, value = "This translates to `AD_User.Phone`.")
@JsonProperty(SALES_REP_PHONE)
String phone;
@ApiModelProperty(required = true, value = "This translates to `AD_User.Email`.")
@JsonProperty(SALES_REP_EMAIL)
String email;
@ApiModelProperty(required = true, value = "This translates to `AD_User.LastName`.")
@JsonProperty(SALES_REP_LASTNAME)
String lastName;
@ApiModelProperty(required = true, value = "This translates to `AD_User.FirstName`.")
@JsonProperty(SALES_REP_FIRSTNAME)
String firstName;
@ApiModelProperty(required = true, value = "This translates to `AD_User.Name`.")
@JsonProperty(SALES_REP_NAME)
String name;
|
@JsonCreator
@Builder
private JsonResponseSalesRepContact(
@JsonProperty(SALES_REP_ID) @NonNull final JsonMetasfreshId salesRepId,
@JsonProperty(SALES_REP_VALUE) @Nullable final String salesRepValue,
@JsonProperty(SALES_REP_LASTNAME) @Nullable final String lastName,
@JsonProperty(SALES_REP_FIRSTNAME) @Nullable final String firstName,
@JsonProperty(SALES_REP_NAME) @Nullable final String name,
@JsonProperty(SALES_REP_EMAIL) @Nullable final String email,
@JsonProperty(SALES_REP_PHONE) @Nullable final String phone)
{
this.salesRepId = salesRepId;
this.salesRepValue = salesRepValue;
this.lastName = lastName;
this.firstName = firstName;
this.name = name;
this.email = email;
this.phone = phone;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v2\response\JsonResponseSalesRepContact.java
| 2
|
请完成以下Java代码
|
protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("CM_WebProject_ID"))
p_CM_WebProject_ID = ((BigDecimal)para[i].getParameter()).intValue();
else
log.error("Unknown Parameter: " + name);
}
} // prepare
/**
* Perform process.
* @return Message (clear text)
* @throws Exception if not successful
*/
protected String doIt() throws Exception
{
// ReIndex Container
|
int[] containers = MContainer.getAllIDs("CM_Container","CM_WebProject_ID=" + p_CM_WebProject_ID, get_TrxName());
for(int i=0;i<containers.length;i++)
{
MContainer thisContainer = new MContainer(getCtx(),containers[i], get_TrxName());
thisContainer.reIndex(false);
}
// ReIndex News
int[] newsChannels = MNewsChannel.getAllIDs("CM_NewsChannel","CM_WebProject_ID=" + p_CM_WebProject_ID, get_TrxName());
for (int i=0;i<newsChannels.length;i++)
{
MNewsChannel thisChannel = new MNewsChannel(getCtx(),newsChannels[i], get_TrxName());
thisChannel.reIndex(false);
int[] newsItems = MNewsItem.getAllIDs("CM_NewsItem","CM_NewsChannel_ID=" + newsChannels[i], get_TrxName());
for (int k=0;k<newsItems.length;k++)
{
MNewsItem thisItem = new MNewsItem(getCtx(), newsItems[k], get_TrxName());
thisItem.reIndex(false);
}
}
return "finished...";
} // doIt
} // KIndexRerun
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\KIndexRerun.java
| 1
|
请完成以下Java代码
|
public final class KafkaStreamBrancher<K, V> {
private final List<Predicate<? super K, ? super V>> predicateList = new ArrayList<>();
private final List<Consumer<? super KStream<K, V>>> consumerList = new ArrayList<>();
private @Nullable Consumer<? super KStream<K, V>> defaultConsumer;
/**
* Defines a new branch.
* @param predicate {@link Predicate} instance
* @param consumer The consumer of this branch's {@code KStream}
* @return {@code this}
*/
public KafkaStreamBrancher<K, V> branch(Predicate<? super K, ? super V> predicate,
Consumer<? super KStream<K, V>> consumer) {
this.predicateList.add(Objects.requireNonNull(predicate));
this.consumerList.add(Objects.requireNonNull(consumer));
return this;
}
/**
* Defines a default branch. All the messages that were not dispatched to other branches will be directed
* to this stream. This method should not necessarily be called in the end
* of chain.
* @param consumer The consumer of this branch's {@code KStream}
* @return {@code this}
*/
public KafkaStreamBrancher<K, V> defaultBranch(Consumer<? super KStream<K, V>> consumer) {
this.defaultConsumer = Objects.requireNonNull(consumer);
return this;
}
/**
* Terminating method that builds branches on top of given {@code KStream}.
* Applies each predicate-consumer pair sequentially to create branches.
* If a default consumer exists, it will handle all records that don't match any predicates.
* @param stream {@code KStream} to split
* @return the processed stream
* @throws NullPointerException if stream is null
* @throws IllegalStateException if number of predicates doesn't match number of consumers
|
*/
public KStream<K, V> onTopOf(KStream<K, V> stream) {
if (this.defaultConsumer != null) {
this.predicateList.add((k, v) -> true);
this.consumerList.add(this.defaultConsumer);
}
// Validate predicate and consumer lists match
if (this.predicateList.size() != this.consumerList.size()) {
throw new IllegalStateException("Number of predicates (" + this.predicateList.size() +
") must match number of consumers (" + this.consumerList.size() + ")");
}
BranchedKStream<K, V> branchedKStream = stream.split();
Iterator<Consumer<? super KStream<K, V>>> consumerIterator = this.consumerList.iterator();
// Process each predicate-consumer pair
for (Predicate<? super K, ? super V> predicate : this.predicateList) {
branchedKStream = branchedKStream.branch(predicate,
Branched.withConsumer(adaptConsumer(consumerIterator.next())));
}
return stream;
}
private Consumer<KStream<K, V>> adaptConsumer(Consumer<? super KStream<K, V>> consumer) {
return consumer::accept;
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\KafkaStreamBrancher.java
| 1
|
请完成以下Java代码
|
private static class ReaderThread extends Thread {
private final InputStream source;
private final @Nullable Consumer<String> outputConsumer;
private final StringBuilder output = new StringBuilder();
private final CountDownLatch latch = new CountDownLatch(1);
ReaderThread(InputStream source, String name, @Nullable Consumer<String> outputConsumer) {
this.source = source;
this.outputConsumer = outputConsumer;
setName("OutputReader-" + name);
setDaemon(true);
start();
}
@Override
public void run() {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(this.source, StandardCharsets.UTF_8))) {
String line = reader.readLine();
while (line != null) {
this.output.append(line);
this.output.append("\n");
if (this.outputConsumer != null) {
this.outputConsumer.accept(line);
}
line = reader.readLine();
}
this.latch.countDown();
}
catch (IOException ex) {
throw new UncheckedIOException("Failed to read process stream", ex);
}
|
}
@Override
public String toString() {
try {
this.latch.await();
return this.output.toString();
}
catch (InterruptedException ex) {
return "";
}
}
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\ProcessRunner.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Post {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String title;
private String url;
private String date;
private String redditID;
private Date submissionDate;
private boolean sent;
private String userName;
public Post() {
}
public boolean isSent() {
return sent;
}
public void setSent(boolean sent) {
this.sent = sent;
}
public String getRedditID() {
return redditID;
}
public void setRedditID(String redditID) {
this.redditID = redditID;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
|
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public Date getSubmissionDate() {
return submissionDate;
}
public void setSubmissionDate(Date submissionDate) {
this.submissionDate = submissionDate;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
|
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\springpagination\model\Post.java
| 2
|
请完成以下Java代码
|
public class NumberAndSumOfTransactions2 {
@XmlElement(name = "NbOfNtries")
protected String nbOfNtries;
@XmlElement(name = "Sum")
protected BigDecimal sum;
@XmlElement(name = "TtlNetNtryAmt")
protected BigDecimal ttlNetNtryAmt;
@XmlElement(name = "CdtDbtInd")
@XmlSchemaType(name = "string")
protected CreditDebitCode cdtDbtInd;
/**
* Gets the value of the nbOfNtries property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNbOfNtries() {
return nbOfNtries;
}
/**
* Sets the value of the nbOfNtries property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNbOfNtries(String value) {
this.nbOfNtries = value;
}
/**
* Gets the value of the sum property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getSum() {
return sum;
}
/**
* Sets the value of the sum property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setSum(BigDecimal value) {
this.sum = value;
}
/**
* Gets the value of the ttlNetNtryAmt property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
|
public BigDecimal getTtlNetNtryAmt() {
return ttlNetNtryAmt;
}
/**
* Sets the value of the ttlNetNtryAmt property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setTtlNetNtryAmt(BigDecimal value) {
this.ttlNetNtryAmt = value;
}
/**
* Gets the value of the cdtDbtInd property.
*
* @return
* possible object is
* {@link CreditDebitCode }
*
*/
public CreditDebitCode getCdtDbtInd() {
return cdtDbtInd;
}
/**
* Sets the value of the cdtDbtInd property.
*
* @param value
* allowed object is
* {@link CreditDebitCode }
*
*/
public void setCdtDbtInd(CreditDebitCode value) {
this.cdtDbtInd = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\NumberAndSumOfTransactions2.java
| 1
|
请完成以下Java代码
|
public void setMode(Mode mode) {
this.delegate = createDelegate(mode);
}
/**
* The X-Frame-Options values. There is no support for ALLOW-FROM because not <a href=
* "https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-Frame-Options">all
* browsers support it</a>. Consider using X-Frame-Options with
* Content-Security-Policy <a href=
* "https://w3c.github.io/webappsec/specs/content-security-policy/#directive-frame-ancestors">frame-ancestors</a>.
*
* @author Rob Winch
* @since 5.0
*/
public enum Mode {
/**
* A browser receiving content with this header field MUST NOT display this
* content in any frame.
*/
|
DENY,
/**
* A browser receiving content with this header field MUST NOT display this
* content in any frame from a page of different origin than the content itself.
*
* If a browser or plugin cannot reliably determine whether or not the origin of
* the content and the frame are the same, this MUST be treated as "DENY".
*/
SAMEORIGIN
}
private static ServerHttpHeadersWriter createDelegate(Mode mode) {
Builder builder = StaticServerHttpHeadersWriter.builder();
builder.header(X_FRAME_OPTIONS, mode.name());
return builder.build();
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\header\XFrameOptionsServerHttpHeadersWriter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getKey() {
return key;
}
public String getKeyLike() {
return keyLike;
}
public String getResourceName() {
return resourceName;
}
public String getResourceNameLike() {
return resourceNameLike;
}
public Integer getVersion() {
return version;
}
|
public String getVersionTag() {
return versionTag;
}
public String getVersionTagLike() {
return versionTagLike;
}
public boolean isLatest() {
return latest;
}
public boolean isShouldJoinDeploymentTable() {
return shouldJoinDeploymentTable;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\entity\repository\DecisionDefinitionQueryImpl.java
| 2
|
请完成以下Java代码
|
public boolean hasChangesToApply()
{
return !linesToAddGroupedByAcctSchemaId.isEmpty()
|| !linesToChangeByKey.isEmpty()
|| !linesToRemoveByKey.isEmpty();
}
public void applyTo(final ArrayList<Fact> facts)
{
if (!hasChangesToApply())
{
return;
}
facts.forEach(this::applyTo);
}
public void applyTo(final Fact fact)
{
if (!hasChangesToApply())
{
return;
}
applyUpdatesTo(fact);
addLinesTo(fact);
}
public void applyUpdatesTo(final Fact fact)
{
fact.mapEachLine(this::applyTo);
}
private FactLine applyTo(@NonNull final FactLine factLine)
{
final FactLineMatchKey matchKey = FactLineMatchKey.ofFactLine(factLine);
//
// Remove line
final FactAcctChanges remove = linesToRemoveByKey.remove(matchKey);
if (remove != null)
{
return null; // consider line removed
}
//
// Change line
else
{
final FactAcctChanges change = linesToChangeByKey.remove(matchKey);
if (change != null)
{
|
factLine.updateFrom(change);
}
return factLine;
}
}
private void addLinesTo(@NonNull final Fact fact)
{
final AcctSchemaId acctSchemaId = fact.getAcctSchemaId();
final List<FactAcctChanges> additions = linesToAddGroupedByAcctSchemaId.removeAll(acctSchemaId);
additions.forEach(addition -> addLine(fact, addition));
}
public void addLine(@NonNull final Fact fact, @NonNull final FactAcctChanges changesToAdd)
{
if (!changesToAdd.getType().isAdd())
{
throw new AdempiereException("Expected type `Add` but it was " + changesToAdd);
}
final FactLine factLine = fact.createLine()
.alsoAddZeroLine()
.setAccount(changesToAdd.getAccountIdNotNull())
.setAmtSource(changesToAdd.getAmtSourceDr(), changesToAdd.getAmtSourceCr())
.setAmtAcct(changesToAdd.getAmtAcctDr(), changesToAdd.getAmtAcctCr())
.setC_Tax_ID(changesToAdd.getTaxId())
.description(changesToAdd.getDescription())
.productId(changesToAdd.getProductId())
.userElementString1(changesToAdd.getUserElementString1())
.salesOrderId(changesToAdd.getSalesOrderId())
.activityId(changesToAdd.getActivityId())
.buildAndAdd();
if (factLine != null)
{
factLine.updateFrom(changesToAdd); // just to have appliedUserChanges set
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\factacct_userchanges\FactAcctChangesApplier.java
| 1
|
请完成以下Java代码
|
public class JcaExecutorServiceManagedConnectionFactory implements ManagedConnectionFactory, ResourceAdapterAssociation {
private static final long serialVersionUID = 1L;
protected ResourceAdapter ra;
protected PrintWriter logwriter;
public JcaExecutorServiceManagedConnectionFactory() {
}
public Object createConnectionFactory(ConnectionManager cxManager) throws ResourceException {
return new JcaExecutorServiceConnectionFactoryImpl(this, cxManager);
}
public Object createConnectionFactory() throws ResourceException {
throw new ResourceException("This resource adapter doesn't support non-managed environments");
}
public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
return new JcaExecutorServiceManagedConnection(this);
}
@SuppressWarnings("rawtypes")
public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
ManagedConnection result = null;
Iterator it = connectionSet.iterator();
while (result == null && it.hasNext()) {
ManagedConnection mc = (ManagedConnection) it.next();
if (mc instanceof JcaExecutorServiceManagedConnection) {
result = mc;
}
}
return result;
}
public PrintWriter getLogWriter() throws ResourceException {
return logwriter;
|
}
public void setLogWriter(PrintWriter out) throws ResourceException {
logwriter = out;
}
public ResourceAdapter getResourceAdapter() {
return ra;
}
public void setResourceAdapter(ResourceAdapter ra) {
this.ra = ra;
}
@Override
public int hashCode() {
return 31;
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other == this)
return true;
if (!(other instanceof JcaExecutorServiceManagedConnectionFactory))
return false;
return true;
}
}
|
repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\outbound\JcaExecutorServiceManagedConnectionFactory.java
| 1
|
请完成以下Java代码
|
public static class Scripts implements Iterable<Resource> {
private final List<Resource> resources;
private boolean continueOnError;
private String separator = ";";
private @Nullable Charset encoding;
public Scripts(List<Resource> resources) {
this.resources = resources;
}
@Override
public Iterator<Resource> iterator() {
return this.resources.iterator();
}
public Scripts continueOnError(boolean continueOnError) {
this.continueOnError = continueOnError;
return this;
}
public boolean isContinueOnError() {
return this.continueOnError;
|
}
public Scripts separator(String separator) {
this.separator = separator;
return this;
}
public String getSeparator() {
return this.separator;
}
public Scripts encoding(@Nullable Charset encoding) {
this.encoding = encoding;
return this;
}
public @Nullable Charset getEncoding() {
return this.encoding;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\init\AbstractScriptDatabaseInitializer.java
| 1
|
请完成以下Java代码
|
public org.compiere.model.I_M_MovementLine getReversalLine() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_MovementLine.class);
}
@Override
public void setReversalLine(org.compiere.model.I_M_MovementLine ReversalLine)
{
set_ValueFromPO(COLUMNNAME_ReversalLine_ID, org.compiere.model.I_M_MovementLine.class, ReversalLine);
}
/** Set Reversal Line.
@param ReversalLine_ID
Use to keep the reversal line ID for reversing costing purpose
*/
@Override
public void setReversalLine_ID (int ReversalLine_ID)
{
if (ReversalLine_ID < 1)
set_Value (COLUMNNAME_ReversalLine_ID, null);
else
set_Value (COLUMNNAME_ReversalLine_ID, Integer.valueOf(ReversalLine_ID));
}
/** Get Reversal Line.
@return Use to keep the reversal line ID for reversing costing purpose
*/
@Override
public int getReversalLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ReversalLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verworfene Menge.
@param ScrappedQty
The Quantity scrapped due to QA issues
*/
@Override
public void setScrappedQty (java.math.BigDecimal ScrappedQty)
{
set_Value (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Verworfene Menge.
@return The Quantity scrapped due to QA issues
*/
@Override
public java.math.BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Zielmenge.
@param TargetQty
Target Movement Quantity
*/
@Override
public void setTargetQty (java.math.BigDecimal TargetQty)
{
|
set_Value (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Zielmenge.
@return Target Movement Quantity
*/
@Override
public java.math.BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
throw new IllegalArgumentException ("Value is virtual column"); }
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementLine.java
| 1
|
请完成以下Java代码
|
public JsonStructure update(String key, String newValue) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
JsonString jsonNewValue = Json.createValue(newValue);
jsonStructure = jsonPointer.replace(jsonStructure, jsonNewValue);
return jsonStructure;
}
public JsonStructure delete(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
jsonPointer.getValue(jsonStructure);
jsonStructure = jsonPointer.remove(jsonStructure);
return jsonStructure;
}
public String fetchValueFromKey(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
JsonString jsonString = (JsonString) jsonPointer.getValue(jsonStructure);
return jsonString.getString();
}
|
public String fetchListValues(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure);
return jsonObject.toString();
}
public String fetchFullJSON() {
JsonPointer jsonPointer = Json.createPointer("");
JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure);
return jsonObject.toString();
}
public boolean check(String key) {
JsonPointer jsonPointer = Json.createPointer("/" + key);
boolean found = jsonPointer.containsValue(jsonStructure);
return found;
}
}
|
repos\tutorials-master\json-modules\json\src\main\java\com\baeldung\jsonpointer\JsonPointerCrud.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class CompositeHandlerAdapter implements HandlerAdapter {
private final ListableBeanFactory beanFactory;
private @Nullable List<HandlerAdapter> adapters;
CompositeHandlerAdapter(ListableBeanFactory beanFactory) {
this.beanFactory = beanFactory;
}
@Override
public boolean supports(Object handler) {
return getAdapter(handler).isPresent();
}
@Override
public @Nullable ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
Optional<HandlerAdapter> adapter = getAdapter(handler);
if (adapter.isPresent()) {
|
return adapter.get().handle(request, response, handler);
}
return null;
}
private Optional<HandlerAdapter> getAdapter(Object handler) {
if (this.adapters == null) {
this.adapters = extractAdapters();
}
return this.adapters.stream().filter((a) -> a.supports(handler)).findFirst();
}
private List<HandlerAdapter> extractAdapters() {
List<HandlerAdapter> list = new ArrayList<>(this.beanFactory.getBeansOfType(HandlerAdapter.class).values());
list.remove(this);
AnnotationAwareOrderComparator.sort(list);
return list;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-webmvc\src\main\java\org\springframework\boot\webmvc\autoconfigure\actuate\web\CompositeHandlerAdapter.java
| 2
|
请完成以下Java代码
|
public int getAD_Task_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Task_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Server Process.
@param IsServerProcess
Run this Process on Server only
*/
public void setIsServerProcess (boolean IsServerProcess)
{
set_Value (COLUMNNAME_IsServerProcess, Boolean.valueOf(IsServerProcess));
}
/** Get Server Process.
@return Run this Process on Server only
*/
public boolean isServerProcess ()
{
Object oo = get_Value(COLUMNNAME_IsServerProcess);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
|
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set OS Command.
@param OS_Command
Operating System Command
*/
public void setOS_Command (String OS_Command)
{
set_Value (COLUMNNAME_OS_Command, OS_Command);
}
/** Get OS Command.
@return Operating System Command
*/
public String getOS_Command ()
{
return (String)get_Value(COLUMNNAME_OS_Command);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Task.java
| 1
|
请完成以下Java代码
|
protected static ImageIcon loadIcon(String iconFile) {
try {
return new ImageIcon(DefaultCheckboxTreeCellRenderer.class.getClassLoader().getResource(iconFile));
} catch (NullPointerException npe) { // did not find the resource
return null;
}
}
@Override
public void setBackground(Color color) {
if (color instanceof ColorUIResource) {
color = null;
}
super.setBackground(color);
}
/**
* Sets the icon used to represent non-leaf nodes that are expanded.
*/
public void setOpenIcon(Icon newIcon) {
this.label.setOpenIcon(newIcon);
|
}
/**
* Sets the icon used to represent non-leaf nodes that are not expanded.
*/
public void setClosedIcon(Icon newIcon) {
this.label.setClosedIcon(newIcon);
}
/**
* Sets the icon used to represent leaf nodes.
*/
public void setLeafIcon(Icon newIcon) {
this.label.setLeafIcon(newIcon);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\DefaultCheckboxTreeCellRenderer.java
| 1
|
请完成以下Java代码
|
private LookupTaxCategoryRequest createLookupTaxCategoryRequest(@NonNull final I_M_ProductPrice productPrice)
{
final ProductId productId = ProductId.ofRepoId(productPrice.getM_Product_ID());
final PriceListVersionId priceListVersionId = PriceListVersionId.ofRepoId(productPrice.getM_PriceList_Version_ID());
final I_M_PriceList_Version priceListVersionRecord = priceListDAO.getPriceListVersionById(priceListVersionId);
final I_M_PriceList priceListRecord = priceListDAO.getById(priceListVersionRecord.getM_PriceList_ID());
return LookupTaxCategoryRequest.builder()
.productId(productId)
.targetDate(TimeUtil.asInstant(priceListVersionRecord.getValidFrom()))
.countryId(CountryId.ofRepoIdOrNull(priceListRecord.getC_Country_ID()))
.build();
}
@NonNull
public Optional<ProductTaxCategory> getProductTaxCategoryByUniqueKey(
@NonNull final ProductId productId,
@NonNull final CountryId countryId)
|
{
return productTaxCategoryRepository.getProductTaxCategoryByUniqueKey(productId, countryId);
}
public void save(@NonNull final ProductTaxCategory request)
{
productTaxCategoryRepository.save(request);
}
@NonNull
public ProductTaxCategory createProductTaxCategory(@NonNull final CreateProductTaxCategoryRequest createProductTaxCategoryRequest)
{
return productTaxCategoryRepository.createProductTaxCategory(createProductTaxCategoryRequest);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\tax\ProductTaxCategoryService.java
| 1
|
请完成以下Java代码
|
protected class QueryTable {
//数据库名
private String dbName;
//表名
private String name;
//表的别名
private String alias;
// 字段名集合
private Set<String> fields;
// 是否查询所有字段
private boolean all;
public QueryTable() {
}
public QueryTable(String name, String alias) {
this.name = name;
this.alias = alias;
this.all = false;
this.fields = new HashSet<>();
}
public void addField(String field) {
this.fields.add(field);
}
public String getDbName() {
return dbName;
}
public void setDbName(String dbName) {
this.dbName = dbName;
}
public String getName() {
return name;
}
public Set<String> getFields() {
return new HashSet<>(fields);
}
public void setName(String name) {
this.name = name;
}
public void setFields(Set<String> fields) {
this.fields = fields;
}
public String getAlias() {
return alias;
}
public void setAlias(String alias) {
this.alias = alias;
}
public boolean isAll() {
return all;
}
public void setAll(boolean all) {
this.all = all;
}
/**
* 判断是否有相同字段
*
* @param fieldString
* @return
*/
public boolean existSameField(String fieldString) {
String[] controlFields = fieldString.split(",");
for (String sqlField : fields) {
for (String controlField : controlFields) {
if (sqlField.equals(controlField)) {
// 非常明确的列直接比较
log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询");
|
return true;
} else {
// 使用表达式的列 只能判读字符串包含了
String aliasColumn = controlField;
if (StringUtils.isNotBlank(alias)) {
aliasColumn = alias + "." + controlField;
}
if (sqlField.indexOf(aliasColumn) != -1) {
log.warn("sql黑名单校验,表【"+name+"】中字段【"+controlField+"】禁止查询");
return true;
}
}
}
}
return false;
}
@Override
public String toString() {
return "QueryTable{" +
"name='" + name + '\'' +
", alias='" + alias + '\'' +
", fields=" + fields +
", all=" + all +
'}';
}
}
public String getError(){
// TODO
return "系统设置了安全规则,敏感表和敏感字段禁止查询,联系管理员授权!";
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\security\AbstractQueryBlackListHandler.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ShiroFilterFactoryBean shiroFilterFactoryBean() {
ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
shiroFilterFactoryBean.setSecurityManager(securityManager());
Map<String, Filter> filters = new LinkedHashMap<String, Filter>();
LogoutFilter logoutFilter = new LogoutFilter();
logoutFilter.setRedirectUrl("/login");
// filters.put("logout",null);
shiroFilterFactoryBean.setFilters(filters);
Map<String, String> filterChainDefinitionManager = new LinkedHashMap<String, String>();
filterChainDefinitionManager.put("/logout", "logout");
filterChainDefinitionManager.put("/user/**", "authc,roles[ROLE_USER]");
filterChainDefinitionManager.put("/events/**", "authc,roles[ROLE_ADMIN]");
// filterChainDefinitionManager.put("/user/edit/**", "authc,perms[user:edit]");// 这里为了测试,固定写死的值,也可以从数据库或其他配置中读取
filterChainDefinitionManager.put("/**", "anon");
shiroFilterFactoryBean.setFilterChainDefinitionMap(filterChainDefinitionManager);
shiroFilterFactoryBean.setSuccessUrl("/");
shiroFilterFactoryBean.setUnauthorizedUrl("/403");
return shiroFilterFactoryBean;
}
/**
* DefaultAdvisorAutoProxyCreator,Spring的一个bean,由Advisor决定对哪些类的方法进行AOP代理。
*/
|
@Bean
@ConditionalOnMissingBean
public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
DefaultAdvisorAutoProxyCreator defaultAAP = new DefaultAdvisorAutoProxyCreator();
defaultAAP.setProxyTargetClass(true);
return defaultAAP;
}
/**
* AuthorizationAttributeSourceAdvisor,shiro里实现的Advisor类,
* 内部使用AopAllianceAnnotationsAuthorizingMethodInterceptor来拦截用以下注解的方法。
*/
@Bean
public AuthorizationAttributeSourceAdvisor authorizationAttributeSourceAdvisor() {
AuthorizationAttributeSourceAdvisor aASA = new AuthorizationAttributeSourceAdvisor();
aASA.setSecurityManager(securityManager());
return aASA;
}
}
|
repos\springBoot-master\springboot-shiro\src\main\java\com\us\shiro\ShiroConfiguration.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class ZipCodeApi {
private ZIPRepo zipRepo;
public ZipCodeApi(ZIPRepo zipRepo) {
this.zipRepo = zipRepo;
}
@GetMapping("/{zipcode}")
public Mono<ZipCode> findById(@PathVariable String zipcode) {
return getById(zipcode);
}
@GetMapping("/by_city")
public Flux<ZipCode> postZipCode(@RequestParam String city) {
return zipRepo.findByCity(city);
}
@PostMapping
public Mono<ZipCode> create(@RequestBody ZipCode zipCode) {
return getById(zipCode.getZip())
.switchIfEmpty(Mono.defer(createZipCode(zipCode)))
.onErrorResume(this::isKeyDuplicated, this.recoverWith(zipCode));
}
private Mono<ZipCode> getById(String zipCode) {
return zipRepo.findById(zipCode);
}
|
private boolean isKeyDuplicated(Throwable ex) {
return ex instanceof DataIntegrityViolationException || ex instanceof UncategorizedR2dbcException;
}
private Function<? super Throwable, ? extends Mono<ZipCode>> recoverWith(ZipCode zipCode) {
return throwable -> zipRepo.findById(zipCode.getZip());
}
private Supplier<Mono<? extends ZipCode>> createZipCode(ZipCode zipCode) {
return () -> {
zipCode.setId(zipCode.getZip());
return zipRepo.save(zipCode);
};
}
}
|
repos\tutorials-master\quarkus-modules\quarkus-vs-springboot\spring-project\src\main\java\com\baeldung\spring_project\ZipCodeApi.java
| 2
|
请完成以下Java代码
|
public String toString()
{
return "PlainHandlingUnitsInfo [tuName=" + tuName + ", qtyTU=" + qtyTU + "]";
}
@Override
public int getQtyTU()
{
return qtyTU;
}
@Override
public String getTUName()
{
return tuName;
}
@Override
public IHandlingUnitsInfo add(@Nullable final IHandlingUnitsInfo infoToAdd)
{
if (infoToAdd == null)
{
return this; // shall not happen
}
|
final String tuName = getTUName();
if (!tuName.equals(infoToAdd.getTUName()))
{
throw new AdempiereException("TU Names are not matching."
+ "\n This: " + this
+ "\n Other: " + infoToAdd);
}
final int qtyTU = getQtyTU();
final int qtyTU_ToAdd = infoToAdd.getQtyTU();
final int qtyTU_New = qtyTU + qtyTU_ToAdd;
final PlainHandlingUnitsInfo infoNew = new PlainHandlingUnitsInfo(tuName, qtyTU_New);
return infoNew;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\PlainHandlingUnitsInfo.java
| 1
|
请完成以下Java代码
|
public static LookupDescriptorProvider fromMemoizingFunction(final Function<LookupScope, LookupDescriptor> providerFunction)
{
return new MemoizingFunctionLookupDescriptorProvider(providerFunction);
}
//
//
//
private static class NullLookupDescriptorProvider implements LookupDescriptorProvider
{
@Override
public Optional<LookupDescriptor> provideForScope(final LookupScope scope)
{
return Optional.empty();
}
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@ToString
private static class SingletonLookupDescriptorProvider implements LookupDescriptorProvider
{
private final Optional<LookupDescriptor> lookupDescriptor;
private SingletonLookupDescriptorProvider(@NonNull final LookupDescriptor lookupDescriptor)
{
this.lookupDescriptor = Optional.of(lookupDescriptor);
}
@Override
public Optional<LookupDescriptor> provideForScope(final LookupScope scope)
{
return lookupDescriptor;
}
}
|
@ToString
private static class MemoizingFunctionLookupDescriptorProvider implements LookupDescriptorProvider
{
private final MemoizingFunction<LookupScope, LookupDescriptor> providerFunctionMemoized;
private MemoizingFunctionLookupDescriptorProvider(@NonNull final Function<LookupScope, LookupDescriptor> providerFunction)
{
providerFunctionMemoized = Functions.memoizing(providerFunction);
}
@Override
public Optional<LookupDescriptor> provideForScope(final LookupScope scope)
{
return Optional.ofNullable(providerFunctionMemoized.apply(scope));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\LookupDescriptorProviders.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public int updateDeleteStatus(List<Long> ids, Integer deleteStatus) {
PmsProduct record = new PmsProduct();
record.setDeleteStatus(deleteStatus);
PmsProductExample example = new PmsProductExample();
example.createCriteria().andIdIn(ids);
return productMapper.updateByExampleSelective(record, example);
}
@Override
public List<PmsProduct> list(String keyword) {
PmsProductExample productExample = new PmsProductExample();
PmsProductExample.Criteria criteria = productExample.createCriteria();
criteria.andDeleteStatusEqualTo(0);
if(!StrUtil.isEmpty(keyword)){
criteria.andNameLike("%" + keyword + "%");
productExample.or().andDeleteStatusEqualTo(0).andProductSnLike("%" + keyword + "%");
}
return productMapper.selectByExample(productExample);
}
/**
* 建立和插入关系表操作
*
* @param dao 可以操作的dao
* @param dataList 要插入的数据
* @param productId 建立关系的id
*/
private void relateAndInsertList(Object dao, List dataList, Long productId) {
|
try {
if (CollectionUtils.isEmpty(dataList)) return;
for (Object item : dataList) {
Method setId = item.getClass().getMethod("setId", Long.class);
setId.invoke(item, (Long) null);
Method setProductId = item.getClass().getMethod("setProductId", Long.class);
setProductId.invoke(item, productId);
}
Method insertList = dao.getClass().getMethod("insertList", List.class);
insertList.invoke(dao, dataList);
} catch (Exception e) {
LOGGER.warn("创建商品出错:{}", e.getMessage());
throw new RuntimeException(e.getMessage());
}
}
}
|
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\PmsProductServiceImpl.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDate getTargetDate() {
return targetDate;
|
}
public void setTargetDate(LocalDate targetDate) {
this.targetDate = targetDate;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
@Override
public String toString() {
return "Todo [id=" + id + ", username=" + username + ", description=" + description + ", targetDate="
+ targetDate + ", done=" + done + "]";
}
}
|
repos\master-spring-and-spring-boot-main\91-aws\03-rest-api-full-stack-h2\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\todo\Todo.java
| 2
|
请完成以下Java代码
|
public void setGL_Fund_ID (int GL_Fund_ID)
{
if (GL_Fund_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_Fund_ID, Integer.valueOf(GL_Fund_ID));
}
/** Get GL Fund.
@return General Ledger Funds Control
*/
public int getGL_Fund_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Fund_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Fund Restriction.
@param GL_FundRestriction_ID
Restriction of Funds
*/
public void setGL_FundRestriction_ID (int GL_FundRestriction_ID)
{
if (GL_FundRestriction_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_FundRestriction_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_FundRestriction_ID, Integer.valueOf(GL_FundRestriction_ID));
}
/** Get Fund Restriction.
@return Restriction of Funds
*/
public int getGL_FundRestriction_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_FundRestriction_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
|
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_GL_FundRestriction.java
| 1
|
请完成以下Java代码
|
static boolean isAuthorizationResponse(MultiValueMap<String, String> request) {
return isAuthorizationResponseSuccess(request) || isAuthorizationResponseError(request);
}
static boolean isAuthorizationResponseSuccess(MultiValueMap<String, String> request) {
return StringUtils.hasText(request.getFirst(OAuth2ParameterNames.CODE))
&& StringUtils.hasText(request.getFirst(OAuth2ParameterNames.STATE));
}
static boolean isAuthorizationResponseError(MultiValueMap<String, String> request) {
return StringUtils.hasText(request.getFirst(OAuth2ParameterNames.ERROR))
&& StringUtils.hasText(request.getFirst(OAuth2ParameterNames.STATE));
}
static OAuth2AuthorizationResponse convert(MultiValueMap<String, String> request, String redirectUri) {
String code = request.getFirst(OAuth2ParameterNames.CODE);
String errorCode = request.getFirst(OAuth2ParameterNames.ERROR);
|
String state = request.getFirst(OAuth2ParameterNames.STATE);
if (StringUtils.hasText(code)) {
return OAuth2AuthorizationResponse.success(code).redirectUri(redirectUri).state(state).build();
}
String errorDescription = request.getFirst(OAuth2ParameterNames.ERROR_DESCRIPTION);
String errorUri = request.getFirst(OAuth2ParameterNames.ERROR_URI);
// @formatter:off
return OAuth2AuthorizationResponse.error(errorCode)
.redirectUri(redirectUri)
.errorDescription(errorDescription)
.errorUri(errorUri)
.state(state)
.build();
// @formatter:on
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationResponseUtils.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DeveloperController {
//
@Autowired
private DeveloperRepository developerRepository;
@GetMapping("/dev")
public List<Developer> getAllDevelopers(){
return developerRepository.findAll();
}
@GetMapping("/dev/{id}")
public ResponseEntity<Developer> getDeveloperById(@PathVariable(value = "id") Long devId) throws ResourceNotFoundException{
Developer developer = developerRepository.findById(devId)
.orElseThrow(()-> new ResourceNotFoundException("Developer could not find on::" + devId));
return ResponseEntity.ok().body(developer);
}
@PostMapping("/dev")
public Developer createDev(@Valid @RequestBody Developer developer){
return developerRepository.save(developer);
}
@PutMapping("/dev/{id}")
public ResponseEntity<Developer> updateDeveloper (
@PathVariable(value = "id") Long devId,
@Valid @RequestBody Developer developerDetails) throws ResourceNotFoundException{
|
Developer developer = developerRepository.findById(devId)
.orElseThrow(() -> new ResourceNotFoundException("Developer not found on:: " + devId));
developer.setEmailId(developerDetails.getEmailId());
developer.setLastName(developerDetails.getLastName());
developerDetails.setFirstName(developerDetails.getFirstName());
developerDetails.setCreateAt(developerDetails.getCreateAt());
// developer.setUpdatedAt(new Date());
final Developer updateDev = developerRepository.save(developer);
return ResponseEntity.ok(updateDev);
}
@DeleteMapping("/dev/{id}")
public Map<String, Boolean> deleteDev(
@PathVariable(value = "id") Long devId) throws Exception{
Developer developer = developerRepository.findById(devId)
.orElseThrow(()-> new ResourceNotFoundException("Developer cannot found on:: " + devId));
developerRepository.delete(developer);
Map<String, Boolean> response = new HashMap<>();
response.put("delete", Boolean.TRUE);
return response;
}
}
|
repos\SpringBoot-Projects-FullStack-master\Part-4 Spring Boot REST API\SpringMySQL\src\main\java\spring\restapi\controller\DeveloperController.java
| 2
|
请完成以下Java代码
|
private void flushIfRequired() {
if (RedisSessionRepository.this.flushMode == FlushMode.IMMEDIATE) {
save();
}
}
private boolean hasChangedSessionId() {
return !getId().equals(this.originalSessionId);
}
private void save() {
saveChangeSessionId();
saveDelta();
if (this.isNew) {
this.isNew = false;
}
}
private void saveChangeSessionId() {
if (hasChangedSessionId()) {
if (!this.isNew) {
String originalSessionIdKey = getSessionKey(this.originalSessionId);
String sessionIdKey = getSessionKey(getId());
RedisSessionRepository.this.sessionRedisOperations.rename(originalSessionIdKey, sessionIdKey);
}
this.originalSessionId = getId();
|
}
}
private void saveDelta() {
if (this.delta.isEmpty()) {
return;
}
String key = getSessionKey(getId());
RedisSessionRepository.this.sessionRedisOperations.opsForHash().putAll(key, new HashMap<>(this.delta));
RedisSessionRepository.this.sessionRedisOperations.expireAt(key,
Instant.ofEpochMilli(getLastAccessedTime().toEpochMilli())
.plusSeconds(getMaxInactiveInterval().getSeconds()));
this.delta.clear();
}
}
}
|
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\RedisSessionRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Response login(
@NotBlank(message = "{required}") String username,
@NotBlank(message = "{required}") String password, HttpServletRequest request) throws Exception {
username = StringUtils.lowerCase(username);
password = MD5Util.encrypt(username, password);
final String errorMessage = "用户名或密码错误";
User user = SystemUtils.getUser(username);
if (user == null)
throw new SystemException(errorMessage);
if (!StringUtils.equals(user.getPassword(), password))
throw new SystemException(errorMessage);
// 生成 Token
String token = JWTUtil.sign(username, password);
Map<String, Object> userInfo = this.generateUserInfo(token, user);
return new Response().message("认证成功").data(userInfo);
}
|
/**
* 生成前端需要的用户信息,包括:
* 1. token
* 2. user
*
* @param token token
* @param user 用户信息
* @return UserInfo
*/
private Map<String, Object> generateUserInfo(String token, User user) {
String username = user.getUsername();
Map<String, Object> userInfo = new HashMap<>();
userInfo.put("token", token);
user.setPassword("it's a secret");
userInfo.put("user", user);
return userInfo;
}
}
|
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\controller\LoginController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
/* package */ PartitionerConfigReference build(final PartitionerConfigLine parent)
{
final PartitionerConfigReference partitionerConfigReference = new PartitionerConfigReference(parent, referencingColumnName, referencedTableName, partitionBoundary);
partitionerConfigReference.setDLM_Partition_Config_Reference_ID(DLM_Partition_Config_Reference_ID);
return partitionerConfigReference;
}
@Override
public int hashCode()
{
return new HashcodeBuilder()
.append(referencedTableName)
.append(referencingColumnName)
.append(parentbuilder)
.toHashcode();
};
/**
* Note: it's important not to include {@link #getDLM_Partition_Config_Reference_ID()} in the result.
* Check the implementation of {@link PartitionerConfigLine.LineBuilder#endRef()} for details.
*/
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
|
}
final RefBuilder other = EqualsBuilder.getOther(this, obj);
if (other == null)
{
return false;
}
return new EqualsBuilder()
.append(referencedTableName, other.referencedTableName)
.append(referencingColumnName, other.referencingColumnName)
.append(parentbuilder, other.parentbuilder)
.isEqual();
}
@Override
public String toString()
{
return "RefBuilder [referencingColumnName=" + referencingColumnName + ", referencedTableName=" + referencedTableName + ", partitionBoundary=" + partitionBoundary + ", DLM_Partition_Config_Reference_ID=" + DLM_Partition_Config_Reference_ID + "]";
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\config\PartitionerConfigReference.java
| 2
|
请完成以下Java代码
|
public BigDecimal getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setValue(BigDecimal value) {
this.value = value;
}
/**
* Gets the value of the ccy property.
*
* @return
* possible object is
* {@link String }
*
*/
|
public String getCcy() {
return ccy;
}
/**
* Sets the value of the ccy property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCcy(String value) {
this.ccy = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ActiveOrHistoricCurrencyAndAmount.java
| 1
|
请完成以下Java代码
|
protected boolean requiresEngineAuthentication(String requestUrl) {
for (Pattern whiteListedUrlPattern : WHITE_LISTED_URL_PATTERNS) {
Matcher matcher = whiteListedUrlPattern.matcher(requestUrl);
if (matcher.matches()) {
return false;
}
}
return true;
}
/**
* May not return null
*/
protected String extractEngineName(String requestUrl) {
|
Matcher matcher = ENGINE_REQUEST_URL_PATTERN.matcher(requestUrl);
if (matcher.find()) {
return matcher.group(1);
} else {
// any request that does not match a specific engine and is not an /engine request
// is mapped to the default engine
return DEFAULT_ENGINE_NAME;
}
}
protected ProcessEngine getAddressedEngine(String engineName) {
return EngineUtil.lookupProcessEngine(engineName);
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\security\auth\ProcessEngineAuthenticationFilter.java
| 1
|
请完成以下Java代码
|
public void validate(final I_C_BPartner bpartner)
{
boolean ediRecipient = bpartner.isEdiDesadvRecipient() || bpartner.isEdiInvoicRecipient();
if (!ediRecipient)
{
return;
}
final List<Exception> feedback = Services.get(IEDIDocumentBL.class).isValidPartner(bpartner);
if (feedback == null || feedback.isEmpty())
{
return;
}
final StringBuilder causes = new StringBuilder();
for (final Exception feedbackElement : feedback)
{
causes.append(feedbackElement.getLocalizedMessage()).append("; ");
}
throw new AdempiereException("Invalid EDI partner " + causes.toString().trim());
}
/**
|
* Make sure the IsEDIRecipient flag from the invoice candidates of a partner is always up to date
*/
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_BPartner.COLUMNNAME_IsEdiInvoicRecipient })
public void updateIsEDIInvoicRecipient_InvoiceCandidates(final I_C_BPartner partner)
{
if (partner == null)
{
// nothing to do
return;
}
// Services
final IEDIInvoiceCandDAO invoiceCandidateDAO = Services.get(IEDIInvoiceCandDAO.class);
final boolean isEDIRecipient = partner.isEdiInvoicRecipient();
// update the unprocessed invoice candidates of this bpartner with the ediRecipient flag,
// only if the flag is not yet correctly set
invoiceCandidateDAO.updateEdiRecipientInvoiceCandidates(partner, isEDIRecipient);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\model\validator\C_BPartner.java
| 1
|
请完成以下Java代码
|
default void close() throws Exception {
}
/**
* Factory method to create an appropriate {@link Archive} from the given
* {@link Class} target.
* @param target a target class that will be used to find the archive code source
* @return an new {@link Archive} instance
* @throws Exception if the archive cannot be created
*/
static Archive create(Class<?> target) throws Exception {
return create(target.getProtectionDomain());
}
static Archive create(ProtectionDomain protectionDomain) throws Exception {
CodeSource codeSource = protectionDomain.getCodeSource();
URI location = (codeSource != null) ? codeSource.getLocation().toURI() : null;
if (location == null) {
throw new IllegalStateException("Unable to determine code source archive");
}
return create(Path.of(location).toFile());
}
/**
* Factory method to create an {@link Archive} from the given {@link File} target.
* @param target a target {@link File} used to create the archive. May be a directory
* or a jar file.
* @return a new {@link Archive} instance.
* @throws Exception if the archive cannot be created
*/
static Archive create(File target) throws Exception {
if (!target.exists()) {
throw new IllegalStateException("Unable to determine code source archive from " + target);
}
return (target.isDirectory() ? new ExplodedArchive(target) : new JarFileArchive(target));
}
|
/**
* Represents a single entry in the archive.
*/
interface Entry {
/**
* Returns the name of the entry.
* @return the name of the entry
*/
String name();
/**
* Returns {@code true} if the entry represents a directory.
* @return if the entry is a directory
*/
boolean isDirectory();
}
}
|
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\Archive.java
| 1
|
请完成以下Java代码
|
static AccountDimension extractAccountDimension(final I_Fact_Acct fa)
{
return AccountDimension.builder()
.setAcctSchemaId(AcctSchemaId.ofRepoId(fa.getC_AcctSchema_ID()))
.setAD_Client_ID(fa.getAD_Client_ID())
.setAD_Org_ID(fa.getAD_Org_ID())
.setC_ElementValue_ID(fa.getAccount_ID())
.setC_SubAcct_ID(fa.getC_SubAcct_ID())
.setM_Product_ID(fa.getM_Product_ID())
.setC_BPartner_ID(fa.getC_BPartner_ID())
.setAD_OrgTrx_ID(fa.getAD_OrgTrx_ID())
.setC_LocFrom_ID(fa.getC_LocFrom_ID())
.setC_LocTo_ID(fa.getC_LocTo_ID())
.setC_SalesRegion_ID(SalesRegionId.ofRepoIdOrNull(fa.getC_SalesRegion_ID()))
.setC_Project_ID(fa.getC_Project_ID())
.setC_Campaign_ID(fa.getC_Campaign_ID())
.setC_Activity_ID(fa.getC_Activity_ID())
.setSalesOrderId(fa.getC_OrderSO_ID())
.setUser1_ID(fa.getUser1_ID())
.setUser2_ID(fa.getUser2_ID())
.setUserElement1_ID(fa.getUserElement1_ID())
.setUserElement2_ID(fa.getUserElement2_ID())
.setUserElementString1(fa.getUserElementString1())
.setUserElementString2(fa.getUserElementString2())
.setUserElementString3(fa.getUserElementString3())
.setUserElementString4(fa.getUserElementString4())
.setUserElementString5(fa.getUserElementString5())
.setUserElementString6(fa.getUserElementString6())
.setUserElementString7(fa.getUserElementString7())
.build();
}
static Dimension extractDimension(final I_Fact_Acct record)
{
return Dimension.builder()
.projectId(ProjectId.ofRepoIdOrNull(record.getC_Project_ID()))
|
.campaignId(record.getC_Campaign_ID())
.activityId(ActivityId.ofRepoIdOrNull(record.getC_Activity_ID()))
.salesOrderId(OrderId.ofRepoIdOrNull(record.getC_OrderSO_ID()))
.productId(ProductId.ofRepoIdOrNull(record.getM_Product_ID()))
.bpartnerId2(BPartnerId.ofRepoIdOrNull(record.getC_BPartner_ID()))
.user1_ID(record.getUser1_ID())
.user2_ID(record.getUser2_ID())
.userElement1Id(record.getUserElement1_ID())
.userElement2Id(record.getUserElement2_ID())
.userElementString1(record.getUserElementString1())
.userElementString2(record.getUserElementString2())
.userElementString3(record.getUserElementString3())
.userElementString4(record.getUserElementString4())
.userElementString5(record.getUserElementString5())
.userElementString6(record.getUserElementString6())
.userElementString7(record.getUserElementString7())
.build();
}
Optional<Money> getAcctBalance(@NonNull List<FactAcctQuery> queries);
Stream<I_Fact_Acct> stream(FactAcctQuery query);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\acct\api\IFactAcctBL.java
| 1
|
请完成以下Java代码
|
public int hashCode() {
final int prime = 31;
int result = 1;
long temp;
temp = Double.doubleToLongBits(bestFitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(bestPosition);
temp = Double.doubleToLongBits(fitness);
result = prime * result + (int) (temp ^ (temp >>> 32));
result = prime * result + Arrays.hashCode(position);
result = prime * result + Arrays.hashCode(speed);
return result;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Particle other = (Particle) obj;
if (Double.doubleToLongBits(bestFitness) != Double.doubleToLongBits(other.bestFitness))
return false;
if (!Arrays.equals(bestPosition, other.bestPosition))
return false;
if (Double.doubleToLongBits(fitness) != Double.doubleToLongBits(other.fitness))
return false;
if (!Arrays.equals(position, other.position))
return false;
|
if (!Arrays.equals(speed, other.speed))
return false;
return true;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "Particle [position=" + Arrays.toString(position) + ", speed=" + Arrays.toString(speed) + ", fitness="
+ fitness + ", bestPosition=" + Arrays.toString(bestPosition) + ", bestFitness=" + bestFitness + "]";
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\multiswarm\Particle.java
| 1
|
请完成以下Java代码
|
public static ConstantWorkpackagePrio medium()
{
return prio2strategy.get(X_C_Queue_WorkPackage.PRIORITY_Medium);
}
public static ConstantWorkpackagePrio low()
{
return prio2strategy.get(X_C_Queue_WorkPackage.PRIORITY_Low);
}
public static ConstantWorkpackagePrio minor()
{
return prio2strategy.get(X_C_Queue_WorkPackage.PRIORITY_Minor);
}
public static ConstantWorkpackagePrio fromString(final String string)
{
return prio2strategy.get(string.toLowerCase());
}
|
@Override
public String getPrioriy(IWorkPackageQueue IGNORED)
{
return getPriority();
}
public String getPriority()
{
return prio;
}
@Override
public String toString()
{
return "ConstantWorkpackagePrio[" + prio + "]";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\spi\impl\ConstantWorkpackagePrio.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ArithmeticController {
@Inject
private ArithmeticService arithmeticService;
@Get("/sum/{number1}/{number2}")
public float getSum(float number1, float number2) {
return arithmeticService.add(number1, number2);
}
@Get("/subtract/{number1}/{number2}")
public float getDifference(float number1, float number2) {
return arithmeticService.subtract(number1, number2);
}
@Get("/multiply/{number1}/{number2}")
public float getMultiplication(float number1, float number2) {
return arithmeticService.multiply(number1, number2);
}
@Get("/divide/{number1}/{number2}")
public float getDivision(float number1, float number2) {
return arithmeticService.divide(number1, number2);
}
|
@Get("/memory")
public String getMemoryStatus() {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean();
String memoryStats = "";
String init = String.format("Initial: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
.getInit() / 1073741824);
String usedHeap = String.format("Used: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
.getUsed() / 1073741824);
String maxHeap = String.format("Max: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
.getMax() / 1073741824);
String committed = String.format("Committed: %.2f GB \n", (double) memoryBean.getHeapMemoryUsage()
.getCommitted() / 1073741824);
memoryStats += init;
memoryStats += usedHeap;
memoryStats += maxHeap;
memoryStats += committed;
return memoryStats;
}
}
|
repos\tutorials-master\microservices-modules\micronaut\src\main\java\com\baeldung\micronaut\vs\springboot\controller\ArithmeticController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class Store {
@Id
@GeneratedValue
private Long id;
private String name;
private String location;
@JdbcTypeCode(SqlTypes.JSON)
private Map<String, String> attributes = new HashMap<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
|
}
public String getLocation() {
return location;
}
public void setLocation(String location) {
this.location = location;
}
public Map<String, String> getAttributes() {
return attributes;
}
public void setAttributes(Map<String, String> attributes) {
this.attributes = attributes;
}
}
|
repos\tutorials-master\persistence-modules\hibernate6\src\main\java\com\baeldung\persistjson\Store.java
| 2
|
请完成以下Java代码
|
public void setQty(final BigDecimal qty)
{
olCand.setQtyEntered_Override(qty);
values.setQty(qty);
}
@Override
public BigDecimal getQty()
{
return olCandEffectiveValuesBL.getEffectiveQtyEntered(olCand);
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
final Integer valueOverrideOrValue = getValueOverrideOrValue(olCand, I_C_OLCand.COLUMNNAME_M_HU_PI_Item_Product_ID);
return valueOverrideOrValue == null ? 0 : valueOverrideOrValue;
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
olCand.setM_HU_PI_Item_Product_Override_ID(huPiItemProductId);
values.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return olCand.getM_AttributeSetInstance_ID();
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
olCand.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
values.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
}
@Override
public int getC_UOM_ID()
{
return olCandEffectiveValuesBL.getEffectiveUomId(olCand).getRepoId();
}
@Override
public void setC_UOM_ID(final int uomId)
{
values.setUomId(UomId.ofRepoIdOrNull(uomId));
// NOTE: uom is mandatory
// we assume orderLine's UOM is correct
if (uomId > 0)
{
olCand.setPrice_UOM_Internal_ID(uomId);
}
}
@Override
public BigDecimal getQtyTU()
{
return Quantitys.toBigDecimalOrNull(olCandEffectiveValuesBL.getQtyItemCapacity_Effective(olCand));
}
@Override
|
public void setQtyTU(final BigDecimal qtyPacks)
{
values.setQtyTU(qtyPacks);
}
@Override
public int getC_BPartner_ID()
{
final BPartnerId bpartnerId = olCandEffectiveValuesBL.getBPartnerEffectiveId(olCand);
return BPartnerId.toRepoId(bpartnerId);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
olCand.setC_BPartner_Override_ID(partnerId);
values.setBpartnerId(BPartnerId.ofRepoIdOrNull(partnerId));
}
@Override
public boolean isInDispute()
{
// order line has no IsInDispute flag
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\OLCandHUPackingAware.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BigDecimal getBaseQuantity() {
return baseQuantity;
}
/**
* Sets the value of the baseQuantity property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setBaseQuantity(BigDecimal value) {
this.baseQuantity = value;
}
/**
* Gets the value of the priceType property.
*
* @return
* possible object is
|
* {@link String }
*
*/
public String getPriceType() {
return priceType;
}
/**
* Sets the value of the priceType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPriceType(String value) {
this.priceType = value;
}
}
|
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\UnitPriceExtType.java
| 2
|
请完成以下Spring Boot application配置
|
spring:
application:
name: user-service-provider
# dubbo 配置项,对应 DubboConfigurationProperties 配置类
dubbo:
# Dubbo 应用配置
application:
name: ${spring.application.name} # 应用名
# Dubbo 注册中心配
registry:
address: zookeeper://127.0.0.1:2181 # 注册中心地址。个鞥多注册中心,可见 http://dubbo.apache.org/zh-cn/docs/user/references/registry/introduction.html 文档。
# Dubbo 服务提供者协议配置
protocol:
port: -1 # 协议端口。使用 -1 表示随机端口。
name: dubbo # 使用 `dubbo://` 协议。更多协议,可见 http://dubbo.a
|
pache.org/zh-cn/docs/user/references/protocol/introduction.html 文档
# 配置扫描 Dubbo 自定义的 @Service 注解,暴露成 Dubbo 服务提供者
scan:
base-packages: cn.iocoder.springboot.lab39.skywalkingdemo.providerdemo.service
|
repos\SpringBoot-Labs-master\lab-39\lab-39-skywalking-dubbo\lab-39-skywalking-dubbo-provider\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public static <T> UomId getCommonUomIdOfAll(
@NonNull final Function<T, UomId> getUomId,
@NonNull final String name,
@Nullable final T... objects)
{
if (objects == null || objects.length == 0)
{
throw new AdempiereException("No " + name + " provided");
}
else if (objects.length == 1 && objects[0] != null)
{
return getUomId.apply(objects[0]);
}
else
{
UomId commonUomId = null;
for (final T object : objects)
{
if (object == null)
{
continue;
}
|
final UomId uomId = getUomId.apply(object);
if (commonUomId == null)
{
commonUomId = uomId;
}
else if (!UomId.equals(commonUomId, uomId))
{
throw new AdempiereException("All given " + name + "(s) shall have the same UOM: " + Arrays.asList(objects));
}
}
if (commonUomId == null)
{
throw new AdempiereException("At least one non null " + name + " instance was expected: " + Arrays.asList(objects));
}
return commonUomId;
}
}
public boolean isEach() {return EACH.equals(this);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UomId.java
| 1
|
请完成以下Java代码
|
public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
@Override
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Kann exportieren.
@param IsCanExport
Users with this role can export data
*/
@Override
public void setIsCanExport (boolean IsCanExport)
{
set_Value (COLUMNNAME_IsCanExport, Boolean.valueOf(IsCanExport));
}
/** Get Kann exportieren.
@return Users with this role can export data
*/
@Override
public boolean isCanExport ()
{
Object oo = get_Value(COLUMNNAME_IsCanExport);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Kann Berichte erstellen.
@param IsCanReport
Users with this role can create reports
*/
@Override
public void setIsCanReport (boolean IsCanReport)
{
set_Value (COLUMNNAME_IsCanReport, Boolean.valueOf(IsCanReport));
}
/** Get Kann Berichte erstellen.
@return Users with this role can create reports
*/
@Override
public boolean isCanReport ()
{
Object oo = get_Value(COLUMNNAME_IsCanReport);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Ausschluß.
@param IsExclude
Exclude access to the data - if not selected Include access to the data
*/
@Override
public void setIsExclude (boolean IsExclude)
{
|
set_Value (COLUMNNAME_IsExclude, Boolean.valueOf(IsExclude));
}
/** Get Ausschluß.
@return Exclude access to the data - if not selected Include access to the data
*/
@Override
public boolean isExclude ()
{
Object oo = get_Value(COLUMNNAME_IsExclude);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Schreibgeschützt.
@param IsReadOnly
Field is read only
*/
@Override
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Schreibgeschützt.
@return Field is read only
*/
@Override
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Table_Access.java
| 1
|
请完成以下Java代码
|
public void setSameSite(String sameSite) {
this.sameSite = sameSite;
}
private String getDomainName(HttpServletRequest request) {
if (this.domainName != null) {
return this.domainName;
}
if (this.domainNamePattern != null) {
Matcher matcher = this.domainNamePattern.matcher(request.getServerName());
if (matcher.matches()) {
return matcher.group(1);
}
}
return null;
}
private String getCookiePath(HttpServletRequest request) {
if (this.cookiePath == null) {
String contextPath = request.getContextPath();
return (contextPath != null && contextPath.length() > 0) ? contextPath : "/";
}
return this.cookiePath;
}
/**
|
* Gets the name of the request attribute that is checked to see if the cookie should
* be written with {@link Integer#MAX_VALUE}.
* @return the remember me request attribute
* @since 3.2
*/
public String getRememberMeRequestAttribute() {
return this.rememberMeRequestAttribute;
}
/**
* Allows defining whether the generated cookie carries the Partitioned attribute.
* @param partitioned whether the generate cookie is partitioned
* @since 3.4
*/
public void setPartitioned(boolean partitioned) {
this.partitioned = partitioned;
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\DefaultCookieSerializer.java
| 1
|
请完成以下Java代码
|
public void setArangoId(String arangoId) {
this.arangoId = arangoId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
|
}
public ZonedDateTime getPublishDate() {
return publishDate;
}
public void setPublishDate(ZonedDateTime publishDate) {
this.publishDate = publishDate;
}
public String getHtmlContent() {
return htmlContent;
}
public void setHtmlContent(String htmlContent) {
this.htmlContent = htmlContent;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-arangodb\src\main\java\com\baeldung\arangodb\model\Article.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
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
|
请在Spring Boot框架中完成以下Java代码
|
public void setRequestBody (final @Nullable java.lang.String RequestBody)
{
set_Value (COLUMNNAME_RequestBody, RequestBody);
}
@Override
public java.lang.String getRequestBody()
{
return get_ValueAsString(COLUMNNAME_RequestBody);
}
@Override
public void setRequestURI (final @Nullable java.lang.String RequestURI)
{
set_Value (COLUMNNAME_RequestURI, RequestURI);
}
@Override
public java.lang.String getRequestURI()
{
return get_ValueAsString(COLUMNNAME_RequestURI);
}
@Override
public void setResponseBody (final @Nullable java.lang.String ResponseBody)
{
set_Value (COLUMNNAME_ResponseBody, ResponseBody);
}
@Override
public java.lang.String getResponseBody()
{
return get_ValueAsString(COLUMNNAME_ResponseBody);
}
@Override
public void setResponseCode (final int ResponseCode)
{
set_Value (COLUMNNAME_ResponseCode, ResponseCode);
}
@Override
public int getResponseCode()
{
return get_ValueAsInt(COLUMNNAME_ResponseCode);
}
@Override
public void setSUMUP_API_Log_ID (final int SUMUP_API_Log_ID)
{
if (SUMUP_API_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_SUMUP_API_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SUMUP_API_Log_ID, SUMUP_API_Log_ID);
}
@Override
|
public int getSUMUP_API_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_API_Log_ID);
}
@Override
public de.metas.payment.sumup.repository.model.I_SUMUP_Config getSUMUP_Config()
{
return get_ValueAsPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class);
}
@Override
public void setSUMUP_Config(final de.metas.payment.sumup.repository.model.I_SUMUP_Config SUMUP_Config)
{
set_ValueFromPO(COLUMNNAME_SUMUP_Config_ID, de.metas.payment.sumup.repository.model.I_SUMUP_Config.class, SUMUP_Config);
}
@Override
public void setSUMUP_Config_ID (final int SUMUP_Config_ID)
{
if (SUMUP_Config_ID < 1)
set_Value (COLUMNNAME_SUMUP_Config_ID, null);
else
set_Value (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID);
}
@Override
public int getSUMUP_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID);
}
@Override
public void setSUMUP_merchant_code (final @Nullable java.lang.String SUMUP_merchant_code)
{
set_Value (COLUMNNAME_SUMUP_merchant_code, SUMUP_merchant_code);
}
@Override
public java.lang.String getSUMUP_merchant_code()
{
return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_API_Log.java
| 2
|
请完成以下Java代码
|
public PageData<Notification> findLatestUnreadNotificationsByRecipientIdAndNotificationTypes(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId, Set<NotificationType> types, int limit) {
SortOrder sortOrder = new SortOrder(EntityKeyMapping.CREATED_TIME, SortOrder.Direction.DESC);
PageLink pageLink = new PageLink(limit, 0, null, sortOrder);
return notificationDao.findUnreadByDeliveryMethodAndRecipientIdAndNotificationTypesAndPageLink(tenantId, deliveryMethod, recipientId, types, pageLink);
}
@Override
public int countUnreadNotificationsByRecipientId(TenantId tenantId, NotificationDeliveryMethod deliveryMethod, UserId recipientId) {
return notificationDao.countUnreadByDeliveryMethodAndRecipientId(tenantId, deliveryMethod, recipientId);
}
@Override
public boolean deleteNotification(TenantId tenantId, UserId recipientId, NotificationId notificationId) {
return notificationDao.deleteByIdAndRecipientId(tenantId, recipientId, notificationId);
}
@Override
|
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findNotificationById(tenantId, new NotificationId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(notificationDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.NOTIFICATION;
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationService.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.