instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public KeyManagerFactory getKeyManagerFactory() {
try {
KeyStore store = this.storeBundle.getKeyStore();
this.key.assertContainsAlias(store);
String alias = this.key.getAlias();
String algorithm = KeyManagerFactory.getDefaultAlgorithm();
KeyManagerFactory factory = getKeyManagerFactoryInstance(algorithm);
factory = (alias != null) ? new AliasKeyManagerFactory(factory, alias, algorithm) : factory;
String password = this.key.getPassword();
password = (password != null) ? password : this.storeBundle.getKeyStorePassword();
factory.init(store, (password != null) ? password.toCharArray() : null);
return factory;
}
catch (RuntimeException ex) {
throw ex;
}
catch (Exception ex) {
throw new IllegalStateException("Could not load key manager factory: " + ex.getMessage(), ex);
}
}
@Override
public TrustManagerFactory getTrustManagerFactory() {
try {
KeyStore store = this.storeBundle.getTrustStore(); | String algorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory factory = getTrustManagerFactoryInstance(algorithm);
factory.init(store);
return factory;
}
catch (Exception ex) {
throw new IllegalStateException("Could not load trust manager factory: " + ex.getMessage(), ex);
}
}
protected KeyManagerFactory getKeyManagerFactoryInstance(String algorithm) throws NoSuchAlgorithmException {
return KeyManagerFactory.getInstance(algorithm);
}
protected TrustManagerFactory getTrustManagerFactoryInstance(String algorithm) throws NoSuchAlgorithmException {
return TrustManagerFactory.getInstance(algorithm);
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ssl\DefaultSslManagerBundle.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static boolean verifySign(SortedMap<String, String> params,String headerSign) {
if (params == null || StringUtils.isEmpty(headerSign)) {
return false;
}
// 把参数加密
String paramsSign = getParamsSign(params);
log.debug("Param Sign : {}", paramsSign);
return !StringUtils.isEmpty(paramsSign) && headerSign.equals(paramsSign);
}
/**
* @param params
* 所有的请求参数都会在这里进行排序加密
* @return 得到签名
*/
public static String getParamsSign(SortedMap<String, String> params) {
//去掉 Url 里的时间戳
params.remove("_t");
String paramsJsonStr = JSONObject.toJSONString(params);
log.debug("Param paramsJsonStr : {}", paramsJsonStr);
//设置签名秘钥 | JeecgBaseConfig jeecgBaseConfig = SpringContextUtils.getBean(JeecgBaseConfig.class);
String signatureSecret = jeecgBaseConfig.getSignatureSecret();
String curlyBracket = SymbolConstant.DOLLAR + SymbolConstant.LEFT_CURLY_BRACKET;
if(oConvertUtils.isEmpty(signatureSecret) || signatureSecret.contains(curlyBracket)){
throw new JeecgBootException("签名密钥 ${jeecg.signatureSecret} 缺少配置 !!");
}
try {
//【issues/I484RW】2.4.6部署后,下拉搜索框提示“sign签名检验失败”
return DigestUtils.md5DigestAsHex((paramsJsonStr + signatureSecret).getBytes("UTF-8")).toUpperCase();
} catch (UnsupportedEncodingException e) {
log.error(e.getMessage(),e);
return null;
}
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\sign\util\SignUtil.java | 2 |
请完成以下Java代码 | public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Freight Category.
@param M_FreightCategory_ID
Category of the Freight
*/
public void setM_FreightCategory_ID (int M_FreightCategory_ID)
{
if (M_FreightCategory_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_FreightCategory_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_FreightCategory_ID, Integer.valueOf(M_FreightCategory_ID));
}
/** Get Freight Category.
@return Category of the Freight
*/
public int getM_FreightCategory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_FreightCategory_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());
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (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_FreightCategory.java | 1 |
请完成以下Java代码 | public int compare(ProcessEngineLookup o1, ProcessEngineLookup o2) {
return (-1) * ((Integer) o1.getPrecedence()).compareTo(o2.getPrecedence());
}
});
ProcessEngine processEngine = null;
for (ProcessEngineLookup processEngineLookup : discoveredLookups) {
processEngine = processEngineLookup.getProcessEngine();
if (processEngine != null) {
this.processEngineLookup = processEngineLookup;
LOGGER.debug("ProcessEngineLookup service {} returned process engine.", processEngineLookup.getClass());
break;
} else {
LOGGER.debug("ProcessEngineLookup service {} returned 'null' value.", processEngineLookup.getClass());
}
}
if (processEngineLookup == null) {
throw new FlowableException("Could not find an implementation of the org.flowable.cdi.spi.ProcessEngineLookup service " + "returning a non-null processEngine. Giving up."); | }
FlowableServices services = ProgrammaticBeanLookup.lookup(FlowableServices.class, beanManager);
services.setProcessEngine(processEngine);
return processEngine;
}
private void deployProcesses(ProcessEngine processEngine) {
new ProcessDeployer(processEngine).deployProcesses();
}
public void beforeShutdown(@Observes BeforeShutdown event) {
if (processEngineLookup != null) {
processEngineLookup.ungetProcessEngine();
processEngineLookup = null;
}
LOGGER.info("Shutting down flowable-cdi");
}
} | repos\flowable-engine-main\modules\flowable-cdi\src\main\java\org\flowable\cdi\impl\FlowableExtension.java | 1 |
请完成以下Java代码 | public void actionPerformed(ActionEvent e)
{
if (e.getSource() == bShowDay)
m_days = 1;
else if (e.getSource() == bShowWeek)
m_days = 7;
else if (e.getSource() == bShowMonth)
m_days = 31;
else if (e.getSource() == bShowYear)
m_days = 365;
else
m_days = 0; // all
dispose();
} // actionPerformed
/** | * Get selected number of days
* @return days or -1 for all
*/
public int getCurrentDays()
{
return m_days;
} // getCurrentDays
/**
* @return true if user has canceled this form
*/
public boolean isCancel() {
return m_isCancel;
}
} // VOnlyCurrentDays | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\VOnlyCurrentDays.java | 1 |
请完成以下Java代码 | private void setExecutionStatus()
{
// Success
if (exception == null)
{
Check.assumeNotNull(executionResult, "executionResult not null");
step.setErrorMsg(null);
if (executionResult == ExecutionResult.Executed)
{
if (action == Action.Apply)
{
step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Applied);
}
else if (action == Action.Rollback)
{
step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Unapplied);
}
else
{
throw new AdempiereException("Unknown action: " + action);
}
}
else if (executionResult == ExecutionResult.Skipped)
{
step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Unapplied);
}
else | {
throw new AdempiereException("Unknown execution result: " + executionResult);
}
}
// Error / Warning
else
{
logger.error("Action " + action + " of " + step + " failed.", exception);
step.setErrorMsg(exception.getLocalizedMessage());
if (action == Action.Apply)
{
step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Failed);
step.setApply(X_AD_MigrationStep.APPLY_Apply);
}
}
if (X_AD_MigrationStep.STATUSCODE_Applied.equals(step.getStatusCode()))
{
step.setApply(X_AD_MigrationStep.APPLY_Rollback);
}
else if (X_AD_MigrationStep.STATUSCODE_Unapplied.equals(step.getStatusCode()))
{
step.setApply(X_AD_MigrationStep.APPLY_Apply);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationStepExecutorRunnable.java | 1 |
请完成以下Java代码 | public PizzaStatusEnum getStatus() {
return status;
}
public void setStatus(PizzaStatusEnum status) {
this.status = status;
}
public boolean isDeliverable() {
return this.status.isReady();
}
public void printTimeToDeliver() {
System.out.println("Time to delivery is " + this.getStatus().getTimeToDelivery() + " days");
}
public static List<Pizza> getAllUndeliveredPizzas(List<Pizza> input) {
return input.stream().filter((s) -> !deliveredPizzaStatuses.contains(s.getStatus())).collect(Collectors.toList());
} | public static EnumMap<PizzaStatusEnum, List<Pizza>> groupPizzaByStatus(List<Pizza> pzList) {
return pzList.stream().collect(Collectors.groupingBy(Pizza::getStatus, () -> new EnumMap<>(PizzaStatusEnum.class), Collectors.toList()));
}
public void deliver() {
if (isDeliverable()) {
PizzaDeliverySystemConfiguration.getInstance().getDeliveryStrategy().deliver(this);
this.setStatus(PizzaStatusEnum.DELIVERED);
}
}
public int getDeliveryTimeInDays() {
switch (status) {
case ORDERED: return 5;
case READY: return 2;
case DELIVERED: return 0;
}
return 0;
}
} | repos\tutorials-master\core-java-modules\core-java-lang-oop-types\src\main\java\com\baeldung\enums\Pizza.java | 1 |
请完成以下Java代码 | public class Lwm2mController extends BaseController {
@Autowired
private DeviceController deviceController;
@Autowired
private LwM2MService lwM2MService;
public static final String IS_BOOTSTRAP_SERVER = "isBootstrapServer";
@ApiOperation(value = "Get Lwm2m Bootstrap SecurityInfo (getLwm2mBootstrapSecurityInfo)",
notes = "Get the Lwm2m Bootstrap SecurityInfo object (of the current server) based on the provided isBootstrapServer parameter. If isBootstrapServer == true, get the parameters of the current Bootstrap Server. If isBootstrapServer == false, get the parameters of the current Lwm2m Server. Used for client settings when starting the client in Bootstrap mode. " +
TENANT_OR_CUSTOMER_AUTHORITY_PARAGRAPH)
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/lwm2m/deviceProfile/bootstrap/{isBootstrapServer}", method = RequestMethod.GET)
@ResponseBody | public LwM2MServerSecurityConfigDefault getLwm2mBootstrapSecurityInfo(
@Parameter(description = IS_BOOTSTRAP_SERVER_PARAM_DESCRIPTION)
@PathVariable(IS_BOOTSTRAP_SERVER) boolean bootstrapServer) throws ThingsboardException {
return lwM2MService.getServerSecurityInfo(bootstrapServer);
}
@ApiOperation(hidden = true, value = "Save device with credentials (Deprecated)")
@PreAuthorize("hasAnyAuthority('TENANT_ADMIN', 'CUSTOMER_USER')")
@RequestMapping(value = "/lwm2m/device-credentials", method = RequestMethod.POST)
@ResponseBody
public Device saveDeviceWithCredentials(@RequestBody Map<Class<?>, Object> deviceWithDeviceCredentials) throws ThingsboardException {
Device device = checkNotNull(JacksonUtil.convertValue(deviceWithDeviceCredentials.get(Device.class), Device.class));
DeviceCredentials credentials = checkNotNull(JacksonUtil.convertValue(deviceWithDeviceCredentials.get(DeviceCredentials.class), DeviceCredentials.class));
return deviceController.saveDeviceWithCredentials(new SaveDeviceWithCredentialsRequest(device, credentials), DEFAULT.policy(), DEFAULT.separator(), DEFAULT.uniquifyStrategy());
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\controller\Lwm2mController.java | 1 |
请完成以下Java代码 | public class SwingUtils
{
/**
* @return JFrame of component or null
*/
public static JFrame getFrame(final Component component)
{
Component element = component;
while (element != null)
{
if (element instanceof JFrame)
{
return (JFrame)element;
}
element = element.getParent();
}
return null;
} // getFrame
public static Window getParentWindow(final Component component)
{
Component element = component;
while (element != null)
{
if (element instanceof JDialog || element instanceof JFrame)
{
return (Window)element;
}
if (element instanceof Window)
{
return (Window)element;
}
element = element.getParent();
}
return null;
} // getParent
/**
* Get Graphics of container or its parent. The element may not have a Graphic if not displayed yet, but the parent might have.
* | * @param container Container
* @return Graphics of container or null
*/
public static Graphics getGraphics(final Container container)
{
Container element = container;
while (element != null)
{
final Graphics g = element.getGraphics();
if (g != null)
{
return g;
}
element = element.getParent();
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\SwingUtils.java | 1 |
请完成以下Java代码 | public String getTablePrefix() {
return tablePrefix;
}
public void setTablePrefix(String tablePrefix) {
this.tablePrefix = tablePrefix;
}
public static List<String> getSchemaUpdateValues() {
return SCHEMA_UPDATE_VALUES;
}
public String getSchemaName() {
return schemaName;
}
public void setSchemaName(String schemaName) {
this.schemaName = schemaName;
}
public boolean isJdbcBatchProcessing() {
return jdbcBatchProcessing; | }
public void setJdbcBatchProcessing(boolean jdbcBatchProcessing) {
this.jdbcBatchProcessing = jdbcBatchProcessing;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("type=" + type)
.add("schemaUpdate=" + schemaUpdate)
.add("schemaName=" + schemaName)
.add("tablePrefix=" + tablePrefix)
.add("jdbcBatchProcessing=" + jdbcBatchProcessing)
.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\DatabaseProperty.java | 1 |
请完成以下Java代码 | public static JsonAddress.JsonAddressBuilder buildNShiftAddressBuilder(@NonNull final de.metas.common.delivery.v1.json.JsonAddress commonAddress, @NonNull final JsonAddressKind kind)
{
String street1 = commonAddress.getStreet();
if (Check.isNotBlank(commonAddress.getHouseNo()))
{
street1 = street1 + " " + commonAddress.getHouseNo();
}
return JsonAddress.builder()
.kind(kind)
.name1(commonAddress.getCompanyName1())
.name2(commonAddress.getCompanyName2())
.street1(street1)
.street2(commonAddress.getAdditionalAddressInfo())
.postCode(commonAddress.getZipCode())
.city(commonAddress.getCity())
.countryCode(commonAddress.getCountry());
}
public static JsonAddress.JsonAddressBuilder buildNShiftReceiverAddress(
@NonNull final de.metas.common.delivery.v1.json.JsonAddress deliveryAddress,
@Nullable final de.metas.common.delivery.v1.json.JsonContact deliveryContact) | {
final JsonAddress.JsonAddressBuilder receiverAddressBuilder = buildNShiftAddressBuilder(deliveryAddress, JsonAddressKind.RECEIVER);
if (deliveryContact != null)
{
if (Check.isNotBlank(deliveryContact.getPhone()))
{
receiverAddressBuilder.phone(deliveryContact.getPhone());
}
if (Check.isNotBlank(deliveryContact.getEmailAddress()))
{
receiverAddressBuilder.email(deliveryContact.getEmailAddress());
}
}
return receiverAddressBuilder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftUtil.java | 1 |
请完成以下Java代码 | public void setFilter(ISqlQueryFilter filter)
{
this.filter = filter;
}
@Override
public ISqlQueryFilter getModelFilter()
{
return modelFilter;
}
@Override
public void setModelFilter(ISqlQueryFilter modelFilter)
{
this.modelFilter = modelFilter;
}
@Override
public Access getRequiredAccess()
{
return requiredAccess;
}
@Override
public void setRequiredAccess(final Access requiredAccess)
{
this.requiredAccess = requiredAccess;
}
@Override
public Integer getCopies()
{ | return copies;
}
@Override
public void setCopies(int copies)
{
this.copies = copies;
}
@Override
public String getAggregationKey()
{
return aggregationKey;
}
@Override
public void setAggregationKey(final String aggregationKey)
{
this.aggregationKey=aggregationKey;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\api\impl\PrintingQueueQuery.java | 1 |
请在Spring Boot框架中完成以下Java代码 | 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 org.compiere.model.I_MobileUI_UserProfile_Picking getMobileUI_UserProfile_Picking()
{
return get_ValueAsPO(COLUMNNAME_MobileUI_UserProfile_Picking_ID, org.compiere.model.I_MobileUI_UserProfile_Picking.class);
}
@Override
public void setMobileUI_UserProfile_Picking(final org.compiere.model.I_MobileUI_UserProfile_Picking MobileUI_UserProfile_Picking)
{
set_ValueFromPO(COLUMNNAME_MobileUI_UserProfile_Picking_ID, org.compiere.model.I_MobileUI_UserProfile_Picking.class, MobileUI_UserProfile_Picking);
}
@Override
public void setMobileUI_UserProfile_Picking_ID (final int MobileUI_UserProfile_Picking_ID)
{
if (MobileUI_UserProfile_Picking_ID < 1)
set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, null);
else
set_Value (COLUMNNAME_MobileUI_UserProfile_Picking_ID, MobileUI_UserProfile_Picking_ID);
}
@Override
public int getMobileUI_UserProfile_Picking_ID()
{
return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_ID);
}
@Override
public void setPickingProfile_Filter_ID (final int PickingProfile_Filter_ID)
{
if (PickingProfile_Filter_ID < 1)
set_ValueNoCheck (COLUMNNAME_PickingProfile_Filter_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PickingProfile_Filter_ID, PickingProfile_Filter_ID);
}
@Override | public int getPickingProfile_Filter_ID()
{
return get_ValueAsInt(COLUMNNAME_PickingProfile_Filter_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\picking\model\X_PickingProfile_Filter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String prefix() {
return "management.elastic.metrics.export";
}
@Override
public String host() {
return obtain(ElasticProperties::getHost, ElasticConfig.super::host);
}
@Override
public String index() {
return obtain(ElasticProperties::getIndex, ElasticConfig.super::index);
}
@Override
public String indexDateFormat() {
return obtain(ElasticProperties::getIndexDateFormat, ElasticConfig.super::indexDateFormat);
}
@Override
public String indexDateSeparator() {
return obtain(ElasticProperties::getIndexDateSeparator, ElasticConfig.super::indexDateSeparator);
}
@Override
public String timestampFieldName() {
return obtain(ElasticProperties::getTimestampFieldName, ElasticConfig.super::timestampFieldName);
}
@Override
public boolean autoCreateIndex() {
return obtain(ElasticProperties::isAutoCreateIndex, ElasticConfig.super::autoCreateIndex);
}
@Override | public @Nullable String userName() {
return get(ElasticProperties::getUserName, ElasticConfig.super::userName);
}
@Override
public @Nullable String password() {
return get(ElasticProperties::getPassword, ElasticConfig.super::password);
}
@Override
public @Nullable String pipeline() {
return get(ElasticProperties::getPipeline, ElasticConfig.super::pipeline);
}
@Override
public @Nullable String apiKeyCredentials() {
return get(ElasticProperties::getApiKeyCredentials, ElasticConfig.super::apiKeyCredentials);
}
@Override
public boolean enableSource() {
return obtain(ElasticProperties::isEnableSource, ElasticConfig.super::enableSource);
}
} | repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\elastic\ElasticPropertiesConfigAdapter.java | 2 |
请完成以下Java代码 | public Collection<Rule> getRules() {
return ruleCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DecisionTable.class, DMN_ELEMENT_DECISION_TABLE)
.namespaceUri(LATEST_DMN_NS)
.extendsType(Expression.class)
.instanceProvider(new ModelTypeInstanceProvider<DecisionTable>() {
public DecisionTable newInstance(ModelTypeInstanceContext instanceContext) {
return new DecisionTableImpl(instanceContext);
}
});
hitPolicyAttribute = typeBuilder.namedEnumAttribute(DMN_ATTRIBUTE_HIT_POLICY, HitPolicy.class)
.defaultValue(HitPolicy.UNIQUE)
.build();
aggregationAttribute = typeBuilder.enumAttribute(DMN_ATTRIBUTE_AGGREGATION, BuiltinAggregator.class)
.build();
preferredOrientationAttribute = typeBuilder.namedEnumAttribute(DMN_ATTRIBUTE_PREFERRED_ORIENTATION, DecisionTableOrientation.class)
.defaultValue(DecisionTableOrientation.Rule_as_Row)
.build();
outputLabelAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_OUTPUT_LABEL)
.build(); | SequenceBuilder sequenceBuilder = typeBuilder.sequence();
inputCollection = sequenceBuilder.elementCollection(Input.class)
.build();
outputCollection = sequenceBuilder.elementCollection(Output.class)
.required()
.build();
ruleCollection = sequenceBuilder.elementCollection(Rule.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DecisionTableImpl.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8081
spring:
application:
name: publisher-demo
cloud:
# Consul
consul:
host: 127.0.0.1
port: 8500
# Bus 相关配置项,对应 BusProperties
bus:
enable | d: true # 是否开启,默认为 true
destination: springCloudBus # 目标消息队列,默认为 springCloudBus | repos\SpringBoot-Labs-master\labx-29-spring-cloud-consul-bus\labx-29-sc-bus-consul-demo-publisher\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public org.compiere.model.I_M_InOut getM_InOut()
{
return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class);
}
@Override
public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut)
{
set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut);
}
@Override
public void setM_InOut_ID (final int M_InOut_ID)
{
throw new IllegalArgumentException ("M_InOut_ID is virtual column"); }
@Override
public int getM_InOut_ID() | {
return get_ValueAsInt(COLUMNNAME_M_InOut_ID);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_Desadv_Pack.java | 1 |
请完成以下Java代码 | public class PrometheusApp {
public static void main(String[] args) throws InterruptedException, IOException {
JvmMetrics.builder().register();
HTTPServer server = HTTPServer.builder()
.port(9400)
.buildAndStart();
Counter requestCounter = Counter.builder()
.name("http_requests_total")
.help("Total number of HTTP requests")
.labelNames("method", "status")
.register();
requestCounter.labelValues("GET", "200").inc();
Gauge memoryUsage = Gauge.builder()
.name("memory_usage_bytes")
.help("Current memory usage in bytes")
.register();
memoryUsage.set(5000000);
Histogram requestLatency = Histogram.builder()
.name("http_request_latency_seconds")
.help("Tracks HTTP request latency in seconds")
.labelNames("method")
.register();
Random random = new Random();
for (int i = 0; i < 100; i++) {
double latency = 0.1 + (3 * random.nextDouble());
requestLatency.labelValues("GET").observe(latency);
} | Summary requestDuration = Summary.builder()
.name("http_request_duration_seconds")
.help("Tracks the duration of HTTP requests in seconds")
.quantile(0.5, 0.05)
.quantile(0.9, 0.01)
.register();
for (int i = 0; i < 100; i++) {
double duration = 0.05 + (2 * random.nextDouble());
requestDuration.observe(duration);
}
Info appInfo = Info.builder()
.name("app_info")
.help("Application version information")
.labelNames("version", "build")
.register();
appInfo.addLabelValues("1.0.0", "12345");
StateSet stateSet = StateSet.builder()
.name("feature_flags")
.help("Feature flags")
.labelNames("env")
.states("feature1")
.register();
stateSet.labelValues("dev").setFalse("feature1");
System.out.println("HTTPServer listening on http://localhost:" + server.getPort() + "/metrics");
Thread.currentThread().join();
}
} | repos\tutorials-master\metrics\src\main\java\com\baeldung\metrics\prometheus\PrometheusApp.java | 1 |
请完成以下Java代码 | public final class PayPalOrderAuthorizationId
{
@JsonCreator
public static PayPalOrderAuthorizationId ofString(@NonNull final String authId)
{
return new PayPalOrderAuthorizationId(authId);
}
public static PayPalOrderAuthorizationId ofNullableString(@Nullable final String authId)
{
return !Check.isEmpty(authId, true) ? new PayPalOrderAuthorizationId(authId) : null;
}
private final String id;
private PayPalOrderAuthorizationId(final String id)
{
Check.assumeNotEmpty(id, "id is not empty");
this.id = id;
} | @Override
@Deprecated
public String toString()
{
return getAsString();
}
@JsonValue
public String getAsString()
{
return id;
}
public static String toString(@Nullable final PayPalOrderAuthorizationId id)
{
return id != null ? id.getAsString() : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\client\PayPalOrderAuthorizationId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class InvoiceExportClientFactoryImpl implements InvoiceExportClientFactory
{
private static final Logger logger = LogManager.getLogger(InvoiceExportClientFactoryImpl.class);
private final ExportConfigRepository configRepository;
private final CrossVersionServiceRegistry crossVersionServiceRegistry;
public InvoiceExportClientFactoryImpl(
@NonNull final ExportConfigRepository configRepository,
@NonNull final CrossVersionServiceRegistry crossVersionServiceRegistry)
{
this.configRepository = configRepository;
this.crossVersionServiceRegistry = crossVersionServiceRegistry;
}
@Override
public String getInvoiceExportProviderId()
{
return ForumDatenaustauschChConstants.INVOICE_EXPORT_PROVIDER_ID;
}
@Override
public Optional<InvoiceExportClient> newClientForInvoice(@NonNull final InvoiceToExport invoice)
{
try (final MDCCloseable ignored = TableRecordMDC.putTableRecordReference(I_C_Invoice.Table_Name, invoice.getId()))
{
final String requiredAttachmentTag = ForumDatenaustauschChConstants.INVOICE_EXPORT_PROVIDER_ID;
final ILoggable loggable = Loggables.withLogger(logger, Level.DEBUG);
final boolean supported = invoice.getInvoiceAttachments()
.stream()
.map(attachment -> attachment.getTags().get(InvoiceExportClientFactory.ATTACHMENT_TAGNAME_EXPORT_PROVIDER)) // might be null
.anyMatch(providerId -> requiredAttachmentTag.equals(providerId));
if (!supported)
{
loggable.addLog("forum_datenaustausch_ch - The invoice with id={} has no attachment with an {}-tag", invoice.getId(), requiredAttachmentTag);
return Optional.empty();
}
final BPartnerId recipientId = invoice.getRecipient().getId(); | final BPartnerQuery query = BPartnerQuery
.builder()
.bPartnerId(de.metas.bpartner.BPartnerId.ofRepoId(recipientId.getRepoId()))
.build();
final ExportConfig config = configRepository.getForQueryOrNull(query);
if (config == null)
{
loggable.addLog("forum_datenaustausch_ch - There is no export config for the recipiend-id={} of the invoice with id={}", recipientId, invoice.getId());
return Optional.empty();
}
final InvoiceExportClientImpl client = new InvoiceExportClientImpl(crossVersionServiceRegistry, config);
if (!client.applies(invoice))
{
loggable.addLog("forum_datenaustausch_ch - the export-client {} said that it won't export the invoice with id={}", client.getClass().getSimpleName(), invoice.getId());
return Optional.empty();
}
return Optional.of(client);
}
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\export\invoice\InvoiceExportClientFactoryImpl.java | 2 |
请完成以下Java代码 | protected Mono<Void> doNotify(InstanceEvent event, Instance instance) {
return Mono.fromRunnable(() -> {
Context ctx = new Context();
ctx.setVariables(additionalProperties);
ctx.setVariable("baseUrl", this.baseUrl);
ctx.setVariable("event", event);
ctx.setVariable("instance", instance);
ctx.setVariable("lastStatus", getLastStatus(event.getInstance()));
try {
MimeMessage mimeMessage = mailSender.createMimeMessage();
MimeMessageHelper message = new MimeMessageHelper(mimeMessage, StandardCharsets.UTF_8.name());
message.setText(getBody(ctx).replaceAll("\\s+\\n", "\n"), true);
message.setSubject(getSubject(ctx));
message.setTo(this.to);
message.setCc(this.cc);
message.setFrom(this.from);
mailSender.send(mimeMessage);
}
catch (MessagingException ex) {
throw new RuntimeException("Error sending mail notification", ex);
}
});
}
protected String getBody(Context ctx) {
return templateEngine.process(this.template, ctx);
}
protected String getSubject(Context ctx) {
return templateEngine.process(this.template, singleton("subject"), ctx).trim();
}
public String[] getTo() {
return Arrays.copyOf(to, to.length);
}
public void setTo(String[] to) {
this.to = Arrays.copyOf(to, to.length);
}
public String[] getCc() {
return Arrays.copyOf(cc, cc.length);
} | public void setCc(String[] cc) {
this.cc = Arrays.copyOf(cc, cc.length);
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public String getTemplate() {
return template;
}
public void setTemplate(String template) {
this.template = template;
}
@Nullable
public String getBaseUrl() {
return baseUrl;
}
public void setBaseUrl(@Nullable String baseUrl) {
this.baseUrl = baseUrl;
}
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
public void setAdditionalProperties(Map<String, Object> additionalProperties) {
this.additionalProperties = additionalProperties;
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\MailNotifier.java | 1 |
请完成以下Java代码 | public boolean isSystemUser(@NonNull final UserId userId)
{
return queryBL
.createQueryBuilder(I_AD_User.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(org.compiere.model.I_AD_User.COLUMNNAME_AD_User_ID, userId)
.addEqualsFilter(org.compiere.model.I_AD_User.COLUMNNAME_IsSystemUser, true)
.create()
.anyMatch();
}
@Override
public BPartnerId getBPartnerIdByUserId(@NonNull final UserId userId)
{
final org.compiere.model.I_AD_User userRecord = getById(userId);
return BPartnerId.ofRepoIdOrNull(userRecord.getC_BPartner_ID());
}
@Override
public <T extends org.compiere.model.I_AD_User> T getByIdInTrx(final UserId userId, final Class<T> modelClass)
{
return load(userId, modelClass);
}
@Override
@Nullable
public UserId retrieveUserIdByLogin(@NonNull final String login)
{
return queryBL
.createQueryBuilderOutOfTrx(I_AD_User.class)
.addEqualsFilter(org.compiere.model.I_AD_User.COLUMNNAME_Login, login)
.create()
.firstId(UserId::ofRepoIdOrNull);
}
@Override
public void save(@NonNull final org.compiere.model.I_AD_User user)
{
InterfaceWrapperHelper.save(user);
}
@Override
public Optional<I_AD_User> getCounterpartUser(
@NonNull final UserId sourceUserId,
@NonNull final OrgId targetOrgId)
{
final OrgMappingId orgMappingId = getOrgMappingId(sourceUserId).orElse(null);
if (orgMappingId == null)
{
return Optional.empty();
} | final UserId targetUserId = queryBL.createQueryBuilder(I_AD_User.class)
.addEqualsFilter(I_AD_User.COLUMNNAME_AD_Org_Mapping_ID, orgMappingId)
.addEqualsFilter(I_AD_User.COLUMNNAME_AD_Org_ID, targetOrgId)
.orderByDescending(I_AD_User.COLUMNNAME_AD_User_ID)
.create()
.firstId(UserId::ofRepoIdOrNull);
if (targetUserId == null)
{
return Optional.empty();
}
return Optional.of(getById(targetUserId));
}
@Override
public ImmutableSet<UserId> retrieveUsersByJobId(@NonNull final JobId jobId)
{
return queryBL.createQueryBuilder(I_AD_User.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_User.COLUMNNAME_C_Job_ID, jobId)
.create()
.idsAsSet(UserId::ofRepoId);
}
private Optional<OrgMappingId> getOrgMappingId(@NonNull final UserId sourceUserId)
{
final I_AD_User sourceUserRecord = getById(sourceUserId);
return OrgMappingId.optionalOfRepoId(sourceUserRecord.getAD_Org_Mapping_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\impl\UserDAO.java | 1 |
请完成以下Java代码 | private void setJvmInfo() throws UnknownHostException {
Properties props = System.getProperties();
jvm.setTotal(Runtime.getRuntime().totalMemory());
jvm.setMax(Runtime.getRuntime().maxMemory());
jvm.setFree(Runtime.getRuntime().freeMemory());
jvm.setVersion(props.getProperty("java.version"));
jvm.setHome(props.getProperty("java.home"));
}
/**
* 设置磁盘信息
*/
private void setSysFiles(OperatingSystem os) {
FileSystem fileSystem = os.getFileSystem();
OSFileStore[] fsArray = fileSystem.getFileStores();
for (OSFileStore fs : fsArray) {
long free = fs.getUsableSpace();
long total = fs.getTotalSpace();
long used = total - free;
SysFile sysFile = new SysFile();
sysFile.setDirName(fs.getMount());
sysFile.setSysTypeName(fs.getType());
sysFile.setTypeName(fs.getName());
sysFile.setTotal(convertFileSize(total));
sysFile.setFree(convertFileSize(free));
sysFile.setUsed(convertFileSize(used));
sysFile.setUsage(NumberUtil.mul(NumberUtil.div(used, total, 4), 100)); | sysFiles.add(sysFile);
}
}
/**
* 字节转换
*
* @param size 字节大小
* @return 转换后值
*/
public String convertFileSize(long size) {
long kb = 1024;
long mb = kb * 1024;
long gb = mb * 1024;
if (size >= gb) {
return String.format("%.1f GB", (float) size / gb);
} else if (size >= mb) {
float f = (float) size / mb;
return String.format(f > 100 ? "%.0f MB" : "%.1f MB", f);
} else if (size >= kb) {
float f = (float) size / kb;
return String.format(f > 100 ? "%.0f KB" : "%.1f KB", f);
} else {
return String.format("%d B", size);
}
}
} | repos\spring-boot-demo-master\demo-websocket\src\main\java\com\xkcoding\websocket\model\Server.java | 1 |
请完成以下Java代码 | public void insertEditorSourceExtraForModel(String modelId, byte[] modelSource) {
ModelEntity model = findById(modelId);
if (model != null) {
ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceExtraValueId());
ref.setValue("source-extra", modelSource);
if (model.getEditorSourceExtraValueId() == null) {
model.setEditorSourceExtraValueId(ref.getId());
updateModel(model);
}
}
}
@Override
public List<Model> findModelsByQueryCriteria(ModelQueryImpl query, Page page) {
return modelDataManager.findModelsByQueryCriteria(query, page);
}
@Override
public long findModelCountByQueryCriteria(ModelQueryImpl query) {
return modelDataManager.findModelCountByQueryCriteria(query);
}
@Override
public byte[] findEditorSourceByModelId(String modelId) {
ModelEntity model = findById(modelId);
if (model == null || model.getEditorSourceValueId() == null) {
return null;
}
ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceValueId());
return ref.getBytes();
}
@Override | public byte[] findEditorSourceExtraByModelId(String modelId) {
ModelEntity model = findById(modelId);
if (model == null || model.getEditorSourceExtraValueId() == null) {
return null;
}
ByteArrayRef ref = new ByteArrayRef(model.getEditorSourceExtraValueId());
return ref.getBytes();
}
@Override
public List<Model> findModelsByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return modelDataManager.findModelsByNativeQuery(parameterMap, firstResult, maxResults);
}
@Override
public long findModelCountByNativeQuery(Map<String, Object> parameterMap) {
return modelDataManager.findModelCountByNativeQuery(parameterMap);
}
public ModelDataManager getModelDataManager() {
return modelDataManager;
}
public void setModelDataManager(ModelDataManager modelDataManager) {
this.modelDataManager = modelDataManager;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ModelEntityManagerImpl.java | 1 |
请完成以下Java代码 | public java.lang.String getPrintName ()
{
return (java.lang.String)get_Value(COLUMNNAME_PrintName);
}
/** Set Browse name.
@param WEBUI_NameBrowse Browse name */
@Override
public void setWEBUI_NameBrowse (java.lang.String WEBUI_NameBrowse)
{
set_Value (COLUMNNAME_WEBUI_NameBrowse, WEBUI_NameBrowse);
}
/** Get Browse name.
@return Browse name */
@Override
public java.lang.String getWEBUI_NameBrowse ()
{
return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameBrowse);
}
/** Set New record name.
@param WEBUI_NameNew New record name */
@Override
public void setWEBUI_NameNew (java.lang.String WEBUI_NameNew)
{
set_Value (COLUMNNAME_WEBUI_NameNew, WEBUI_NameNew);
}
/** Get New record name.
@return New record name */
@Override
public java.lang.String getWEBUI_NameNew ()
{
return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNew);
}
/** Set New record name (breadcrumb).
@param WEBUI_NameNewBreadcrumb New record name (breadcrumb) */
@Override
public void setWEBUI_NameNewBreadcrumb (java.lang.String WEBUI_NameNewBreadcrumb)
{
set_Value (COLUMNNAME_WEBUI_NameNewBreadcrumb, WEBUI_NameNewBreadcrumb);
} | /** Get New record name (breadcrumb).
@return New record name (breadcrumb) */
@Override
public java.lang.String getWEBUI_NameNewBreadcrumb ()
{
return (java.lang.String)get_Value(COLUMNNAME_WEBUI_NameNewBreadcrumb);
}
/**
* WidgetSize AD_Reference_ID=540724
* Reference name: WidgetSize_WEBUI
*/
public static final int WIDGETSIZE_AD_Reference_ID=540724;
/** Small = S */
public static final String WIDGETSIZE_Small = "S";
/** Medium = M */
public static final String WIDGETSIZE_Medium = "M";
/** Large = L */
public static final String WIDGETSIZE_Large = "L";
/** Set Widget size.
@param WidgetSize Widget size */
@Override
public void setWidgetSize (java.lang.String WidgetSize)
{
set_Value (COLUMNNAME_WidgetSize, WidgetSize);
}
/** Get Widget size.
@return Widget size */
@Override
public java.lang.String getWidgetSize ()
{
return (java.lang.String)get_Value(COLUMNNAME_WidgetSize);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Element.java | 1 |
请完成以下Java代码 | public class User {
private String id;
private String name;
private String email;
public User(String id, String name, String email) {
super();
this.id = id;
this.name = name;
this.email = email;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
} | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-basic-customization\src\main\java\com\baeldung\bootcustomfilters\model\User.java | 1 |
请完成以下Java代码 | public int getW_Store_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_W_Store_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set WebStore User.
@param WStoreUser
User ID of the Web Store EMail address
*/
public void setWStoreUser (String WStoreUser)
{
set_Value (COLUMNNAME_WStoreUser, WStoreUser);
}
/** Get WebStore User.
@return User ID of the Web Store EMail address
*/
public String getWStoreUser ()
{
return (String)get_Value(COLUMNNAME_WStoreUser); | }
/** Set WebStore Password.
@param WStoreUserPW
Password of the Web Store EMail address
*/
public void setWStoreUserPW (String WStoreUserPW)
{
set_Value (COLUMNNAME_WStoreUserPW, WStoreUserPW);
}
/** Get WebStore Password.
@return Password of the Web Store EMail address
*/
public String getWStoreUserPW ()
{
return (String)get_Value(COLUMNNAME_WStoreUserPW);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_W_Store.java | 1 |
请完成以下Java代码 | public List<User> executeList(CommandContext commandContext) {
return CommandContextUtil.getUserEntityManager(commandContext).findUserByQueryCriteria(this);
}
// getters //////////////////////////////////////////////////////////
@Override
public String getId() {
return id;
}
public List<String> getIds() {
return ids;
}
public String getIdIgnoreCase() {
return idIgnoreCase;
}
public String getFirstName() {
return firstName;
}
public String getFirstNameLike() {
return firstNameLike;
}
public String getFirstNameLikeIgnoreCase() {
return firstNameLikeIgnoreCase;
}
public String getLastName() {
return lastName;
}
public String getLastNameLike() {
return lastNameLike;
}
public String getLastNameLikeIgnoreCase() {
return lastNameLikeIgnoreCase;
}
public String getEmail() {
return email;
}
public String getEmailLike() {
return emailLike;
}
public String getGroupId() {
return groupId; | }
public List<String> getGroupIds() {
return groupIds;
}
public String getFullNameLike() {
return fullNameLike;
}
public String getFullNameLikeIgnoreCase() {
return fullNameLikeIgnoreCase;
}
public String getDisplayName() {
return displayName;
}
public String getDisplayNameLike() {
return displayNameLike;
}
public String getDisplayNameLikeIgnoreCase() {
return displayNameLikeIgnoreCase;
}
public String getTenantId() {
return tenantId;
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\UserQueryImpl.java | 1 |
请完成以下Java代码 | public String toString()
{
if (isNull())
{
return "NULL";
}
else if (isUnspecified())
{
return "UNSPECIFIED";
}
else
{
return String.valueOf(repoId);
}
}
@Override
@JsonValue
public int getRepoId()
{
if (isUnspecified())
{
throw Check.mkEx("Illegal call of getRepoId() on the unspecified CandidateId instance");
}
else if (isNull())
{
return -1;
}
else
{
return repoId;
}
} | public boolean isNull()
{
return repoId == IdConstants.NULL_REPO_ID;
}
public boolean isUnspecified()
{
return repoId == IdConstants.UNSPECIFIED_REPO_ID;
}
public boolean isRegular()
{
return !isNull() && !isUnspecified();
}
public static boolean isRegularNonNull(@Nullable final CandidateId candidateId)
{
return candidateId != null && candidateId.isRegular();
}
public void assertRegular()
{
if (!isRegular())
{
throw new AdempiereException("Expected " + this + " to be a regular ID");
}
}
public static boolean equals(@Nullable CandidateId id1, @Nullable CandidateId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\candidate\CandidateId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PmsPortalBrandServiceImpl implements PmsPortalBrandService {
@Autowired
private HomeDao homeDao;
@Autowired
private PmsBrandMapper brandMapper;
@Autowired
private PmsProductMapper productMapper;
@Override
public List<PmsBrand> recommendList(Integer pageNum, Integer pageSize) {
int offset = (pageNum - 1) * pageSize;
return homeDao.getRecommendBrandList(offset, pageSize);
}
@Override | public PmsBrand detail(Long brandId) {
return brandMapper.selectByPrimaryKey(brandId);
}
@Override
public CommonPage<PmsProduct> productList(Long brandId, Integer pageNum, Integer pageSize) {
PageHelper.startPage(pageNum,pageSize);
PmsProductExample example = new PmsProductExample();
example.createCriteria().andDeleteStatusEqualTo(0)
.andPublishStatusEqualTo(1)
.andBrandIdEqualTo(brandId);
List<PmsProduct> productList = productMapper.selectByExample(example);
return CommonPage.restPage(productList);
}
} | repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\PmsPortalBrandServiceImpl.java | 2 |
请完成以下Java代码 | public void extractDatabaseInfo() throws SQLException {
String productName = databaseMetaData.getDatabaseProductName();
String productVersion = databaseMetaData.getDatabaseProductVersion();
String driverName = databaseMetaData.getDriverName();
String driverVersion = databaseMetaData.getDriverVersion();
System.out.println(String.format("Product name:%s, Product version:%s", productName, productVersion));
System.out.println(String.format("Driver name:%s, Driver Version:%s", driverName, driverVersion));
}
public void extractUserName() throws SQLException {
String userName = databaseMetaData.getUserName();
System.out.println(userName);
try(ResultSet schemas = databaseMetaData.getSchemas()) {
while (schemas.next()) {
String table_schem = schemas.getString("TABLE_SCHEM");
String table_catalog = schemas.getString("TABLE_CATALOG"); | System.out.println(String.format("Table_schema:%s, Table_catalog:%s", table_schem, table_catalog));
}
}
}
public void extractSupportedFeatures() throws SQLException {
System.out.println("Supports scrollable & Updatable Result Set: " + databaseMetaData.supportsResultSetConcurrency(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE));
System.out.println("Supports Full Outer Joins: " + databaseMetaData.supportsFullOuterJoins());
System.out.println("Supports Stored Procedures: " + databaseMetaData.supportsStoredProcedures());
System.out.println("Supports Subqueries in 'EXISTS': " + databaseMetaData.supportsSubqueriesInExists());
System.out.println("Supports Transactions: " + databaseMetaData.supportsTransactions());
System.out.println("Supports Core SQL Grammar: " + databaseMetaData.supportsCoreSQLGrammar());
System.out.println("Supports Batch Updates: " + databaseMetaData.supportsBatchUpdates());
System.out.println("Supports Column Aliasing: " + databaseMetaData.supportsColumnAliasing());
System.out.println("Supports Savepoints: " + databaseMetaData.supportsSavepoints());
System.out.println("Supports Union All: " + databaseMetaData.supportsUnionAll());
System.out.println("Supports Union: " + databaseMetaData.supportsUnion());
}
} | repos\tutorials-master\persistence-modules\core-java-persistence-4\src\main\java\com\baeldung\jdbcmetadata\MetadataExtractor.java | 1 |
请完成以下Java代码 | public class GraphicInfo {
protected double x;
protected double y;
protected double height;
protected double width;
protected BaseElement element;
protected Boolean expanded;
protected int xmlRowNumber;
protected int xmlColumnNumber;
public double getX() {
return x;
}
public void setX(double x) {
this.x = x;
}
public double getY() {
return y;
}
public void setY(double y) {
this.y = y;
}
public double getHeight() {
return height;
}
public void setHeight(double height) {
this.height = height;
}
public double getWidth() {
return width;
}
public void setWidth(double width) { | this.width = width;
}
public Boolean getExpanded() {
return expanded;
}
public void setExpanded(Boolean expanded) {
this.expanded = expanded;
}
public BaseElement getElement() {
return element;
}
public void setElement(BaseElement element) {
this.element = element;
}
public int getXmlRowNumber() {
return xmlRowNumber;
}
public void setXmlRowNumber(int xmlRowNumber) {
this.xmlRowNumber = xmlRowNumber;
}
public int getXmlColumnNumber() {
return xmlColumnNumber;
}
public void setXmlColumnNumber(int xmlColumnNumber) {
this.xmlColumnNumber = xmlColumnNumber;
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\GraphicInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public long getMaxOplogSize() {
return this.maxOplogSize;
}
public void setMaxOplogSize(long maxOplogSize) {
this.maxOplogSize = maxOplogSize;
}
public int getQueueSize() {
return this.queueSize;
}
public void setQueueSize(int queueSize) {
this.queueSize = queueSize;
} | public long getTimeInterval() {
return this.timeInterval;
}
public void setTimeInterval(long timeInterval) {
this.timeInterval = timeInterval;
}
public int getWriteBufferSize() {
return this.writeBufferSize;
}
public void setWriteBufferSize(int writeBufferSize) {
this.writeBufferSize = writeBufferSize;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\DiskStoreProperties.java | 2 |
请完成以下Java代码 | public String getF_LOGPASS() {
return F_LOGPASS;
}
public void setF_LOGPASS(String f_LOGPASS) {
F_LOGPASS = f_LOGPASS;
}
public String getF_STARTDATE() {
return F_STARTDATE;
}
public void setF_STARTDATE(String f_STARTDATE) {
F_STARTDATE = f_STARTDATE;
}
public String getF_STOPDATE() {
return F_STOPDATE;
}
public void setF_STOPDATE(String f_STOPDATE) {
F_STOPDATE = f_STOPDATE;
}
public String getF_STATUS() {
return F_STATUS;
}
public void setF_STATUS(String f_STATUS) {
F_STATUS = f_STATUS;
}
public String getF_MEMO() {
return F_MEMO;
}
public void setF_MEMO(String f_MEMO) {
F_MEMO = f_MEMO;
}
public String getF_AUDITER() {
return F_AUDITER;
}
public void setF_AUDITER(String f_AUDITER) {
F_AUDITER = f_AUDITER;
}
public String getF_AUDITTIME() {
return F_AUDITTIME;
}
public void setF_AUDITTIME(String f_AUDITTIME) {
F_AUDITTIME = f_AUDITTIME;
}
public String getF_ISAUDIT() {
return F_ISAUDIT; | }
public void setF_ISAUDIT(String f_ISAUDIT) {
F_ISAUDIT = f_ISAUDIT;
}
public Timestamp getF_EDITTIME() {
return F_EDITTIME;
}
public void setF_EDITTIME(Timestamp f_EDITTIME) {
F_EDITTIME = f_EDITTIME;
}
public Integer getF_PLATFORM_ID() {
return F_PLATFORM_ID;
}
public void setF_PLATFORM_ID(Integer f_PLATFORM_ID) {
F_PLATFORM_ID = f_PLATFORM_ID;
}
public String getF_ISPRINTBILL() {
return F_ISPRINTBILL;
}
public void setF_ISPRINTBILL(String f_ISPRINTBILL) {
F_ISPRINTBILL = f_ISPRINTBILL;
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscExeOffice.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<ProactiveNotification> getProactiveNotification() {
if (proactiveNotification == null) {
proactiveNotification = new ArrayList<ProactiveNotification>();
}
return this.proactiveNotification;
}
/**
* Gets the value of the delivery property.
*
* @return
* possible object is
* {@link Delivery }
*
*/
public Delivery getDelivery() {
return delivery;
}
/**
* Sets the value of the delivery property.
*
* @param value
* allowed object is
* {@link Delivery }
*
*/
public void setDelivery(Delivery value) {
this.delivery = value;
}
/**
* Gets the value of the invoiceAddress property.
*
* @return
* possible object is
* {@link Address }
*
*/
public Address getInvoiceAddress() {
return invoiceAddress; | }
/**
* Sets the value of the invoiceAddress property.
*
* @param value
* allowed object is
* {@link Address }
*
*/
public void setInvoiceAddress(Address value) {
this.invoiceAddress = value;
}
/**
* Gets the value of the countrySpecificService property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCountrySpecificService() {
return countrySpecificService;
}
/**
* Sets the value of the countrySpecificService property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCountrySpecificService(String value) {
this.countrySpecificService = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ProductAndServiceData.java | 2 |
请完成以下Java代码 | protected void addSentryPart(CmmnSentryPart sentryPart) {
getCaseSentryParts().add((CaseSentryPartImpl) sentryPart);
}
protected CmmnSentryPart newSentryPart() {
return new CaseSentryPartImpl();
}
// new case executions ////////////////////////////////////////////////////////////
protected CaseExecutionImpl createCaseExecution(CmmnActivity activity) {
CaseExecutionImpl child = newCaseExecution();
// set activity to execute
child.setActivity(activity);
// handle child/parent-relation
child.setParent(this);
getCaseExecutionsInternal().add(child);
// set case instance
child.setCaseInstance(getCaseInstance());
// set case definition
child.setCaseDefinition(getCaseDefinition());
return child;
}
protected CaseExecutionImpl newCaseExecution() {
return new CaseExecutionImpl();
}
// variables //////////////////////////////////////////////////////////////
protected VariableStore<CoreVariableInstance> getVariableStore() {
return (VariableStore) variableStore;
}
@Override
protected VariableInstanceFactory<CoreVariableInstance> getVariableInstanceFactory() {
return (VariableInstanceFactory) SimpleVariableInstanceFactory.INSTANCE;
} | @Override
protected List<VariableInstanceLifecycleListener<CoreVariableInstance>> getVariableInstanceLifecycleListeners() {
return Collections.emptyList();
}
// toString /////////////////////////////////////////////////////////////////
public String toString() {
if (isCaseInstanceExecution()) {
return "CaseInstance[" + getToStringIdentity() + "]";
} else {
return "CmmnExecution["+getToStringIdentity() + "]";
}
}
protected String getToStringIdentity() {
return Integer.toString(System.identityHashCode(this));
}
public String getId() {
return String.valueOf(System.identityHashCode(this));
}
public ProcessEngineServices getProcessEngineServices() {
throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName());
}
public ProcessEngine getProcessEngine() {
throw LOG.unsupportedTransientOperationException(ProcessEngineServicesAware.class.getName());
}
public CmmnElement getCmmnModelElementInstance() {
throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName());
}
public CmmnModelInstance getCmmnModelInstance() {
throw LOG.unsupportedTransientOperationException(CmmnModelExecutionContext.class.getName());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\execution\CaseExecutionImpl.java | 1 |
请完成以下Java代码 | public List<Queue> findAllByTenantId(TenantId tenantId) {
List<QueueEntity> entities = queueRepository.findByTenantId(tenantId.getId());
return DaoUtil.convertDataList(entities);
}
@Override
public List<Queue> findAllMainQueues() {
List<QueueEntity> entities = Lists.newArrayList(queueRepository.findAllByName(DataConstants.MAIN_QUEUE_NAME));
return DaoUtil.convertDataList(entities);
}
@Override
public List<Queue> findAllQueues() {
List<QueueEntity> entities = Lists.newArrayList(queueRepository.findAll());
return DaoUtil.convertDataList(entities);
}
@Override
public PageData<Queue> findQueuesByTenantId(TenantId tenantId, PageLink pageLink) { | return DaoUtil.toPageData(queueRepository
.findByTenantId(tenantId.getId(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<Queue> findAllByTenantId(TenantId tenantId, PageLink pageLink) {
return findQueuesByTenantId(tenantId, pageLink);
}
@Override
public EntityType getEntityType() {
return EntityType.QUEUE;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\queue\JpaQueueDao.java | 1 |
请完成以下Java代码 | public DmnDecisionResult evaluateDecision(DmnDecision decision, Map<String, Object> variables) {
ensureNotNull("decision", decision);
ensureNotNull("variables", variables);
return evaluateDecision(decision, Variables.fromMap(variables).asVariableContext());
}
public DmnDecisionResult evaluateDecision(DmnDecision decision, VariableContext variableContext) {
ensureNotNull("decision", decision);
ensureNotNull("variableContext", variableContext);
if (decision instanceof DmnDecisionImpl) {
DefaultDmnDecisionContext decisionContext = new DefaultDmnDecisionContext(dmnEngineConfiguration);
return decisionContext.evaluateDecision(decision, variableContext);
}
else {
throw LOG.decisionTypeNotSupported(decision);
}
}
public DmnDecisionResult evaluateDecision(String decisionKey, InputStream inputStream, Map<String, Object> variables) {
ensureNotNull("variables", variables);
return evaluateDecision(decisionKey, inputStream, Variables.fromMap(variables).asVariableContext());
}
public DmnDecisionResult evaluateDecision(String decisionKey, InputStream inputStream, VariableContext variableContext) {
ensureNotNull("decisionKey", decisionKey);
List<DmnDecision> decisions = parseDecisions(inputStream);
for (DmnDecision decision : decisions) {
if (decisionKey.equals(decision.getKey())) {
return evaluateDecision(decision, variableContext);
}
}
throw LOG.unableToFindDecisionWithKey(decisionKey);
} | public DmnDecisionResult evaluateDecision(String decisionKey, DmnModelInstance dmnModelInstance, Map<String, Object> variables) {
ensureNotNull("variables", variables);
return evaluateDecision(decisionKey, dmnModelInstance, Variables.fromMap(variables).asVariableContext());
}
public DmnDecisionResult evaluateDecision(String decisionKey, DmnModelInstance dmnModelInstance, VariableContext variableContext) {
ensureNotNull("decisionKey", decisionKey);
List<DmnDecision> decisions = parseDecisions(dmnModelInstance);
for (DmnDecision decision : decisions) {
if (decisionKey.equals(decision.getKey())) {
return evaluateDecision(decision, variableContext);
}
}
throw LOG.unableToFindDecisionWithKey(decisionKey);
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DefaultDmnEngine.java | 1 |
请完成以下Java代码 | private I_M_InOutLine getCreateInOutLine(final I_M_InOutLine originInOutLine, final ProductId productId)
{
final I_M_InOut inout = getM_InOut();
if (inout.getM_InOut_ID() <= 0)
{
// nothing created
return null;
}
//
// Check if we already have a movement line for our key
final ArrayKey inOutLineKey = mkInOutLineKey(originInOutLine, productId);
final I_M_InOutLine existingInOutLine = _inOutLines.get(inOutLineKey);
// return the existing inout line if found
if (existingInOutLine != null)
{
return existingInOutLine;
}
// #1306 verify if the origin line belongs to the manually created return ( _inOutRef)
if (originInOutLine.getM_InOut_ID() == inout.getM_InOut_ID())
{
_inOutLines.put(inOutLineKey, originInOutLine);
return originInOutLine;
}
//
// Create a new inOut line for the product
final I_M_InOutLine newInOutLine = inOutBL.newInOutLine(inout, I_M_InOutLine.class);
newInOutLine.setAD_Org_ID(inout.getAD_Org_ID());
newInOutLine.setM_InOut_ID(inout.getM_InOut_ID());
newInOutLine.setM_Product_ID(originInOutLine.getM_Product_ID());
newInOutLine.setC_UOM_ID(originInOutLine.getC_UOM_ID());
newInOutLine.setReturn_Origin_InOutLine(originInOutLine);
// make sure the attributes in the return line is the same as in the origin line
asiBL.cloneASI(newInOutLine, originInOutLine);
// NOTE: we are not saving the inOut line
//
// Add the movement line to our map (to not created it again)
_inOutLines.put(inOutLineKey, newInOutLine);
return newInOutLine;
}
@Nullable | private I_M_InOutLine getCreateInOutLineInDispute(final I_M_InOutLine originInOutLine, final ProductId productId)
{
final I_M_InOutLine originInOutLineInDispute = InterfaceWrapperHelper.create(inOutDAO.retrieveLineWithQualityDiscount(originInOutLine), I_M_InOutLine.class);
if (originInOutLineInDispute == null)
{
return null;
}
final I_M_InOutLine inoutLineInDispute = getCreateInOutLine(originInOutLineInDispute, productId);
inoutLineInDispute.setIsInDispute(true);
inoutLineInDispute.setQualityDiscountPercent(originInOutLineInDispute.getQualityDiscountPercent());
inoutLineInDispute.setQualityNote(originInOutLineInDispute.getQualityNote());
return inoutLineInDispute;
}
public Collection<I_M_InOutLine> getInOutLines()
{
return _inOutLines.values();
}
/**
* Make a unique key for the given product. This will serve in mapping the inout lines to their products.
*/
private static ArrayKey mkInOutLineKey(final I_M_InOutLine originInOutLine, @NonNull final ProductId productId)
{
return Util.mkKey(originInOutLine.getM_InOutLine_ID(), productId);
}
public boolean isEmpty()
{
return _inOutLines.isEmpty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\AbstractQualityReturnsInOutLinesBuilder.java | 1 |
请完成以下Java代码 | public String index(OAuth2AuthenticationToken authenticationToken) {
OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();
String response = "Hello, " + authenticationToken.getPrincipal().getName();
response += "</br></br>";
response += "Here is your accees token :</br>" + oAuth2AccessToken.getTokenValue();
response += "</br>";
response += "</br>You can use it to call these Resource Server APIs:";
response += "</br></br>";
response += "<a href='/read'>Call Resource Server Read API</a>";
response += "</br>";
response += "<a href='/write'>Call Resource Server Write API</a>";
return response;
}
@RequestMapping("/read")
public String read(OAuth2AuthenticationToken authenticationToken) {
String url = remoteResourceServer + "/read";
return callResourceServer(authenticationToken, url);
}
@RequestMapping("/write")
public String write(OAuth2AuthenticationToken authenticationToken) {
String url = remoteResourceServer + "/write";
return callResourceServer(authenticationToken, url); | }
private String callResourceServer(OAuth2AuthenticationToken authenticationToken, String url) {
OAuth2AuthorizedClient oAuth2AuthorizedClient = this.authorizedClientService.loadAuthorizedClient(authenticationToken.getAuthorizedClientRegistrationId(), authenticationToken.getName());
OAuth2AccessToken oAuth2AccessToken = oAuth2AuthorizedClient.getAccessToken();
HttpHeaders headers = new HttpHeaders();
headers.add("Authorization", "Bearer " + oAuth2AccessToken.getTokenValue());
HttpEntity<String> entity = new HttpEntity<>("parameters", headers);
ResponseEntity<String> responseEntity = null;
String response = null;
try {
responseEntity = restTemplate.exchange(url, HttpMethod.GET, entity, String.class);
response = responseEntity.getBody();
} catch (HttpClientErrorException e) {
response = e.getMessage();
}
return response;
}
} | repos\tutorials-master\security-modules\cloud-foundry-uaa\cf-uaa-oauth2-client\src\main\java\com\baeldung\cfuaa\oauth2\client\CFUAAOAuth2ClientController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String generatePasswordResetKey(final String email)
{
final User user = getUserByMail(email);
if (user == null)
{
throw new PasswordResetFailedException(i18n.get("LoginService.error.emailNotRegistered"));
}
//
// Generate a password reset key and set it on user
final String passwordResetKey = UUID.randomUUID().toString().replace("-", "");
user.setPasswordResetKey(passwordResetKey);
userRepository.save(user);
return passwordResetKey;
}
@Override
@Transactional
public User resetPassword(final String passwordResetKey)
{
final User user = getUserByPasswordResetKey(passwordResetKey);
if (user == null)
{
throw new PasswordResetFailedException(i18n.get("LoginService.error.invalidPasswordResetKey"));
}
final String passwordNew = generatePassword();
user.setPassword(passwordNew);
user.setPasswordResetKey(null);
userRepository.save(user);
senderToMetasfreshService.syncAfterCommit().add(user); | return user;
}
private String generatePassword()
{
final StringBuilder password = new StringBuilder();
final SecureRandom random = new SecureRandom();
final int poolLength = PASSWORD_CHARS.length();
for (int i = 0; i < PASSWORD_Length; i++)
{
final int charIndex = random.nextInt(poolLength);
final char ch = PASSWORD_CHARS.charAt(charIndex);
password.append(ch);
}
return password.toString();
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\impl\LoginService.java | 2 |
请完成以下Java代码 | private DocumentFilterList getStickyFilters()
{
return stickyFilters != null ? stickyFilters : DocumentFilterList.EMPTY;
}
public HUEditorViewBuilder setFilters(final DocumentFilterList filters)
{
this.filters = filters;
return this;
}
DocumentFilterList getFilters()
{
return filters != null ? filters : DocumentFilterList.EMPTY;
}
public HUEditorViewBuilder orderBy(@NonNull final DocumentQueryOrderBy orderBy)
{
if (orderBys == null)
{
orderBys = new ArrayList<>();
}
orderBys.add(orderBy);
return this;
}
public HUEditorViewBuilder orderBys(@NonNull final DocumentQueryOrderByList orderBys)
{
this.orderBys = new ArrayList<>(orderBys.toList());
return this;
}
public HUEditorViewBuilder clearOrderBys()
{
this.orderBys = null;
return this;
}
private DocumentQueryOrderByList getOrderBys()
{
return DocumentQueryOrderByList.ofList(orderBys);
}
public HUEditorViewBuilder setParameter(final String name, @Nullable final Object value)
{
if (value == null)
{
if (parameters != null)
{
parameters.remove(name);
}
}
else
{
if (parameters == null)
{
parameters = new LinkedHashMap<>();
}
parameters.put(name, value);
}
return this;
}
public HUEditorViewBuilder setParameters(final Map<String, Object> parameters)
{
parameters.forEach(this::setParameter);
return this;
} | ImmutableMap<String, Object> getParameters()
{
return parameters != null ? ImmutableMap.copyOf(parameters) : ImmutableMap.of();
}
@Nullable
public <T> T getParameter(@NonNull final String name)
{
if (parameters == null)
{
return null;
}
@SuppressWarnings("unchecked") final T value = (T)parameters.get(name);
return value;
}
public void assertParameterSet(final String name)
{
final Object value = getParameter(name);
if (value == null)
{
throw new AdempiereException("Parameter " + name + " is expected to be set in " + parameters + " for " + this);
}
}
public HUEditorViewBuilder setHUEditorViewRepository(final HUEditorViewRepository huEditorViewRepository)
{
this.huEditorViewRepository = huEditorViewRepository;
return this;
}
HUEditorViewBuffer createRowsBuffer(@NonNull final SqlDocumentFilterConverterContext context)
{
final ViewId viewId = getViewId();
final DocumentFilterList stickyFilters = getStickyFilters();
final DocumentFilterList filters = getFilters();
if (HUEditorViewBuffer_HighVolume.isHighVolume(stickyFilters))
{
return new HUEditorViewBuffer_HighVolume(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context);
}
else
{
return new HUEditorViewBuffer_FullyCached(viewId, huEditorViewRepository, stickyFilters, filters, getOrderBys(), context);
}
}
public HUEditorViewBuilder setUseAutoFilters(final boolean useAutoFilters)
{
this.useAutoFilters = useAutoFilters;
return this;
}
public boolean isUseAutoFilters()
{
return useAutoFilters;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorViewBuilder.java | 1 |
请完成以下Java代码 | protected TbActorRef getOrCreateActor(RuleChainId ruleChainId) {
return getOrCreateActor(ruleChainId, eId -> ruleChainService.findRuleChainById(TenantId.SYS_TENANT_ID, eId));
}
protected TbActorRef getOrCreateActor(RuleChainId ruleChainId, Function<RuleChainId, RuleChain> provider) {
return ctx.getOrCreateChildActor(new TbEntityActorId(ruleChainId),
() -> DefaultActorService.RULE_DISPATCHER_NAME,
() -> {
RuleChain ruleChain = provider.apply(ruleChainId);
if (ruleChain == null) {
return new RuleChainErrorActor.ActorCreator(systemContext, tenantId, ruleChainId,
new RuleEngineException("Rule Chain with id: " + ruleChainId + " not found!"));
} else {
return new RuleChainActor.ActorCreator(systemContext, tenantId, ruleChain);
} | },
() -> true);
}
protected TbActorRef getEntityActorRef(EntityId entityId) {
TbActorRef target = null;
if (entityId.getEntityType() == EntityType.RULE_CHAIN) {
target = getOrCreateActor((RuleChainId) entityId);
}
return target;
}
protected void broadcast(TbActorMsg msg) {
ctx.broadcastToChildren(msg, new TbEntityTypeActorIdPredicate(EntityType.RULE_CHAIN));
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\RuleChainManagerActor.java | 1 |
请完成以下Java代码 | public Integer visitAddSub(LabeledExprParser.AddSubContext ctx) {
int left = visit(ctx.expr(0)); // get value of left subexpression
int right = visit(ctx.expr(1)); // get value of right subexpression
if (ctx.op.getType() == LabeledExprParser.ADD) return left + right;
return left - right; // must be SUB
}
/** expr : INT */
@Override
public Integer visitInt(LabeledExprParser.IntContext ctx) {
return Integer.valueOf(ctx.INT().getText());
}
/** expr : ID */
@Override
public Integer visitId(LabeledExprParser.IdContext ctx) { | String id = ctx.ID().getText();
if (memory.containsKey(id)) return memory.get(id);
return 0; // default value if the variable is not found
}
/** expr : '(' expr ')' */
@Override
public Integer visitParens(LabeledExprParser.ParensContext ctx) {
return visit(ctx.expr()); // return child expr's value
}
/** stat : NEWLINE */
@Override
public Integer visitBlank(LabeledExprParser.BlankContext ctx) {
return 0; // return dummy value
}
} | repos\springboot-demo-master\ANTLR\src\main\java\com\et\antlr\EvalVisitor.java | 1 |
请完成以下Spring Boot application配置 | spring.sql.init.platform=postgre
spring.datasource.url=jdbc:postgresql://localhost:5432/jdbc_authentication
spring.datasource.username=postgres
spring.datasource.passw | ord=pass
spring.sql.init.mode=always
spring.jpa.hibernate.ddl-auto=none | repos\tutorials-master\spring-security-modules\spring-security-web-boot-2\src\main\resources\application-postgre.properties | 2 |
请完成以下Java代码 | private POSPayment processPOSPayment_CARD(
@NonNull final POSPayment posPayment,
@NonNull final POSOrder posOrder)
{
posPayment.getPaymentMethod().assertCard();
final POSTerminal posTerminal = posTerminalService.getPOSTerminalById(posOrder.getPosTerminalId());
final POSTerminalPaymentProcessorConfig paymentProcessorConfig = posTerminal.getPaymentProcessorConfigNotNull();
final POSPaymentProcessResponse processResponse = posPaymentProcessorService.processPayment(POSPaymentProcessRequest.builder()
.paymentProcessorConfig(paymentProcessorConfig)
.clientAndOrgId(posOrder.getClientAndOrgId())
.posOrderAndPaymentId(POSOrderAndPaymentId.of(posOrder.getLocalIdNotNull(), posPayment.getLocalIdNotNull()))
.amount(posPayment.getAmount().toAmount(moneyService::getCurrencyCodeByCurrencyId))
.build());
return posPayment.changingStatusFromRemote(processResponse);
}
public POSPayment refundPOSPayment(@NonNull final POSPayment posPaymentToProcess, @NonNull POSOrderId posOrderId, @NonNull final POSTerminalPaymentProcessorConfig paymentProcessorConfig)
{
posPaymentToProcess.assertAllowRefund();
POSPayment posPayment = posPaymentToProcess;
//
// Reverse payment
// (usually this field is not populated at this moment)
// TODO run this async!
if (posPayment.getPaymentReceiptId() != null)
{ | paymentBL.reversePaymentById(posPayment.getPaymentReceiptId());
posPayment = posPayment.withPaymentReceipt(null);
}
//
// Ask payment processor to refund
final POSPaymentProcessResponse refundResponse = posPaymentProcessorService.refund(
POSRefundRequest.builder()
.paymentProcessorConfig(paymentProcessorConfig)
.posOrderAndPaymentId(POSOrderAndPaymentId.of(posOrderId, posPayment.getLocalIdNotNull()))
.build()
);
posPayment = posPayment.changingStatusFromRemote(refundResponse);
return posPayment;
}
public void scheduleCreateSalesOrderInvoiceAndShipment(@NonNull final POSOrderId posOrderId, @NonNull final UserId cashierId)
{
final UserId adUserId = Env.getLoggedUserIdIfExists().orElse(cashierId);
try (IAutoCloseable ignored = Env.temporaryChangeLoggedUserId(adUserId))
{
workPackageQueueFactory.getQueueForEnqueuing(Env.getCtx(), C_POSOrder_CreateInvoiceAndShipment.class)
.newWorkPackage()
.addElement(TableRecordReference.of(I_C_POS_Order.Table_Name, posOrderId))
.bindToThreadInheritedTrx()
.buildAndEnqueue();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSOrderProcessingServices.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class Embedded {
/**
* Whether to enable embedded mode if the ActiveMQ Broker is available.
*/
private boolean enabled = true;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public static class Packages {
/**
* Whether to trust all packages.
*/
private @Nullable Boolean trustAll; | /**
* List of specific packages to trust (when not trusting all packages).
*/
private List<String> trusted = new ArrayList<>();
public @Nullable Boolean getTrustAll() {
return this.trustAll;
}
public void setTrustAll(@Nullable Boolean trustAll) {
this.trustAll = trustAll;
}
public List<String> getTrusted() {
return this.trusted;
}
public void setTrusted(List<String> trusted) {
this.trusted = trusted;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-activemq\src\main\java\org\springframework\boot\activemq\autoconfigure\ActiveMQProperties.java | 2 |
请完成以下Java代码 | public class CodeGenerator {
public static void generate() throws IOException {
Consumer<MethodBuilder> calculateAnnualBonusBuilder = methodBuilder -> methodBuilder.withCode(codeBuilder -> {
Label notSales = codeBuilder.newLabel();
Label notEngineer = codeBuilder.newLabel();
ClassDesc stringClass = ClassDesc.of("java.lang.String");
codeBuilder.aload(3)
.ldc("sales")
.invokevirtual(stringClass, "equals", MethodTypeDesc.of(ClassDesc.of("Z"), stringClass))
.ifeq(notSales)
.dload(1)
.ldc(0.35)
.dmul()
.dreturn()
.labelBinding(notSales)
.aload(3)
.ldc("engineer")
.invokevirtual(stringClass, "equals", MethodTypeDesc.of(ClassDesc.of("Z"), stringClass))
.ifeq(notEngineer)
.dload(1)
.ldc(0.25)
.dmul()
.dreturn()
.labelBinding(notEngineer)
.dload(1)
.ldc(0.15)
.dmul()
.dreturn();
});
var classBuilder = ClassFile.of()
.build(ClassDesc.of("EmployeeSalaryCalculator"),
cb -> cb.withMethod("calculateAnnualBonus", MethodTypeDesc.of(CD_double, CD_double, CD_String), AccessFlag.PUBLIC.mask(),
calculateAnnualBonusBuilder)); | Files.write(Path.of("EmployeeSalaryCalculator.class"), classBuilder);
}
public static void transform() throws IOException {
var basePath = Files.readAllBytes(Path.of("EmployeeSalaryCalculator.class"));
CodeTransform codeTransform = ClassFileBuilder::accept;
MethodTransform methodTransform = MethodTransform.transformingCode(codeTransform);
ClassTransform classTransform = ClassTransform.transformingMethods(methodTransform);
ClassFile classFile = ClassFile.of();
byte[] transformedClass = classFile.transformClass(classFile.parse(basePath), classTransform);
Files.write(Path.of("TransformedEmployeeSalaryCalculator.class"), transformedClass);
}
public static void main(String[] args) throws IOException {
generate();
transform();
}
} | repos\tutorials-master\core-java-modules\core-java-24\src\main\java\com\baeldung\classfiles\CodeGenerator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<SysUser> findAll() {
return sysUserRepository.findAll();
}
@Override
public SysUser findById(Long id) {
return sysUserRepository.findById(id).orElseThrow(() -> new RuntimeException("找不到用户"));
}
@Override
public void createUser(SysUser sysUser) {
sysUser.setId(null);
sysUserRepository.save(sysUser);
}
@Override
public void updateUser(SysUser sysUser) {
sysUser.setPassword(null);
sysUserRepository.save(sysUser); | }
@Override
public void updatePassword(Long id, String password) {
SysUser exist = findById(id);
exist.setPassword(passwordEncoder.encode(password));
sysUserRepository.save(exist);
}
@Override
public void deleteUser(Long id) {
sysUserRepository.deleteById(id);
}
} | repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\service\impl\SysUserServiceImpl.java | 2 |
请完成以下Java代码 | public String getTableName(Class<?> entityClass, boolean withPrefix) {
String databaseTablePrefix = getDbSqlSession().getDbSqlSessionFactory().getDatabaseTablePrefix();
String tableName = null;
if (DbEntity.class.isAssignableFrom(entityClass)) {
tableName = persistentObjectToTableNameMap.get(entityClass);
}
else {
tableName = apiTypeToTableNameMap.get(entityClass);
}
if (withPrefix) {
return databaseTablePrefix + tableName;
}
else {
return tableName;
}
}
public TableMetaData getTableMetaData(String tableName) {
TableMetaData result = new TableMetaData();
ResultSet resultSet = null;
try {
try {
result.setTableName(tableName);
DatabaseMetaData metaData = getDbSqlSession()
.getSqlSession()
.getConnection()
.getMetaData();
if (DatabaseUtil.checkDatabaseType(DbSqlSessionFactory.POSTGRES)) {
tableName = tableName.toLowerCase();
}
String databaseSchema = getDbSqlSession().getDbSqlSessionFactory().getDatabaseSchema();
tableName = getDbSqlSession().prependDatabaseTablePrefix(tableName);
resultSet = metaData.getColumns(null, databaseSchema, tableName, null); | while(resultSet.next()) {
String name = resultSet.getString("COLUMN_NAME").toUpperCase();
String type = resultSet.getString("TYPE_NAME").toUpperCase();
result.addColumnMetaData(name, type);
}
} catch (SQLException se) {
throw se;
} finally {
if (resultSet != null) {
resultSet.close();
}
}
} catch (Exception e) {
throw LOG.retrieveMetadataException(e);
}
if(result.getColumnNames().size() == 0) {
// According to API, when a table doesn't exist, null should be returned
result = null;
}
return result;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TableDataManager.java | 1 |
请完成以下Java代码 | public class ServletContextApplicationContextInitializer
implements ApplicationContextInitializer<ConfigurableWebApplicationContext>, Ordered {
private int order = Ordered.HIGHEST_PRECEDENCE;
private final ServletContext servletContext;
private final boolean addApplicationContextAttribute;
/**
* Create a new {@link ServletContextApplicationContextInitializer} instance.
* @param servletContext the servlet that should be ultimately set.
*/
public ServletContextApplicationContextInitializer(ServletContext servletContext) {
this(servletContext, false);
}
/**
* Create a new {@link ServletContextApplicationContextInitializer} instance.
* @param servletContext the servlet that should be ultimately set.
* @param addApplicationContextAttribute if the {@link ApplicationContext} should be
* stored as an attribute in the {@link ServletContext}
* @since 1.3.4
*/
public ServletContextApplicationContextInitializer(ServletContext servletContext,
boolean addApplicationContextAttribute) {
this.servletContext = servletContext;
this.addApplicationContextAttribute = addApplicationContextAttribute; | }
public void setOrder(int order) {
this.order = order;
}
@Override
public int getOrder() {
return this.order;
}
@Override
public void initialize(ConfigurableWebApplicationContext applicationContext) {
applicationContext.setServletContext(this.servletContext);
if (this.addApplicationContextAttribute) {
this.servletContext.setAttribute(WebApplicationContext.ROOT_WEB_APPLICATION_CONTEXT_ATTRIBUTE,
applicationContext);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\web\servlet\support\ServletContextApplicationContextInitializer.java | 1 |
请完成以下Java代码 | public int getC_Flatrate_Conditions_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Flatrate_Conditions_ID);
}
@Override
public void setC_Flatrate_Matching_ID (final int C_Flatrate_Matching_ID)
{
if (C_Flatrate_Matching_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Flatrate_Matching_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Flatrate_Matching_ID, C_Flatrate_Matching_ID);
}
@Override
public int getC_Flatrate_Matching_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Flatrate_Matching_ID);
}
@Override
public de.metas.contracts.model.I_C_Flatrate_Transition getC_Flatrate_Transition()
{
return get_ValueAsPO(COLUMNNAME_C_Flatrate_Transition_ID, de.metas.contracts.model.I_C_Flatrate_Transition.class);
}
@Override
public void setC_Flatrate_Transition(final de.metas.contracts.model.I_C_Flatrate_Transition C_Flatrate_Transition)
{
set_ValueFromPO(COLUMNNAME_C_Flatrate_Transition_ID, de.metas.contracts.model.I_C_Flatrate_Transition.class, C_Flatrate_Transition);
}
@Override
public void setC_Flatrate_Transition_ID (final int C_Flatrate_Transition_ID)
{
if (C_Flatrate_Transition_ID < 1)
set_Value (COLUMNNAME_C_Flatrate_Transition_ID, null);
else
set_Value (COLUMNNAME_C_Flatrate_Transition_ID, C_Flatrate_Transition_ID);
}
@Override
public int getC_Flatrate_Transition_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Flatrate_Transition_ID);
}
@Override
public void setM_PricingSystem_ID (final int M_PricingSystem_ID)
{
if (M_PricingSystem_ID < 1)
set_Value (COLUMNNAME_M_PricingSystem_ID, null);
else
set_Value (COLUMNNAME_M_PricingSystem_ID, M_PricingSystem_ID);
}
@Override
public int getM_PricingSystem_ID()
{
return get_ValueAsInt(COLUMNNAME_M_PricingSystem_ID);
}
@Override
public void setM_Product_Category_Matching_ID (final int M_Product_Category_Matching_ID)
{ | if (M_Product_Category_Matching_ID < 1)
set_Value (COLUMNNAME_M_Product_Category_Matching_ID, null);
else
set_Value (COLUMNNAME_M_Product_Category_Matching_ID, M_Product_Category_Matching_ID);
}
@Override
public int getM_Product_Category_Matching_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_Category_Matching_ID);
}
@Override
public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setQtyPerDelivery (final BigDecimal QtyPerDelivery)
{
set_Value (COLUMNNAME_QtyPerDelivery, QtyPerDelivery);
}
@Override
public BigDecimal getQtyPerDelivery()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPerDelivery);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Flatrate_Matching.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ResponseHeaderController {
@GetMapping("/http-servlet-response")
public String usingHttpServletResponse(HttpServletResponse response) {
response.addHeader("Baeldung-Example-Header", "Value-HttpServletResponse");
return "Response with header using HttpServletResponse";
}
@GetMapping("/response-entity-constructor")
public ResponseEntity<String> usingResponseEntityConstructor() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityContructor");
String responseBody = "Response with header using ResponseEntity (constructor)";
HttpStatus responseStatus = HttpStatus.OK;
return new ResponseEntity<String>(responseBody, responseHeaders, responseStatus);
}
@GetMapping("/response-entity-contructor-multiple-headers")
public ResponseEntity<String> usingResponseEntityConstructorAndMultipleHeaders() {
List<MediaType> acceptableMediaTypes = new ArrayList<>(Arrays.asList(MediaType.APPLICATION_JSON));
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityConstructorAndHeaders");
responseHeaders.setAccept(acceptableMediaTypes);
String responseBody = "Response with header using ResponseEntity (constructor)";
HttpStatus responseStatus = HttpStatus.OK; | return new ResponseEntity<String>(responseBody, responseHeaders, responseStatus);
}
@GetMapping("/response-entity-builder")
public ResponseEntity<String> usingResponseEntityBuilder() {
String responseHeaderKey = "Baeldung-Example-Header";
String responseHeaderValue = "Value-ResponseEntityBuilder";
String responseBody = "Response with header using ResponseEntity (builder)";
return ResponseEntity.ok()
.header(responseHeaderKey, responseHeaderValue)
.body(responseBody);
}
@GetMapping("/response-entity-builder-with-http-headers")
public ResponseEntity<String> usingResponseEntityBuilderAndHttpHeaders() {
HttpHeaders responseHeaders = new HttpHeaders();
responseHeaders.set("Baeldung-Example-Header", "Value-ResponseEntityBuilderWithHttpHeaders");
String responseBody = "Response with header using ResponseEntity (builder)";
return ResponseEntity.ok()
.headers(responseHeaders)
.body(responseBody);
}
} | repos\tutorials-master\spring-web-modules\spring-rest-http\src\main\java\com\baeldung\responseheaders\controllers\ResponseHeaderController.java | 2 |
请完成以下Java代码 | public class OrderLineReceiptScheduleListener extends ReceiptScheduleListenerAdapter
{
public static final OrderLineReceiptScheduleListener INSTANCE = new OrderLineReceiptScheduleListener();
private final IOrderBL orderBL = Services.get(IOrderBL.class);
private final IInvoiceCandBL invoiceCandBL = Services.get(IInvoiceCandBL.class);
private OrderLineReceiptScheduleListener()
{
}
/**
* If a receipt schedule is closed then this method retrieves its <code>orderLine</code> and invokes {@link IOrderBL#closeLine(I_C_OrderLine)} on it.
*
* @task 08452
*/
@Override
public void onAfterClose(final I_M_ReceiptSchedule receiptSchedule)
{
final I_C_OrderLine orderLine = receiptSchedule.getC_OrderLine();
if (orderLine == null)
{
return; // shall not happen
}
orderBL.closeLine(orderLine);
invoiceCandBL.closeDeliveryInvoiceCandidatesByOrderLineId(OrderLineId.ofRepoId(orderLine.getC_OrderLine_ID()));
}
/**
* If a receipt schedule is reopened then this method retrieves its <code>orderLine</code> and invokes {@link IOrderBL#reopenLine(I_C_OrderLine)} on it.
* <p>
* Note: we open the order line <b>after</b> the reopen,
* because this reopening will cause a synchronous updating of the receipt schedule via the {@link IReceiptScheduleProducer} framework
* and the <code>receiptSchedule</code> that is to be reopened uses the order line's <code>QtyOrdered</code> value. | *
* @task <a href="https://github.com/metasfresh/metasfresh/issues/315">issue #315</a>
*/
@Override
public void onAfterReopen(final I_M_ReceiptSchedule receiptSchedule)
{
final I_C_OrderLine orderLine = receiptSchedule.getC_OrderLine();
if (orderLine == null)
{
return; // shall not happen
}
orderBL.reopenLine(orderLine);
invoiceCandBL.openDeliveryInvoiceCandidatesByOrderLineId(OrderLineId.ofRepoId(orderLine.getC_OrderLine_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\OrderLineReceiptScheduleListener.java | 1 |
请完成以下Java代码 | protected Properties getCtx()
{
return m_ctx;
}
@Override
public int getColumnCount()
{
try
{
return m_resultSet.getMetaData().getColumnCount();
}
catch (SQLException e)
{
throw DBException.wrapIfNeeded(e);
}
}
@Override
public int getDisplayType(final int IGNORED, final int col)
{
final Object value = getValue(col);
return CellValues.extractDisplayTypeFromValue(value);
}
@Override
public List<CellValue> getHeaderNames()
{
final List<String> headerNames = new ArrayList<>();
if (m_columnHeaders == null || m_columnHeaders.isEmpty())
{
// use the next data row; can be the first, but if we add another sheet, it can also be another one.
final List<Object> currentRow = getNextRawDataRow();
for (Object headerNameObj : currentRow)
{
headerNames.add(headerNameObj != null ? headerNameObj.toString() : null);
}
}
else
{
headerNames.addAll(m_columnHeaders);
}
final ArrayList<CellValue> result = new ArrayList<>();
final String adLanguage = getLanguage().getAD_Language();
for (final String rawHeaderName : headerNames)
{
final String headerName;
if (translateHeaders)
{
headerName = msgBL.translatable(rawHeaderName).translate(adLanguage);
}
else
{
headerName = rawHeaderName;
}
result.add(CellValues.toCellValue(headerName));
}
return result;
}
private Object getValue(final int col)
{
try
{
return m_resultSet.getObject(col + 1);
}
catch (SQLException e)
{
throw DBException.wrapIfNeeded(e);
}
}
@Override
public int getRowCount()
{
return -1; // TODO remove
}
@Override
public boolean isColumnPrinted(final int col)
{
return true;
}
@Override
public boolean isFunctionRow(final int row)
{
return false;
}
@Override | public boolean isPageBreak(final int row, final int col)
{
return false;
}
@Override
protected List<CellValue> getNextRow()
{
return CellValues.toCellValues(getNextRawDataRow());
}
private List<Object> getNextRawDataRow()
{
try
{
final List<Object> row = new ArrayList<>();
for (int col = 1; col <= getColumnCount(); col++)
{
final Object o = m_resultSet.getObject(col);
row.add(o);
}
noDataAddedYet = false;
return row;
}
catch (final SQLException e)
{
throw DBException.wrapIfNeeded(e);
}
}
@Override
protected boolean hasNextRow()
{
try
{
return m_resultSet.next();
}
catch (SQLException e)
{
throw DBException.wrapIfNeeded(e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\excel\JdbcExcelExporter.java | 1 |
请完成以下Java代码 | public void setAD_OrgTo_ID (int AD_OrgTo_ID)
{
if (AD_OrgTo_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_OrgTo_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_OrgTo_ID, Integer.valueOf(AD_OrgTo_ID));
}
/** Get Inter-Organization.
@return Organization valid for intercompany documents
*/
public int getAD_OrgTo_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_OrgTo_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_AcctSchema getC_AcctSchema() throws RuntimeException
{
return (I_C_AcctSchema)MTable.get(getCtx(), I_C_AcctSchema.Table_Name)
.getPO(getC_AcctSchema_ID(), get_TrxName()); }
/** Set Accounting Schema.
@param C_AcctSchema_ID
Rules for accounting
*/
public void setC_AcctSchema_ID (int C_AcctSchema_ID)
{
if (C_AcctSchema_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID));
}
/** Get Accounting Schema.
@return Rules for accounting
*/
public int getC_AcctSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getIntercompanyDueFrom_A() throws RuntimeException
{ | return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getIntercompanyDueFrom_Acct(), get_TrxName()); }
/** Set Intercompany Due From Acct.
@param IntercompanyDueFrom_Acct
Intercompany Due From / Receivables Account
*/
public void setIntercompanyDueFrom_Acct (int IntercompanyDueFrom_Acct)
{
set_Value (COLUMNNAME_IntercompanyDueFrom_Acct, Integer.valueOf(IntercompanyDueFrom_Acct));
}
/** Get Intercompany Due From Acct.
@return Intercompany Due From / Receivables Account
*/
public int getIntercompanyDueFrom_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IntercompanyDueFrom_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
public I_C_ValidCombination getIntercompanyDueTo_A() throws RuntimeException
{
return (I_C_ValidCombination)MTable.get(getCtx(), I_C_ValidCombination.Table_Name)
.getPO(getIntercompanyDueTo_Acct(), get_TrxName()); }
/** Set Intercompany Due To Acct.
@param IntercompanyDueTo_Acct
Intercompany Due To / Payable Account
*/
public void setIntercompanyDueTo_Acct (int IntercompanyDueTo_Acct)
{
set_Value (COLUMNNAME_IntercompanyDueTo_Acct, Integer.valueOf(IntercompanyDueTo_Acct));
}
/** Get Intercompany Due To Acct.
@return Intercompany Due To / Payable Account
*/
public int getIntercompanyDueTo_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IntercompanyDueTo_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_InterOrg_Acct.java | 1 |
请完成以下Java代码 | public Map<String, List<DmnExtensionElement>> getChildElements() {
return childElements;
}
public void addChildElement(DmnExtensionElement childElement) {
if (childElement != null && childElement.getName() != null && !childElement.getName().trim().isEmpty()) {
List<DmnExtensionElement> elementList = null;
if (!this.childElements.containsKey(childElement.getName())) {
elementList = new ArrayList<>();
this.childElements.put(childElement.getName(), elementList);
}
this.childElements.get(childElement.getName()).add(childElement);
}
}
public void setChildElements(Map<String, List<DmnExtensionElement>> childElements) {
this.childElements = childElements;
}
@Override
public DmnExtensionElement clone() {
DmnExtensionElement clone = new DmnExtensionElement();
clone.setValues(this);
return clone; | }
public void setValues(DmnExtensionElement otherElement) {
setName(otherElement.getName());
setNamespacePrefix(otherElement.getNamespacePrefix());
setNamespace(otherElement.getNamespace());
setElementText(otherElement.getElementText());
setAttributes(otherElement.getAttributes());
childElements = new LinkedHashMap<>();
if (otherElement.getChildElements() != null && !otherElement.getChildElements().isEmpty()) {
for (String key : otherElement.getChildElements().keySet()) {
List<DmnExtensionElement> otherElementList = otherElement.getChildElements().get(key);
if (otherElementList != null && !otherElementList.isEmpty()) {
List<DmnExtensionElement> elementList = new ArrayList<>();
for (DmnExtensionElement dmnExtensionElement : otherElementList) {
elementList.add(dmnExtensionElement.clone());
}
childElements.put(key, elementList);
}
}
}
}
} | repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnExtensionElement.java | 1 |
请完成以下Java代码 | public String getSql(final Properties ctx, final List<Object> params)
{
buildSql(ctx);
params.addAll(sqlParams);
return sql;
}
private void buildSql(final Properties ctx)
{
if (sqlBuilt)
{
return;
}
if (queryUpdaters.isEmpty())
{
throw new AdempiereException("Cannot build sql update query for an empty " + CompositeQueryUpdater.class);
}
final StringBuilder sql = new StringBuilder();
final List<Object> params = new ArrayList<>();
for (final IQueryUpdater<T> updater : queryUpdaters)
{
final ISqlQueryUpdater<T> sqlUpdater = (ISqlQueryUpdater<T>)updater;
final String sqlChunk = sqlUpdater.getSql(ctx, params); | if (Check.isEmpty(sqlChunk))
{
continue;
}
if (sql.length() > 0)
{
sql.append(", ");
}
sql.append(sqlChunk);
}
this.sql = sql.toString();
this.sqlParams = params;
this.sqlBuilt = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CompositeQueryUpdater.java | 1 |
请完成以下Java代码 | public void setP_TradeDiscountRec_A(org.compiere.model.I_C_ValidCombination P_TradeDiscountRec_A)
{
set_ValueFromPO(COLUMNNAME_P_TradeDiscountRec_Acct, org.compiere.model.I_C_ValidCombination.class, P_TradeDiscountRec_A);
}
/** Set Trade Discount Received.
@param P_TradeDiscountRec_Acct
Trade Discount Receivable Account
*/
@Override
public void setP_TradeDiscountRec_Acct (int P_TradeDiscountRec_Acct)
{
set_Value (COLUMNNAME_P_TradeDiscountRec_Acct, Integer.valueOf(P_TradeDiscountRec_Acct));
}
/** Get Trade Discount Received.
@return Trade Discount Receivable Account
*/
@Override
public int getP_TradeDiscountRec_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_P_TradeDiscountRec_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getP_UsageVariance_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_P_UsageVariance_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setP_UsageVariance_A(org.compiere.model.I_C_ValidCombination P_UsageVariance_A)
{
set_ValueFromPO(COLUMNNAME_P_UsageVariance_Acct, org.compiere.model.I_C_ValidCombination.class, P_UsageVariance_A);
}
/** Set Usage Variance.
@param P_UsageVariance_Acct
The Usage Variance account is the account used Manufacturing Order
*/
@Override
public void setP_UsageVariance_Acct (int P_UsageVariance_Acct)
{
set_Value (COLUMNNAME_P_UsageVariance_Acct, Integer.valueOf(P_UsageVariance_Acct));
}
/** Get Usage Variance.
@return The Usage Variance account is the account used Manufacturing Order
*/
@Override
public int getP_UsageVariance_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_P_UsageVariance_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_ValidCombination getP_WIP_A() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class); | }
@Override
public void setP_WIP_A(org.compiere.model.I_C_ValidCombination P_WIP_A)
{
set_ValueFromPO(COLUMNNAME_P_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, P_WIP_A);
}
/** Set Work In Process.
@param P_WIP_Acct
The Work in Process account is the account used Manufacturing Order
*/
@Override
public void setP_WIP_Acct (int P_WIP_Acct)
{
set_Value (COLUMNNAME_P_WIP_Acct, Integer.valueOf(P_WIP_Acct));
}
/** Get Work In Process.
@return The Work in Process account is the account used Manufacturing Order
*/
@Override
public int getP_WIP_Acct ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_P_WIP_Acct);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Acct.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DeploymentBuilder disableBpmnValidation() {
this.isProcessValidationEnabled = false;
return this;
}
@Override
public DeploymentBuilder disableSchemaValidation() {
this.isBpmn20XsdValidationEnabled = false;
return this;
}
@Override
public DeploymentBuilder tenantId(String tenantId) {
deployment.setTenantId(tenantId);
return this;
}
@Override
public DeploymentBuilder enableDuplicateFiltering() {
this.isDuplicateFilterEnabled = true;
return this;
}
@Override
public DeploymentBuilder activateProcessDefinitionsOn(Date date) {
this.processDefinitionsActivationDate = date;
return this;
}
@Override
public DeploymentBuilder deploymentProperty(String propertyKey, Object propertyValue) {
deploymentProperties.put(propertyKey, propertyValue);
return this;
}
@Override
public Deployment deploy() {
return repositoryService.deploy(this);
}
// getters and setters
// ////////////////////////////////////////////////////// | public DeploymentEntity getDeployment() {
return deployment;
}
public boolean isProcessValidationEnabled() {
return isProcessValidationEnabled;
}
public boolean isBpmn20XsdValidationEnabled() {
return isBpmn20XsdValidationEnabled;
}
public boolean isDuplicateFilterEnabled() {
return isDuplicateFilterEnabled;
}
public Date getProcessDefinitionsActivationDate() {
return processDefinitionsActivationDate;
}
public Map<String, Object> getDeploymentProperties() {
return deploymentProperties;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\repository\DeploymentBuilderImpl.java | 2 |
请完成以下Java代码 | public static void main(String[] args) {
// List of Parent Class
ArrayList<Number> myList = new ArrayList<>();
myList.add(1.2);
myList.add(2);
myList.add(-3.5);
// List of Interface type
ArrayList<Map> diffMapList = new ArrayList<>();
diffMapList.add(new HashMap<>());
diffMapList.add(new TreeMap<>());
diffMapList.add(new LinkedHashMap<>());
// List of Custom Object
ArrayList<CustomObject> objList = new ArrayList<>();
objList.add(new CustomObject("String"));
objList.add(new CustomObject(2));
// List via Functional Interface
List<Object> dataList = new ArrayList<>();
Predicate<Object> myPredicate = inputData -> (inputData instanceof String || inputData instanceof Integer); | UserFunctionalInterface myInterface = (listObj, data) -> {
if (myPredicate.test(data))
listObj.add(data);
else
System.out.println("Skipping input as data not allowed for class: " + data.getClass()
.getSimpleName());
return listObj;
};
myInterface.addToList(dataList, Integer.valueOf(2));
myInterface.addToList(dataList, Double.valueOf(3.33));
myInterface.addToList(dataList, "String Value");
myInterface.printList(dataList);
}
} | repos\tutorials-master\core-java-modules\core-java-collections-array-list-2\src\main\java\com\baeldung\list\multipleobjecttypes\AlternativeMultipeTypeList.java | 1 |
请完成以下Java代码 | public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean isAccountNonExpired() {
return accountNonExpired;
}
public void setAccountNonExpired(boolean accountNonExpired) {
this.accountNonExpired = accountNonExpired;
}
public boolean isAccountNonLocked() { | return accountNonLocked;
}
public void setAccountNonLocked(boolean accountNonLocked) {
this.accountNonLocked = accountNonLocked;
}
public boolean isCredentialsNonExpired() {
return credentialsNonExpired;
}
public void setCredentialsNonExpired(boolean credentialsNonExpired) {
this.credentialsNonExpired = credentialsNonExpired;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
} | repos\SpringAll-master\36.Spring-Security-ValidateCode\src\main\java\cc\mrbird\domain\MyUser.java | 1 |
请完成以下Java代码 | public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TemplateDefinition that = (TemplateDefinition) o;
return (
Objects.equals(from, that.from) &&
Objects.equals(subject, that.subject) &&
type == that.type &&
Objects.equals(value, that.value)
);
}
@Override
public int hashCode() {
return Objects.hash(from, subject, type, value);
}
@Override | public String toString() {
return (
"TemplateDefinition{" +
"from='" +
from +
'\'' +
", subject='" +
subject +
'\'' +
", type=" +
type +
", value='" +
value +
'\'' +
'}'
);
}
} | repos\Activiti-develop\activiti-core\activiti-spring-process-extensions\src\main\java\org\activiti\spring\process\model\TemplateDefinition.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(value = "For a single resource contains the actual URL to use for retrieving the binary resource", example = "http://localhost:8081/flowable-rest/service/cmmn-repository/deployments/10/resources/diagrams%2Fmy-process.bpmn20.xml")
public String getUrl() {
return url;
}
public void setContentUrl(String contentUrl) {
this.contentUrl = contentUrl;
}
@ApiModelProperty(example = "http://localhost:8081/flowable-rest/service/cmmn-repository/deployments/10/resourcedata/diagrams%2Fmy-process.bpmn20.xml")
public String getContentUrl() {
return contentUrl;
} | public void setMediaType(String mimeType) {
this.mediaType = mimeType;
}
@ApiModelProperty(example = "text/xml", value = "Contains the media-type the resource has. This is resolved using a (pluggable) MediaTypeResolver and contains, by default, a limited number of mime-type mappings.")
public String getMediaType() {
return mediaType;
}
public void setType(String type) {
this.type = type;
}
@ApiModelProperty(example = "processDefinition", value = "Type of resource", allowableValues = "resource,processDefinition,processImage")
public String getType() {
return type;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\repository\DeploymentResourceResponse.java | 2 |
请完成以下Java代码 | public class SysRole implements Serializable {
private static final long serialVersionUID = 1L;
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
private String id;
/**
* 角色名称
*/
@Excel(name="角色名",width=15)
private String roleName;
/**
* 角色编码
*/
@Excel(name="角色编码",width=15)
private String roleCode;
/**
* 描述
*/
@Excel(name="描述",width=60)
private String description;
/**
* 创建人
*/
private String createBy;
/** | * 创建时间
*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date createTime;
/**
* 更新人
*/
private String updateBy;
/**
* 更新时间
*/
@JsonFormat(timezone = "GMT+8",pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss")
private Date updateTime;
/**租户ID*/
private java.lang.Integer tenantId;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysRole.java | 1 |
请完成以下Java代码 | public class RemoveExecutionVariablesCmd extends AbstractRemoveVariableCmd {
private static final long serialVersionUID = 1L;
public RemoveExecutionVariablesCmd(String executionId, Collection<String> variableNames, boolean isLocal) {
super(executionId, variableNames, isLocal);
}
protected ExecutionEntity getEntity() {
ensureNotNull("executionId", entityId);
ExecutionEntity execution = commandContext
.getExecutionManager()
.findExecutionById(entityId);
ensureNotNull("execution " + entityId + " doesn't exist", "execution", execution);
checkRemoveExecutionVariables(execution);
return execution; | }
@Override
protected ExecutionEntity getContextExecution() {
return getEntity();
}
protected void logVariableOperation(AbstractVariableScope scope) {
ExecutionEntity execution = (ExecutionEntity) scope;
commandContext.getOperationLogManager().logVariableOperation(getLogEntryOperation(), execution.getId(), null, PropertyChange.EMPTY_CHANGE);
}
protected void checkRemoveExecutionVariables(ExecutionEntity execution) {
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkUpdateProcessInstanceVariables(execution);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\RemoveExecutionVariablesCmd.java | 1 |
请完成以下Java代码 | public int inspectRecord(final Object model)
{
final Timestamp value;
final Optional<Timestamp> updated = InterfaceWrapperHelper.getValue(model, I_AD_Column.COLUMNNAME_Updated);
if (updated.isPresent())
{
value = updated.get();
}
else
{
final Optional<Timestamp> created = InterfaceWrapperHelper.getValue(model, I_AD_Column.COLUMNNAME_Created);
Check.errorUnless(created.isPresent(), "model={} does not have an {}-value ", model, I_AD_Column.COLUMNNAME_Created);
value = created.get();
} | final boolean modelIsOld = TimeUtil.addMonths(value, 1).after(SystemTime.asDate());
return modelIsOld ? IMigratorService.DLM_Level_ARCHIVE : IMigratorService.DLM_Level_LIVE;
}
/**
* Returns <code>true</code> if the given model has an <code>Updated</code> column.
*/
@Override
public boolean isApplicableFor(final Object model)
{
return InterfaceWrapperHelper.hasModelColumnName(model, I_AD_Column.COLUMNNAME_Updated)
|| InterfaceWrapperHelper.hasModelColumnName(model, I_AD_Column.COLUMNNAME_Created);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\coordinator\impl\LastUpdatedInspector.java | 1 |
请完成以下Java代码 | public void setRetourenAnteilTyp(RetourenAnteilTypType value) {
this.retourenAnteilTyp = value;
}
/**
* <p>Java class for anonymous complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType>
* <complexContent>
* <extension base="{urn:msv3:v2}RetourePositionType">
* </extension>
* </complexContent> | * </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "")
public static class Position
extends RetourePositionType
{
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnkuendigungAntwort.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int updatePassword(UpdateAdminPasswordParam param) {
if(StrUtil.isEmpty(param.getUsername())
||StrUtil.isEmpty(param.getOldPassword())
||StrUtil.isEmpty(param.getNewPassword())){
return -1;
}
UmsAdminExample example = new UmsAdminExample();
example.createCriteria().andUsernameEqualTo(param.getUsername());
List<UmsAdmin> adminList = adminMapper.selectByExample(example);
if(CollUtil.isEmpty(adminList)){
return -2;
}
UmsAdmin umsAdmin = adminList.get(0);
if(!passwordEncoder.matches(param.getOldPassword(),umsAdmin.getPassword())){
return -3;
}
umsAdmin.setPassword(passwordEncoder.encode(param.getNewPassword()));
adminMapper.updateByPrimaryKey(umsAdmin);
getCacheService().delAdmin(umsAdmin.getId());
return 1;
}
@Override
public UserDetails loadUserByUsername(String username){
//获取用户信息
UmsAdmin admin = getAdminByUsername(username);
if (admin != null) {
List<UmsResource> resourceList = getResourceList(admin.getId());
return new AdminUserDetails(admin,resourceList);
}
throw new UsernameNotFoundException("用户名或密码错误"); | }
@Override
public UmsAdminCacheService getCacheService() {
return SpringUtil.getBean(UmsAdminCacheService.class);
}
@Override
public void logout(String username) {
//清空缓存中的用户相关数据
UmsAdmin admin = getCacheService().getAdmin(username);
getCacheService().delAdmin(admin.getId());
getCacheService().delResourceList(admin.getId());
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsAdminServiceImpl.java | 2 |
请完成以下Java代码 | public class ReceiptScheduleHUAllocations extends AbstractHUAllocations
{
//
// Services
private final IHUReceiptScheduleDAO huReceiptScheduleDAO = Services.get(IHUReceiptScheduleDAO.class);
public ReceiptScheduleHUAllocations(final I_M_ReceiptSchedule receiptSchedule, final IProductStorage productStorage)
{
super(
InterfaceWrapperHelper.create(receiptSchedule, I_M_ReceiptSchedule.class),
productStorage);
}
public ReceiptScheduleHUAllocations(final I_M_ReceiptSchedule receiptSchedule)
{
this(receiptSchedule, (IProductStorage)null);
}
@Override
protected final I_M_ReceiptSchedule getDocumentLineModel()
{
return (I_M_ReceiptSchedule)super.getDocumentLineModel();
}
@Override
protected final void deleteAllocations()
{
final I_M_ReceiptSchedule receiptSchedule = getDocumentLineModel();
final String trxName = getTrxName();
huReceiptScheduleDAO.deleteHandlingUnitAllocations(receiptSchedule, trxName);
}
@Override
protected final void createAllocation(final I_M_HU luHU,
final I_M_HU tuHU,
final I_M_HU vhu,
@NonNull final StockQtyAndUOMQty qtyToAllocate,
final boolean deleteOldTUAllocations)
{
// In case TU is null, consider using VHU as HU (i.e. the case of an VHU on LU, or free VHU)
// NOTE: we do this shit because in some BLs TU is assumed to be there not null
// and also, before VHU level allocation the TU field was filled with VHU.
final I_M_HU tuHUActual = coalesce(tuHU, vhu);
Check.assumeNotNull(tuHUActual, "At least one of tuHU or vhu needs to be not null; qtyToAllocate={}", qtyToAllocate);
final IContextAware contextProvider = getContextProvider();
final I_M_ReceiptSchedule receiptSchedule = getDocumentLineModel();
if (deleteOldTUAllocations)
{
deleteAllocationsOfTU(receiptSchedule, tuHUActual);
}
final HUReceiptScheduleAllocBuilder builder = new HUReceiptScheduleAllocBuilder();
builder.setContext(contextProvider)
.setM_ReceiptSchedule(receiptSchedule)
.setM_InOutLine(null)
.setQtyToAllocate(qtyToAllocate.toZero())
.setQtyWithIssues(qtyToAllocate.toZero()) // to be sure...
;
builder.setHU_QtyAllocated(qtyToAllocate) | .setM_LU_HU(luHU)
.setM_TU_HU(tuHUActual)
.setVHU(vhu);
// Create RSA and save it
builder.buildAndSave();
}
/**
* Remove existing receipt schedule allocations for the given TU.
*/
private final void deleteAllocationsOfTU(final I_M_ReceiptSchedule receiptSchedule, final I_M_HU tuHU)
{
final String trxName = getTrxName();
final List<I_M_HU> tradingUnitsToUnassign = Collections.singletonList(tuHU);
huReceiptScheduleDAO.deleteTradingUnitAllocations(receiptSchedule, tradingUnitsToUnassign, trxName);
}
@Override
protected void deleteAllocations(final Collection<I_M_HU> husToUnassign)
{
final I_M_ReceiptSchedule receiptSchedule = getDocumentLineModel();
final String trxName = getTrxName();
huReceiptScheduleDAO.deleteHandlingUnitAllocations(receiptSchedule, husToUnassign, trxName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleHUAllocations.java | 1 |
请完成以下Java代码 | private ViewLayout createViewLayout(final WindowId windowId)
{
return ViewLayout.builder()
.setWindowId(windowId)
.setCaption("PP Order Issue/Receipt")
.setEmptyResultText(msgBL.getTranslatableMsgText(LayoutFactory.TAB_EMPTY_RESULT_TEXT))
.setEmptyResultHint(msgBL.getTranslatableMsgText(LayoutFactory.TAB_EMPTY_RESULT_HINT))
//
.setHasAttributesSupport(true)
.setHasTreeSupport(true)
.setIncludedViewLayout(IncludedViewLayout.DEFAULT)
//
.addElementsFromViewRowClass(PPOrderLineRow.class, JSONViewDataType.grid)
.setAllowOpeningRowDetails(false)
//
.build();
}
private List<RelatedProcessDescriptor> createAdditionalRelatedProcessDescriptors()
{
return ImmutableList.of(
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_Receipt.class),
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.handlingunits.process.WEBUI_M_HU_Pick.class),
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_IssueServiceProduct.class),
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_ReverseCandidate.class),
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_ChangePlanningStatus_Planning.class),
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_ChangePlanningStatus_Review.class),
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_ChangePlanningStatus_Complete.class), | createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_HUEditor_Launcher.class),
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_M_Source_HU_Delete.class),
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_M_Source_HU_IssueTuQty.class),
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_M_Source_HU_IssueCUQty.class),
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_PrintLabel.class),
createProcessDescriptorForIssueReceiptWindow(de.metas.ui.web.pporder.process.WEBUI_PP_Order_Pick_ReceivedHUs.class));
}
private RelatedProcessDescriptor createProcessDescriptorForIssueReceiptWindow(@NonNull final Class<?> processClass)
{
final AdProcessId processId = adProcessDAO.retrieveProcessIdByClass(processClass);
return RelatedProcessDescriptor.builder()
.processId(processId)
.windowId(PPOrderConstants.AD_WINDOW_ID_IssueReceipt.toAdWindowIdOrNull())
.anyTable()
.displayPlace(DisplayPlace.ViewQuickActions)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\PPOrderLinesViewFactory.java | 1 |
请完成以下Java代码 | public void setDescription (final @Nullable java.lang.String Description)
{
set_ValueNoCheck (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setDocBaseType (final @Nullable java.lang.String DocBaseType)
{
set_Value (COLUMNNAME_DocBaseType, DocBaseType);
}
@Override
public java.lang.String getDocBaseType()
{
return get_ValueAsString(COLUMNNAME_DocBaseType);
}
@Override
public void setDocumentNo (final @Nullable java.lang.String DocumentNo)
{
set_Value (COLUMNNAME_DocumentNo, DocumentNo);
}
@Override
public java.lang.String getDocumentNo()
{
return get_ValueAsString(COLUMNNAME_DocumentNo);
}
@Override
public void setDR_Account (final @Nullable java.lang.String DR_Account)
{
set_Value (COLUMNNAME_DR_Account, DR_Account);
}
@Override
public java.lang.String getDR_Account()
{
return get_ValueAsString(COLUMNNAME_DR_Account);
}
@Override
public void setDueDate (final @Nullable java.sql.Timestamp DueDate)
{
set_ValueNoCheck (COLUMNNAME_DueDate, DueDate);
}
@Override
public java.sql.Timestamp getDueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DueDate);
}
@Override
public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx)
{
set_ValueNoCheck (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public java.lang.String getIsSOTrx()
{
return get_ValueAsString(COLUMNNAME_IsSOTrx);
} | @Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_ValueNoCheck (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setPostingType (final @Nullable java.lang.String PostingType)
{
set_ValueNoCheck (COLUMNNAME_PostingType, PostingType);
}
@Override
public java.lang.String getPostingType()
{
return get_ValueAsString(COLUMNNAME_PostingType);
}
@Override
public void setTaxAmtSource (final @Nullable BigDecimal TaxAmtSource)
{
set_ValueNoCheck (COLUMNNAME_TaxAmtSource, TaxAmtSource);
}
@Override
public BigDecimal getTaxAmtSource()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtSource);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVATCode (final @Nullable java.lang.String VATCode)
{
set_ValueNoCheck (COLUMNNAME_VATCode, VATCode);
}
@Override
public java.lang.String getVATCode()
{
return get_ValueAsString(COLUMNNAME_VATCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportLine.java | 1 |
请完成以下Java代码 | public ResponseEntity getProfile(
@PathVariable("username") String username, @AuthenticationPrincipal User user) {
return profileQueryService
.findByUsername(username, user)
.map(this::profileResponse)
.orElseThrow(ResourceNotFoundException::new);
}
@PostMapping(path = "follow")
public ResponseEntity follow(
@PathVariable("username") String username, @AuthenticationPrincipal User user) {
return userRepository
.findByUsername(username)
.map(
target -> {
FollowRelation followRelation = new FollowRelation(user.getId(), target.getId());
userRepository.saveRelation(followRelation);
return profileResponse(profileQueryService.findByUsername(username, user).get());
})
.orElseThrow(ResourceNotFoundException::new);
}
@DeleteMapping(path = "follow")
public ResponseEntity unfollow(
@PathVariable("username") String username, @AuthenticationPrincipal User user) {
Optional<User> userOptional = userRepository.findByUsername(username);
if (userOptional.isPresent()) { | User target = userOptional.get();
return userRepository
.findRelation(user.getId(), target.getId())
.map(
relation -> {
userRepository.removeRelation(relation);
return profileResponse(profileQueryService.findByUsername(username, user).get());
})
.orElseThrow(ResourceNotFoundException::new);
} else {
throw new ResourceNotFoundException();
}
}
private ResponseEntity profileResponse(ProfileData profile) {
return ResponseEntity.ok(
new HashMap<String, Object>() {
{
put("profile", profile);
}
});
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\ProfileApi.java | 1 |
请完成以下Java代码 | public boolean areAllEnginesIdle() {
for (AcquiredJobs acquiredJobs : acquiredJobsByEngine.values()) {
int jobsAcquired = acquiredJobs.getJobIdBatches().size() + acquiredJobs.getNumberOfJobsFailedToLock();
if (jobsAcquired >= acquiredJobs.getNumberOfJobsAttemptedToAcquire()) {
return false;
}
}
return true;
}
/**
* true if at least one job could not be locked, regardless of engine
*/
public boolean hasJobAcquisitionLockFailureOccurred() {
for (AcquiredJobs acquiredJobs : acquiredJobsByEngine.values()) {
if (acquiredJobs.getNumberOfJobsFailedToLock() > 0) {
return true;
}
}
return false;
}
// getters and setters
public void setAcquisitionTime(long acquisitionTime) {
this.acquisitionTime = acquisitionTime;
}
public long getAcquisitionTime() {
return acquisitionTime;
}
/**
* Jobs that were acquired in the current acquisition cycle.
* @return
*/
public Map<String, AcquiredJobs> getAcquiredJobsByEngine() {
return acquiredJobsByEngine;
}
/**
* Jobs that were rejected from execution in the acquisition cycle
* due to lacking execution resources.
* With an execution thread pool, these jobs could not be submitted due to
* saturation of the underlying job queue.
*/
public Map<String, List<List<String>>> getRejectedJobsByEngine() {
return rejectedJobBatchesByEngine;
} | /**
* Jobs that have been acquired in previous cycles and are supposed to
* be re-submitted for execution
*/
public Map<String, List<List<String>>> getAdditionalJobsByEngine() {
return additionalJobBatchesByEngine;
}
public void setAcquisitionException(Exception e) {
this.acquisitionException = e;
}
public Exception getAcquisitionException() {
return acquisitionException;
}
public void setJobAdded(boolean isJobAdded) {
this.isJobAdded = isJobAdded;
}
public boolean isJobAdded() {
return isJobAdded;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\JobAcquisitionContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getRequestDate()
{
return requestDate;
}
public void setRequestDate(String requestDate)
{
this.requestDate = requestDate;
}
public EvidenceRequest respondByDate(String respondByDate)
{
this.respondByDate = respondByDate;
return this;
}
/**
* The timestamp in this field shows the date/time when the seller is expected to provide a requested evidential document to eBay. The timestamps returned here use the ISO-8601 24-hour date and time format, and the time zone used is Universal Coordinated Time (UTC), also known as Greenwich Mean Time (GMT), or Zulu. The ISO-8601 format looks like this: yyyy-MM-ddThh:mm.ss.sssZ. An example would
* be 2019-08-04T19:09:02.768Z.
*
* @return respondByDate
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The timestamp in this field shows the date/time when the seller is expected to provide a requested evidential document to eBay. The timestamps returned here use the ISO-8601 24-hour date and time format, and the time zone used is Universal Coordinated Time (UTC), also known as Greenwich Mean Time (GMT), or Zulu. The ISO-8601 format looks like this: yyyy-MM-ddThh:mm.ss.sssZ. An example would be 2019-08-04T19:09:02.768Z.")
public String getRespondByDate()
{
return respondByDate;
}
public void setRespondByDate(String respondByDate)
{
this.respondByDate = respondByDate;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false; | }
EvidenceRequest evidenceRequest = (EvidenceRequest)o;
return Objects.equals(this.evidenceId, evidenceRequest.evidenceId) &&
Objects.equals(this.evidenceType, evidenceRequest.evidenceType) &&
Objects.equals(this.lineItems, evidenceRequest.lineItems) &&
Objects.equals(this.requestDate, evidenceRequest.requestDate) &&
Objects.equals(this.respondByDate, evidenceRequest.respondByDate);
}
@Override
public int hashCode()
{
return Objects.hash(evidenceId, evidenceType, lineItems, requestDate, respondByDate);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class EvidenceRequest {\n");
sb.append(" evidenceId: ").append(toIndentedString(evidenceId)).append("\n");
sb.append(" evidenceType: ").append(toIndentedString(evidenceType)).append("\n");
sb.append(" lineItems: ").append(toIndentedString(lineItems)).append("\n");
sb.append(" requestDate: ").append(toIndentedString(requestDate)).append("\n");
sb.append(" respondByDate: ").append(toIndentedString(respondByDate)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\EvidenceRequest.java | 2 |
请完成以下Java代码 | public class ProductWithNoCustomsTariffUserNotificationsProducer
{
private static final AdMessageKey MSG_ProductWithNoCustomsTariff = AdMessageKey.of("M_Product_No_CustomsTariff");
public static ProductWithNoCustomsTariffUserNotificationsProducer newInstance()
{
return new ProductWithNoCustomsTariffUserNotificationsProducer();
}
/**
* Topic used to send notifications about shipments/receipts that were generated/reversed asynchronously
*/
public static final Topic EVENTBUS_TOPIC = Topic.builder()
.name("de.metas.product.UserNotifications")
.type(Type.DISTRIBUTED)
.build();
private static final AdWindowId DEFAULT_WINDOW_Product = AdWindowId.ofRepoId(140); // FIXME: HARDCODED
private ProductWithNoCustomsTariffUserNotificationsProducer()
{
}
public ProductWithNoCustomsTariffUserNotificationsProducer notify(final Collection<ProductId> productIds)
{
if (productIds == null || productIds.isEmpty())
{
return this;
}
postNotifications(productIds.stream()
.map(this::createUserNotification)
.collect(ImmutableList.toImmutableList()));
return this;
}
private UserNotificationRequest createUserNotification(@NonNull final ProductId productId)
{
final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class);
final AdWindowId productWindowId = adWindowDAO.getAdWindowId(I_M_Product.Table_Name, SOTrx.SALES, DEFAULT_WINDOW_Product);
final TableRecordReference productRef = toTableRecordRef(productId); | return newUserNotificationRequest()
.recipientUserId(Env.getLoggedUserId())
.contentADMessage(MSG_ProductWithNoCustomsTariff)
.contentADMessageParam(productRef)
.targetAction(TargetRecordAction.ofRecordAndWindow(productRef, productWindowId))
.build();
}
private static TableRecordReference toTableRecordRef(final ProductId productId)
{
return TableRecordReference.of(I_M_Product.Table_Name, productId);
}
private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest()
{
return UserNotificationRequest.builder()
.topic(EVENTBUS_TOPIC);
}
private void postNotifications(final List<UserNotificationRequest> notifications)
{
Services.get(INotificationBL.class).sendAfterCommit(notifications);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\event\ProductWithNoCustomsTariffUserNotificationsProducer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductController {
private ProductService productService;
@Autowired
public ProductController(ProductService productService) {
this.productService = productService;
}
@PostMapping
@ResponseStatus(HttpStatus.CREATED)
public void create(@RequestBody Product product) {
productService.saveProduct(product);
}
@GetMapping(value = "/{id}/category/{category}") | public Optional<Product> get(@PathVariable String id, @PathVariable String category) {
return productService.findById(id, category);
}
@DeleteMapping(value = "/{id}/category/{category}")
public void delete(@PathVariable String id, @PathVariable String category) {
productService.delete(id, category);
}
@GetMapping
public List<Product> getByName(@RequestParam String name) {
return productService.findProductByName(name);
}
} | repos\tutorials-master\persistence-modules\spring-data-cosmosdb\src\main\java\com\baeldung\spring\data\cosmosdb\controller\ProductController.java | 2 |
请完成以下Java代码 | public class ScriptTaskImpl extends TaskImpl implements ScriptTask {
protected static Attribute<String> scriptFormatAttribute;
protected static ChildElement<Script> scriptChild;
/** camunda extensions */
protected static Attribute<String> camundaResultVariableAttribute;
protected static Attribute<String> camundaResourceAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ScriptTask.class, BPMN_ELEMENT_SCRIPT_TASK)
.namespaceUri(BPMN20_NS)
.extendsType(Task.class)
.instanceProvider(new ModelTypeInstanceProvider<ScriptTask>() {
public ScriptTask newInstance(ModelTypeInstanceContext instanceContext) {
return new ScriptTaskImpl(instanceContext);
}
});
scriptFormatAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_SCRIPT_FORMAT)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
scriptChild = sequenceBuilder.element(Script.class)
.build();
/** camunda extensions */
camundaResultVariableAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESULT_VARIABLE)
.namespace(CAMUNDA_NS)
.build();
camundaResourceAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_RESOURCE)
.namespace(CAMUNDA_NS)
.build();
typeBuilder.build();
}
public ScriptTaskImpl(ModelTypeInstanceContext context) {
super(context);
} | @Override
public ScriptTaskBuilder builder() {
return new ScriptTaskBuilder((BpmnModelInstance) modelInstance, this);
}
public String getScriptFormat() {
return scriptFormatAttribute.getValue(this);
}
public void setScriptFormat(String scriptFormat) {
scriptFormatAttribute.setValue(this, scriptFormat);
}
public Script getScript() {
return scriptChild.getChild(this);
}
public void setScript(Script script) {
scriptChild.setChild(this, script);
}
/** camunda extensions */
public String getCamundaResultVariable() {
return camundaResultVariableAttribute.getValue(this);
}
public void setCamundaResultVariable(String camundaResultVariable) {
camundaResultVariableAttribute.setValue(this, camundaResultVariable);
}
public String getCamundaResource() {
return camundaResourceAttribute.getValue(this);
}
public void setCamundaResource(String camundaResource) {
camundaResourceAttribute.setValue(this, camundaResource);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ScriptTaskImpl.java | 1 |
请完成以下Java代码 | public class AuthorizationFailureEvent extends AbstractAuthorizationEvent {
private final AccessDeniedException accessDeniedException;
private final Authentication authentication;
private final Collection<ConfigAttribute> configAttributes;
/**
* Construct the event.
* @param secureObject the secure object
* @param attributes that apply to the secure object
* @param authentication that was found in the <code>SecurityContextHolder</code>
* @param accessDeniedException that was returned by the
* <code>AccessDecisionManager</code>
* @throws IllegalArgumentException if any null arguments are presented.
*/
public AuthorizationFailureEvent(Object secureObject, Collection<ConfigAttribute> attributes,
Authentication authentication, AccessDeniedException accessDeniedException) {
super(secureObject);
Assert.isTrue(attributes != null && authentication != null && accessDeniedException != null,
"All parameters are required and cannot be null");
this.configAttributes = attributes; | this.authentication = authentication;
this.accessDeniedException = accessDeniedException;
}
public AccessDeniedException getAccessDeniedException() {
return this.accessDeniedException;
}
public Authentication getAuthentication() {
return this.authentication;
}
public Collection<ConfigAttribute> getConfigAttributes() {
return this.configAttributes;
}
} | repos\spring-security-main\access\src\main\java\org\springframework\security\access\event\AuthorizationFailureEvent.java | 1 |
请完成以下Java代码 | public Integer addBinaryNumber(Integer firstNum, Integer secondNum) {
StringBuilder output = new StringBuilder();
int carry = 0;
int temp;
while (firstNum != 0 || secondNum != 0) {
temp = (firstNum % 10 + secondNum % 10 + carry) % 2;
output.append(temp);
carry = (firstNum % 10 + secondNum % 10 + carry) / 2;
firstNum = firstNum / 10;
secondNum = secondNum / 10;
}
if (carry != 0) {
output.append(carry);
}
return Integer.valueOf(output.reverse()
.toString());
}
/**
* This method takes two binary number as input and subtract second number from the first number.
* example:- firstNum: 1000, secondNum: 11, output: 101
* @param firstNum
* @param secondNum
* @return Result of subtraction of secondNum from first
*/
public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) {
int onesComplement = Integer.valueOf(getOnesComplement(secondNum));
StringBuilder output = new StringBuilder();
int carry = 0;
int temp;
while (firstNum != 0 || onesComplement != 0) {
temp = (firstNum % 10 + onesComplement % 10 + carry) % 2;
output.append(temp); | carry = (firstNum % 10 + onesComplement % 10 + carry) / 2;
firstNum = firstNum / 10;
onesComplement = onesComplement / 10;
}
String additionOfFirstNumAndOnesComplement = output.reverse()
.toString();
if (carry == 1) {
return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry);
} else {
return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement));
}
}
public Integer getOnesComplement(Integer num) {
StringBuilder onesComplement = new StringBuilder();
while (num > 0) {
int lastDigit = num % 10;
if (lastDigit == 0) {
onesComplement.append(1);
} else {
onesComplement.append(0);
}
num = num / 10;
}
return Integer.valueOf(onesComplement.reverse()
.toString());
}
} | repos\tutorials-master\core-java-modules\core-java-numbers-2\src\main\java\com\baeldung\binarynumbers\BinaryNumbers.java | 1 |
请完成以下Java代码 | public Schema getSchema() {
return Public.PUBLIC;
}
@Override
public UniqueKey<AuthorRecord> getPrimaryKey() {
return Keys.AUTHOR_PKEY;
}
@Override
public List<UniqueKey<AuthorRecord>> getKeys() {
return Arrays.<UniqueKey<AuthorRecord>>asList(Keys.AUTHOR_PKEY);
}
@Override
public Author as(String alias) {
return new Author(DSL.name(alias), this);
}
@Override
public Author as(Name alias) {
return new Author(alias, this);
}
/**
* Rename this table
*/
@Override
public Author rename(String name) {
return new Author(DSL.name(name), null);
}
/** | * Rename this table
*/
@Override
public Author rename(Name name) {
return new Author(name, null);
}
// -------------------------------------------------------------------------
// Row4 type methods
// -------------------------------------------------------------------------
@Override
public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\Author.java | 1 |
请完成以下Java代码 | public RetryConfig addExceptions(Class<? extends Throwable>... exceptions) {
this.exceptions.addAll(Arrays.asList(exceptions));
return this;
}
public Set<HttpMethod> getMethods() {
return methods;
}
public RetryConfig setMethods(Set<HttpMethod> methods) {
this.methods = methods;
return this;
}
public RetryConfig addMethods(HttpMethod... methods) {
this.methods.addAll(Arrays.asList(methods));
return this;
}
public boolean isCacheBody() {
return cacheBody;
}
public RetryConfig setCacheBody(boolean cacheBody) {
this.cacheBody = cacheBody;
return this;
}
} | public static class RetryException extends NestedRuntimeException {
private final ServerRequest request;
private final ServerResponse response;
RetryException(ServerRequest request, ServerResponse response) {
super(null);
this.request = request;
this.response = response;
}
public ServerRequest getRequest() {
return request;
}
public ServerResponse getResponse() {
return response;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\RetryFilterFunctions.java | 1 |
请完成以下Java代码 | public void setDropShip_Location_ID(final int DropShip_Location_ID)
{
delegate.setDropShip_Location_ID(DropShip_Location_ID);
}
@Override
public int getDropShip_Location_Value_ID()
{
return delegate.getDropShip_Location_Value_ID();
}
@Override
public void setDropShip_Location_Value_ID(final int DropShip_Location_Value_ID)
{
delegate.setDropShip_Location_Value_ID(DropShip_Location_Value_ID);
}
@Override
public int getDropShip_User_ID()
{
return delegate.getDropShip_User_ID();
}
@Override
public void setDropShip_User_ID(final int DropShip_User_ID)
{
delegate.setDropShip_User_ID(DropShip_User_ID);
}
@Override
public int getM_Warehouse_ID()
{
return delegate.getM_Warehouse_ID();
}
@Override
public boolean isDropShip()
{
return delegate.isDropShip();
}
@Override
public String getDeliveryToAddress()
{
return delegate.getDeliveryToAddress();
}
@Override
public void setDeliveryToAddress(final String address)
{
delegate.setDeliveryToAddress(address);
}
@Override | public void setRenderedAddressAndCapturedLocation(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddressAndCapturedLocation(from);
}
@Override
public void setRenderedAddress(final @NonNull RenderedAddressAndCapturedLocation from)
{
IDocumentDeliveryLocationAdapter.super.setRenderedAddress(from);
}
@Override
public I_M_InOut getWrappedRecord()
{
return delegate;
}
@Override
public Optional<DocumentLocation> toPlainDocumentLocation(final IDocumentLocationBL documentLocationBL)
{
return documentLocationBL.toPlainDocumentLocation(this);
}
@Override
public DocumentDeliveryLocationAdapter toOldValues()
{
InterfaceWrapperHelper.assertNotOldValues(delegate);
return new DocumentDeliveryLocationAdapter(InterfaceWrapperHelper.createOld(delegate, I_M_InOut.class));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\location\adapter\DocumentDeliveryLocationAdapter.java | 1 |
请完成以下Java代码 | private int getParentID()
{
return parentPO != null ? parentPO.get_ID() : -1;
}
/**
* Allows other modules to install customer code to be executed each time a record was copied.
*/
@Override
public final GeneralCopyRecordSupport onRecordCopied(@NonNull final OnRecordCopiedListener listener)
{
if (!recordCopiedListeners.contains(listener))
{
recordCopiedListeners.add(listener);
} | return this;
}
@Override
public final CopyRecordSupport onChildRecordCopied(@NonNull final OnRecordCopiedListener listener)
{
if (!childRecordCopiedListeners.contains(listener))
{
childRecordCopiedListeners.add(listener);
}
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\GeneralCopyRecordSupport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public HUPIItemProductId getPackingMaterialId()
{
return groupingKey.getPackingMaterialId();
}
@Override
public Set<WarehouseId> getWarehouseIds()
{
return parts.map(PackingItemPart::getWarehouseId).collect(ImmutableSet.toImmutableSet());
}
@Override
public Set<ShipmentScheduleId> getShipmentScheduleIds()
{
return parts.map(PackingItemPart::getShipmentScheduleId).collect(ImmutableSet.toImmutableSet());
}
@Override
public IPackingItem subtractToPackingItem(
@NonNull final Quantity subtrahent, | @Nullable final Predicate<PackingItemPart> acceptPartPredicate)
{
final PackingItemParts subtractedParts = subtract(subtrahent, acceptPartPredicate);
return PackingItems.newPackingItem(subtractedParts);
}
@Override
public PackingItem copy()
{
return new PackingItem(this);
}
@Override
public String toString()
{
return "FreshPackingItem ["
+ "qtySum=" + getQtySum()
+ ", productId=" + getProductId()
+ ", uom=" + getC_UOM() + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItem.java | 2 |
请完成以下Java代码 | public void setId(Integer value) {
set(0, value);
}
/**
* Getter for <code>public.Store.id</code>.
*/
public Integer getId() {
return (Integer) get(0);
}
/**
* Setter for <code>public.Store.name</code>.
*/
public void setName(String value) {
set(1, value);
}
/**
* Getter for <code>public.Store.name</code>.
*/
public String getName() {
return (String) get(1);
}
// -------------------------------------------------------------------------
// Primary key information
// -------------------------------------------------------------------------
@Override
public Record1<Integer> key() {
return (Record1) super.key();
} | // -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached StoreRecord
*/
public StoreRecord() {
super(Store.STORE);
}
/**
* Create a detached, initialised StoreRecord
*/
public StoreRecord(Integer id, String name) {
super(Store.STORE);
setId(id);
setName(name);
resetChangedOnNotNull();
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\records\StoreRecord.java | 1 |
请完成以下Java代码 | public Object aggregateMultiVariables(DelegatePlanItemInstance planItemInstance, List<? extends VariableInstance> instances, PlanItemVariableAggregatorContext context) {
return getPlanItemVariableAggregator().aggregateMultiVariables(planItemInstance, instances, context);
}
protected PlanItemVariableAggregator getPlanItemVariableAggregator() {
Object delegateInstance = instantiate(className);
applyFieldExtensions(fieldExtensions, delegateInstance, false);
if (delegateInstance instanceof PlanItemVariableAggregator) {
return (PlanItemVariableAggregator) delegateInstance;
} else {
throw new FlowableIllegalArgumentException(delegateInstance.getClass().getName() + " doesn't implement " + PlanItemVariableAggregator.class);
}
}
protected Object instantiate(String className) {
return ReflectUtil.instantiate(className);
}
public static void applyFieldExtensions(List<FieldExtension> fieldExtensions, Object target, boolean throwExceptionOnMissingField) {
if (fieldExtensions != null) {
for (FieldExtension fieldExtension : fieldExtensions) {
applyFieldExtension(fieldExtension, target, throwExceptionOnMissingField);
}
}
}
protected static void applyFieldExtension(FieldExtension fieldExtension, Object target, boolean throwExceptionOnMissingField) {
Object value = null;
if (fieldExtension.getExpression() != null) {
ExpressionManager expressionManager = CommandContextUtil.getCmmnEngineConfiguration().getExpressionManager();
value = expressionManager.createExpression(fieldExtension.getExpression());
} else {
value = new FixedValue(fieldExtension.getStringValue());
}
ReflectUtil.invokeSetterOrField(target, fieldExtension.getFieldName(), value, throwExceptionOnMissingField);
}
@Override
public String getSourceState() {
return sourceState;
}
public void setSourceState(String sourceState) {
this.sourceState = sourceState;
}
@Override
public String getTargetState() { | return targetState;
}
public void setTargetState(String targetState) {
this.targetState = targetState;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public List<FieldExtension> getFieldExtensions() {
return fieldExtensions;
}
public void setFieldExtensions(List<FieldExtension> fieldExtensions) {
this.fieldExtensions = fieldExtensions;
}
public CmmnActivityBehavior getActivityBehaviorInstance() {
return activityBehaviorInstance;
}
public void setActivityBehaviorInstance(CmmnActivityBehavior activityBehaviorInstance) {
this.activityBehaviorInstance = activityBehaviorInstance;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\CmmnClassDelegate.java | 1 |
请完成以下Java代码 | public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
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;
} | public String getRating() {
return rating;
}
public void setRating(String rating) {
this.rating = rating;
}
@Override
public String toString() {
return "Author{" + "id=" + id + ", name=" + name
+ ", genre=" + genre + ", age=" + age + ", email="
+ email + ", address=" + address + ", rating=" + rating + '}';
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootDynamicProjection\src\main\java\com\bookstore\entity\Author.java | 1 |
请完成以下Java代码 | public void setAD_Val_Rule_Included_ID (int AD_Val_Rule_Included_ID)
{
if (AD_Val_Rule_Included_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_Included_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_Included_ID, Integer.valueOf(AD_Val_Rule_Included_ID));
}
/** Get AD_Val_Rule_Included.
@return AD_Val_Rule_Included */
public int getAD_Val_Rule_Included_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Val_Rule_Included_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entitäts-Art.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entitäts-Art.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** Set Included_Val_Rule_ID.
@param Included_Val_Rule_ID
Validation rule to be included.
*/
public void setIncluded_Val_Rule_ID (int Included_Val_Rule_ID)
{ | if (Included_Val_Rule_ID < 1)
set_ValueNoCheck (COLUMNNAME_Included_Val_Rule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Included_Val_Rule_ID, Integer.valueOf(Included_Val_Rule_ID));
}
/** Get Included_Val_Rule_ID.
@return Validation rule to be included.
*/
public int getIncluded_Val_Rule_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Included_Val_Rule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
public void setSeqNo (String SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
public String getSeqNo ()
{
return (String)get_Value(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Val_Rule_Included.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DataResponse<TaskResponse> bulkUpdateTasks(@RequestBody BulkTasksRequest bulkTasksRequest) {
if (bulkTasksRequest == null) {
throw new FlowableException("A request body was expected when bulk updating tasks.");
}
if (bulkTasksRequest.getTaskIds() == null) {
throw new FlowableIllegalArgumentException("taskIds can not be null for bulk update tasks requests");
}
Collection<Task> taskList = getTasksFromRequest(bulkTasksRequest.getTaskIds());
if (taskList.size() != bulkTasksRequest.getTaskIds().size()) {
taskList.stream().forEach(task -> bulkTasksRequest.getTaskIds().remove(task.getId()));
throw new FlowableObjectNotFoundException(
"Could not find task instance with id:" + bulkTasksRequest.getTaskIds().stream().collect(Collectors.joining(",")));
}
// Populate the task properties based on the request
populateTasksFromRequest(taskList, bulkTasksRequest);
if (restApiInterceptor != null) {
restApiInterceptor.bulkUpdateTasks(taskList, bulkTasksRequest);
}
// Save the task and fetch again, it's possible that an
// assignment-listener has updated | // fields after it was saved so we can not use the in-memory task
taskService.bulkSaveTasks(taskList);
List<Task> taskResultList = getTasksFromRequest(bulkTasksRequest.getTaskIds());
DataResponse<TaskResponse> dataResponse = new DataResponse<>();
dataResponse.setData(restResponseFactory.createTaskResponseList(taskResultList));
return dataResponse;
}
protected List<String> csvToList(String key, Map<String, String> requestParams) {
String[] candidateGroupsSplit = requestParams.get(key).split(",");
List<String> groups = new ArrayList<>(candidateGroupsSplit.length);
Collections.addAll(groups, candidateGroupsSplit);
return groups;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskCollectionResource.java | 2 |
请完成以下Java代码 | public class Employee {
private String lastName;
private String firstName;
private long id;
private Optional<Salary> salary;
public Employee() {
}
public Employee(final long id, final String lastName, final String firstName, final Optional<Salary> salary) {
this.id = id;
this.lastName = lastName;
this.firstName = firstName;
this.salary = salary;
}
public String getLastName() {
return lastName;
}
public String getFirstName() {
return firstName;
}
public long getId() {
return id;
}
public void setLastName(final String lastName) {
this.lastName = lastName;
}
public void setFirstName(final String firstName) {
this.firstName = firstName;
}
public void setId(final long id) { | this.id = id;
}
public Optional<Salary> getSalary() {
return salary;
}
public void setSalary(final Optional<Salary> salary) {
this.salary = salary;
}
@Override
public String toString() {
return "Employee{" +
"lastName='" + lastName + '\'' +
", firstName='" + firstName + '\'' +
", id=" + id +
", salary=" + salary +
'}';
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-data-2\src\main\java\com\baeldung\jsonignore\absentfields\Employee.java | 1 |
请完成以下Java代码 | public ObjectId getId() {
return id;
}
public String getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public String getAccountDomain() {
return accountDomain;
}
public void setAccountDomain(String accountDomain) {
this.accountDomain = accountDomain;
}
public String getPassword() {
return password;
} | public void setPassword(String password) {
this.password = password;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Account book = (Account) o;
return Objects.equals(id, book.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb\src\main\java\com\baeldung\multipledb\model\Account.java | 1 |
请完成以下Java代码 | private static void addIfNotNull(ObjectNode node, String key, String value) {
if (value != null) {
node.put(key, value);
}
}
private static JsonNode mapRepository(Repository repo) {
ObjectNode node = nodeFactory.objectNode();
node.put("name", repo.getName())
.put("url", (repo.getUrl() != null) ? repo.getUrl().toString() : null)
.put("snapshotEnabled", repo.isSnapshotsEnabled());
return node;
}
private static ObjectNode mapBom(BillOfMaterials bom) {
ObjectNode node = nodeFactory.objectNode();
node.put("groupId", bom.getGroupId());
node.put("artifactId", bom.getArtifactId());
addIfNotNull(node, "version", bom.getVersion());
addArrayIfNotNull(node, bom.getRepositories());
return node;
}
private static void addArrayIfNotNull(ObjectNode node, List<String> values) {
if (!CollectionUtils.isEmpty(values)) {
ArrayNode arrayNode = nodeFactory.arrayNode();
values.forEach(arrayNode::add);
node.set("repositories", arrayNode); | }
}
private static ObjectNode mapNode(Map<String, JsonNode> content) {
ObjectNode node = nodeFactory.objectNode();
content.forEach(node::set);
return node;
}
private ObjectNode mapDependencies(Map<String, Dependency> dependencies) {
return mapNode(dependencies.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapDependency(entry.getValue()))));
}
private ObjectNode mapRepositories(Map<String, Repository> repositories) {
return mapNode(repositories.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapRepository(entry.getValue()))));
}
private ObjectNode mapBoms(Map<String, BillOfMaterials> boms) {
return mapNode(boms.entrySet()
.stream()
.collect(Collectors.toMap(Map.Entry::getKey, (entry) -> mapBom(entry.getValue()))));
}
} | repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\mapper\DependencyMetadataV21JsonMapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static OAuth2TokenCustomizer<OAuth2TokenClaimsContext> getAccessTokenCustomizer(HttpSecurity httpSecurity) {
final OAuth2TokenCustomizer<OAuth2TokenClaimsContext> defaultAccessTokenCustomizer = DefaultOAuth2TokenCustomizers
.accessTokenCustomizer();
ResolvableType type = ResolvableType.forClassWithGenerics(OAuth2TokenCustomizer.class,
OAuth2TokenClaimsContext.class);
OAuth2TokenCustomizer<OAuth2TokenClaimsContext> accessTokenCustomizer = getOptionalBean(httpSecurity, type);
if (accessTokenCustomizer == null) {
return defaultAccessTokenCustomizer;
}
return (context) -> {
defaultAccessTokenCustomizer.customize(context);
accessTokenCustomizer.customize(context);
};
}
static AuthorizationServerSettings getAuthorizationServerSettings(HttpSecurity httpSecurity) {
AuthorizationServerSettings authorizationServerSettings = httpSecurity
.getSharedObject(AuthorizationServerSettings.class);
if (authorizationServerSettings == null) {
authorizationServerSettings = getBean(httpSecurity, AuthorizationServerSettings.class);
httpSecurity.setSharedObject(AuthorizationServerSettings.class, authorizationServerSettings);
}
return authorizationServerSettings;
}
static <T> T getBean(HttpSecurity httpSecurity, Class<T> type) {
return httpSecurity.getSharedObject(ApplicationContext.class).getBean(type);
}
@SuppressWarnings("unchecked")
static <T> T getBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length == 1) {
return (T) context.getBean(names[0]);
} | if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
throw new NoSuchBeanDefinitionException(type);
}
static <T> T getOptionalBean(HttpSecurity httpSecurity, Class<T> type) {
Map<String, T> beansMap = BeanFactoryUtils
.beansOfTypeIncludingAncestors(httpSecurity.getSharedObject(ApplicationContext.class), type);
if (beansMap.size() > 1) {
throw new NoUniqueBeanDefinitionException(type, beansMap.size(),
"Expected single matching bean of type '" + type.getName() + "' but found " + beansMap.size() + ": "
+ StringUtils.collectionToCommaDelimitedString(beansMap.keySet()));
}
return (!beansMap.isEmpty() ? beansMap.values().iterator().next() : null);
}
@SuppressWarnings("unchecked")
static <T> T getOptionalBean(HttpSecurity httpSecurity, ResolvableType type) {
ApplicationContext context = httpSecurity.getSharedObject(ApplicationContext.class);
String[] names = context.getBeanNamesForType(type);
if (names.length > 1) {
throw new NoUniqueBeanDefinitionException(type, names);
}
return (names.length == 1) ? (T) context.getBean(names[0]) : null;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OAuth2ConfigurerUtils.java | 2 |
请完成以下Java代码 | public void sendMessage(String message) {
//log.debug("【系统 WebSocket】广播消息:" + message);
BaseMap baseMap = new BaseMap();
baseMap.put("userId", "");
baseMap.put("message", message);
jeecgRedisClient.sendMessage(WebSocket.REDIS_TOPIC_NAME, baseMap);
}
/**
* 此为单点消息 redis
*
* @param userId
* @param message
*/
public void sendMessage(String userId, String message) {
BaseMap baseMap = new BaseMap();
baseMap.put("userId", userId);
baseMap.put("message", message);
jeecgRedisClient.sendMessage(WebSocket.REDIS_TOPIC_NAME, baseMap); | }
/**
* 此为单点消息(多人) redis
*
* @param userIds
* @param message
*/
public void sendMessage(String[] userIds, String message) {
for (String userId : userIds) {
sendMessage(userId, message);
}
}
//=======【采用redis发布订阅模式——推送消息】==========================================================================================
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\websocket\WebSocket.java | 1 |
请完成以下Java代码 | public void collect(@NonNull final SqlParamsCollector from)
{
collectAll(from.params);
}
/**
* Collects given SQL value and returns an SQL placeholder, i.e. "?"
*
* In case this is in non-collecting mode, the given SQL value will be converted to SQL code and it will be returned.
* The internal list won't be affected, because it does not exist.
*/
public String placeholder(@Nullable final Object sqlValue)
{
if (params == null)
{
return DB.TO_SQL(sqlValue);
}
else
{
params.add(sqlValue); | return "?";
}
}
/** @return readonly live list */
public List<Object> toList()
{
return paramsRO;
}
/** @return read/write live list */
public List<Object> toLiveList()
{
return params;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\SqlParamsCollector.java | 1 |
请完成以下Java代码 | public BPartnerLocationId getHandoverLocationId() {return packageable.getHandoverLocationId();}
public String getCustomerAddress() {return packageable.getCustomerAddress();}
public @NonNull InstantAndOrgId getPreparationDate() {return packageable.getPreparationDate();}
public @NonNull InstantAndOrgId getDeliveryDate() {return packageable.getDeliveryDate();}
public @Nullable OrderId getSalesOrderId() {return packageable.getSalesOrderId();}
public @Nullable String getSalesOrderDocumentNo() {return packageable.getSalesOrderDocumentNo();}
public @Nullable OrderAndLineId getSalesOrderAndLineIdOrNull() {return packageable.getSalesOrderAndLineIdOrNull();}
public @Nullable WarehouseTypeId getWarehouseTypeId() {return packageable.getWarehouseTypeId();}
public boolean isPartiallyPickedOrDelivered()
{
return packageable.getQtyPickedPlanned().signum() != 0
|| packageable.getQtyPickedNotDelivered().signum() != 0
|| packageable.getQtyPickedAndDelivered().signum() != 0;
}
public @NonNull ProductId getProductId() {return packageable.getProductId();}
public @NonNull String getProductName() {return packageable.getProductName();}
public @NonNull I_C_UOM getUOM() {return getQtyToDeliver().getUOM();}
public @NonNull Quantity getQtyToDeliver()
{
return schedule != null
? schedule.getQtyToPick()
: packageable.getQtyToDeliver();
}
public @NonNull HUPIItemProductId getPackToHUPIItemProductId() {return packageable.getPackToHUPIItemProductId();} | public @NonNull Quantity getQtyToPick()
{
return schedule != null
? schedule.getQtyToPick()
: packageable.getQtyToPick();
}
public @Nullable UomId getCatchWeightUomId() {return packageable.getCatchWeightUomId();}
public @Nullable PPOrderId getPickFromOrderId() {return packageable.getPickFromOrderId();}
public @Nullable ShipperId getShipperId() {return packageable.getShipperId();}
public @NonNull AttributeSetInstanceId getAsiId() {return packageable.getAsiId();}
public Optional<ShipmentAllocationBestBeforePolicy> getBestBeforePolicy() {return packageable.getBestBeforePolicy();}
public @NonNull WarehouseId getWarehouseId() {return packageable.getWarehouseId();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\model\ScheduledPackageable.java | 1 |
请完成以下Java代码 | public class QueueEntity extends BaseSqlEntity<Queue> {
@Column(name = ModelConstants.QUEUE_TENANT_ID_PROPERTY)
private UUID tenantId;
@Column(name = ModelConstants.QUEUE_NAME_PROPERTY)
private String name;
@Column(name = ModelConstants.QUEUE_TOPIC_PROPERTY)
private String topic;
@Column(name = ModelConstants.QUEUE_POLL_INTERVAL_PROPERTY)
private int pollInterval;
@Column(name = ModelConstants.QUEUE_PARTITIONS_PROPERTY)
private int partitions;
@Column(name = ModelConstants.QUEUE_CONSUMER_PER_PARTITION)
private boolean consumerPerPartition;
@Column(name = ModelConstants.QUEUE_PACK_PROCESSING_TIMEOUT_PROPERTY)
private long packProcessingTimeout;
@Convert(converter = JsonConverter.class)
@Column(name = ModelConstants.QUEUE_SUBMIT_STRATEGY_PROPERTY)
private JsonNode submitStrategy;
@Convert(converter = JsonConverter.class)
@Column(name = ModelConstants.QUEUE_PROCESSING_STRATEGY_PROPERTY)
private JsonNode processingStrategy;
@Convert(converter = JsonConverter.class)
@Column(name = ModelConstants.QUEUE_ADDITIONAL_INFO_PROPERTY)
private JsonNode additionalInfo;
public QueueEntity() {
}
public QueueEntity(Queue queue) {
if (queue.getId() != null) {
this.setId(queue.getId().getId());
} | this.createdTime = queue.getCreatedTime();
this.tenantId = DaoUtil.getId(queue.getTenantId());
this.name = queue.getName();
this.topic = queue.getTopic();
this.pollInterval = queue.getPollInterval();
this.partitions = queue.getPartitions();
this.consumerPerPartition = queue.isConsumerPerPartition();
this.packProcessingTimeout = queue.getPackProcessingTimeout();
this.submitStrategy = JacksonUtil.valueToTree(queue.getSubmitStrategy());
this.processingStrategy = JacksonUtil.valueToTree(queue.getProcessingStrategy());
this.additionalInfo = queue.getAdditionalInfo();
}
@Override
public Queue toData() {
Queue queue = new Queue(new QueueId(getUuid()));
queue.setCreatedTime(createdTime);
queue.setTenantId(TenantId.fromUUID(tenantId));
queue.setName(name);
queue.setTopic(topic);
queue.setPollInterval(pollInterval);
queue.setPartitions(partitions);
queue.setConsumerPerPartition(consumerPerPartition);
queue.setPackProcessingTimeout(packProcessingTimeout);
queue.setSubmitStrategy(JacksonUtil.convertValue(submitStrategy, SubmitStrategy.class));
queue.setProcessingStrategy(JacksonUtil.convertValue(processingStrategy, ProcessingStrategy.class));
queue.setAdditionalInfo(additionalInfo);
return queue;
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\sql\QueueEntity.java | 1 |
请完成以下Java代码 | public boolean isState() {
return this.equals(STATE);
}
public boolean isDeath() {
return this.equals(DDEATH) || this.equals(NDEATH);
}
public boolean isCommand() {
return this.equals(DCMD) || this.equals(NCMD);
}
public boolean isData() {
return this.equals(DDATA) || this.equals(NDATA);
}
public boolean isBirth() {
return this.equals(DBIRTH) || this.equals(NBIRTH);
}
public boolean isRecord() { | return this.equals(DRECORD) || this.equals(NRECORD);
}
public boolean isSubscribe() {
return isCommand() || isData() || isRecord();
}
public boolean isNode() {
return this.equals(NBIRTH)
|| this.equals(NCMD) || this.equals(NDATA)
||this.equals(NDEATH) || this.equals(NRECORD);
}
public boolean isDevice() {
return this.equals(DBIRTH)
|| this.equals(DCMD) || this.equals(DDATA)
||this.equals(DDEATH) || this.equals(DRECORD);
}
} | repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\SparkplugMessageType.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.