instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private I_DataEntry_Record getRecordById(final DataEntryRecordId dataEntryRecordId)
{
return load(dataEntryRecordId, I_DataEntry_Record.class);
}
private DataEntryRecord toDataEntryRecord(@NonNull final I_DataEntry_Record record)
{
final String jsonString = record.getDataEntry_RecordData();
final List<DataEntryRecordField<?>> fields = jsonDataEntryRecordMapper.deserialize(jsonString);
return DataEntryRecord.builder()
.id(DataEntryRecordId.ofRepoId(record.getDataEntry_Record_ID()))
.dataEntrySubTabId(DataEntrySubTabId.ofRepoId(record.getDataEntry_SubTab_ID()))
.mainRecord(TableRecordReference.of(record.getAD_Table_ID(), record.getRecord_ID()))
.fields(fields)
.build();
}
public DataEntryRecordId save(@NonNull final DataEntryRecord dataEntryRecord)
{
final I_DataEntry_Record dataRecord;
final DataEntryRecordId existingId = dataEntryRecord.getId().orElse(null);
if (existingId == null)
{
dataRecord = newInstance(I_DataEntry_Record.class);
}
else
{
dataRecord = getRecordById(existingId);
}
dataRecord.setAD_Table_ID(dataEntryRecord.getMainRecord().getAD_Table_ID());
dataRecord.setRecord_ID(dataEntryRecord.getMainRecord().getRecord_ID());
dataRecord.setDataEntry_SubTab_ID(dataEntryRecord.getDataEntrySubTabId().getRepoId());
dataRecord.setIsActive(true);
final String jsonString = jsonDataEntryRecordMapper.serialize(dataEntryRecord.getFields());
dataRecord.setDataEntry_RecordData(jsonString); | saveRecord(dataRecord);
final DataEntryRecordId dataEntryRecordId = DataEntryRecordId.ofRepoId(dataRecord.getDataEntry_Record_ID());
dataEntryRecord.setId(dataEntryRecordId);
return dataEntryRecordId;
}
public void deleteBy(@NonNull final DataEntryRecordQuery query)
{
query(query).delete();
}
private IQuery<I_DataEntry_Record> query(@NonNull final DataEntryRecordQuery query)
{
final ImmutableSet<DataEntrySubTabId> dataEntrySubTabIds = query.getDataEntrySubTabIds();
final int recordId = query.getRecordId();
return Services.get(IQueryBL.class)
.createQueryBuilder(I_DataEntry_Record.class)
.addOnlyActiveRecordsFilter() // we have a UC on those columns
.addInArrayFilter(I_DataEntry_Record.COLUMN_DataEntry_SubTab_ID, dataEntrySubTabIds)
.addEqualsFilter(I_DataEntry_Record.COLUMN_Record_ID, recordId)
.orderBy(I_DataEntry_Record.COLUMNNAME_DataEntry_SubTab_ID)
.create();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\DataEntryRecordRepository.java | 1 |
请完成以下Java代码 | private ImmutableList<OrderCostDetail> createOrderCostDetails()
{
final ImmutableSet<OrderAndLineId> orderAndLineIds = request.getOrderAndLineIds();
if (orderAndLineIds.isEmpty())
{
throw new AdempiereException("No order lines provided");
}
// Make sure all lines are from a single order
CollectionUtils.extractSingleElement(orderAndLineIds, OrderAndLineId::getOrderId);
// Do not allow order lines created by other costs
// Maybe in future we will support it, but now, that's the simplest way to avoid recursion.
final ImmutableSet<OrderLineId> orderLineIds = orderAndLineIds.stream().map(OrderAndLineId::getOrderLineId).collect(ImmutableSet.toImmutableSet());
if (orderCostRepository.hasCostsByCreatedOrderLineIds(orderLineIds))
{
throw new AdempiereException("Cannot use order lines which were created by other costs");
}
return orderBL.getLinesByIds(orderAndLineIds)
.values()
.stream()
.sorted(Comparator.comparing(I_C_OrderLine::getLine))
.map(OrderCostCreateCommand::toOrderCostDetail)
.collect(ImmutableList.toImmutableList());
}
private static OrderCostDetail toOrderCostDetail(final I_C_OrderLine orderLine)
{
return OrderCostDetail.builder()
.orderLineInfo(OrderCostDetailOrderLinePart.ofOrderLine(orderLine))
.build();
}
public void createOrderLineIfNeeded(final I_C_Order order, final OrderCost orderCost)
{
final OrderCostCreateRequest.OrderLine addOrderLineRequest = request.getAddOrderLine(); | if (addOrderLineRequest == null)
{
return;
}
final OrderAndLineId createdOrderAndLineId = CreateOrUpdateOrderLineFromOrderCostCommand.builder()
.orderBL(orderBL)
.moneyService(moneyService)
.orderCost(orderCost)
.productId(addOrderLineRequest.getProductId())
.loadedOrder(order)
.build()
.execute();
orderCost.setCreatedOrderLineId(createdOrderAndLineId.getOrderLineId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostCreateCommand.java | 1 |
请完成以下Java代码 | public void addAuthority(GrantedAuthority a) {
if (!hasAuthority(a)) {
this.mutableAuthorities.add(a);
}
}
private boolean hasAuthority(GrantedAuthority a) {
for (GrantedAuthority authority : this.mutableAuthorities) {
if (authority.equals(a)) {
return true;
}
}
return false;
}
public LdapUserDetails createUserDetails() {
Assert.notNull(this.instance, "Essence can only be used to create a single instance");
Assert.notNull(this.instance.username, "username must not be null");
Assert.notNull(this.instance.getDn(), "Distinguished name must not be null");
this.instance.authorities = Collections.unmodifiableList(this.mutableAuthorities);
LdapUserDetails newInstance = this.instance;
this.instance = null;
return newInstance;
}
public Collection<GrantedAuthority> getGrantedAuthorities() {
return this.mutableAuthorities;
}
public void setAccountNonExpired(boolean accountNonExpired) {
this.instance.accountNonExpired = accountNonExpired;
}
public void setAccountNonLocked(boolean accountNonLocked) {
this.instance.accountNonLocked = accountNonLocked;
}
public void setAuthorities(Collection<? extends GrantedAuthority> authorities) {
this.mutableAuthorities = new ArrayList<>();
this.mutableAuthorities.addAll(authorities); | }
public void setCredentialsNonExpired(boolean credentialsNonExpired) {
this.instance.credentialsNonExpired = credentialsNonExpired;
}
public void setDn(String dn) {
this.instance.dn = dn;
}
public void setDn(Name dn) {
this.instance.dn = dn.toString();
}
public void setEnabled(boolean enabled) {
this.instance.enabled = enabled;
}
public void setPassword(String password) {
this.instance.password = password;
}
public void setUsername(String username) {
this.instance.username = username;
}
public void setTimeBeforeExpiration(int timeBeforeExpiration) {
this.instance.timeBeforeExpiration = timeBeforeExpiration;
}
public void setGraceLoginsRemaining(int graceLoginsRemaining) {
this.instance.graceLoginsRemaining = graceLoginsRemaining;
}
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\LdapUserDetailsImpl.java | 1 |
请完成以下Java代码 | public static String getCalendarNameFromConfiguration(String jobHandlerConfiguration) {
try {
JsonNode cfgJson = readJsonValue(jobHandlerConfiguration);
JsonNode calendarNameNode = cfgJson.get(PROPERTYNAME_CALENDAR_NAME_EXPRESSION);
if (calendarNameNode != null) {
return calendarNameNode.asString();
} else {
return "";
}
} catch (JacksonException ex) {
// calendar name is not specified
return "";
}
}
public static String setEndDateToConfiguration(String jobHandlerConfiguration, String endDate) {
ObjectNode cfgJson = null;
try {
cfgJson = readJsonValueAsObjectNode(jobHandlerConfiguration);
} catch (JacksonException ex) {
// create the json config
cfgJson = createObjectNode();
cfgJson.put(PROPERTYNAME_TIMER_ACTIVITY_ID, jobHandlerConfiguration);
}
if (endDate != null) {
cfgJson.put(PROPERTYNAME_END_DATE_EXPRESSION, endDate);
}
return cfgJson.toString();
}
public static String getEndDateFromConfiguration(String jobHandlerConfiguration) {
try {
JsonNode cfgJson = readJsonValue(jobHandlerConfiguration);
JsonNode endDateNode = cfgJson.get(PROPERTYNAME_END_DATE_EXPRESSION);
if (endDateNode != null) {
return endDateNode.asString();
} else {
return null;
} | } catch (JacksonException ex) {
return null;
}
}
protected static ObjectNode createObjectNode() {
return CommandContextUtil.getProcessEngineConfiguration().getObjectMapper().createObjectNode();
}
protected static ObjectNode readJsonValueAsObjectNode(String config) throws JacksonException {
return (ObjectNode) readJsonValue(config);
}
protected static JsonNode readJsonValue(String config) throws JacksonException {
if (CommandContextUtil.getCommandContext() != null) {
return CommandContextUtil.getProcessEngineConfiguration().getObjectMapper().readTree(config);
} else {
return JsonMapper.shared().readTree(config);
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\jobexecutor\TimerEventHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserSyncRestEndpoint
{
public static final String ENDPOINT = MSV3ServerConstants.BACKEND_SYNC_REST_ENDPOINT + "/users";
@Autowired
private MSV3ServerAuthenticationService authService;
@Autowired
private MSV3ServerPeerService msv3ServerPeerService;
@PostMapping
public void processBatchEvent(@RequestBody final MSV3UserChangedBatchEvent batchEvent)
{
authService.handleEvent(batchEvent);
}
// TODO: remove this endpoint, it's only for testing/debugging
@PostMapping("/toRabbitMQ")
public void forwardEventToRabbitMQ(@RequestBody final MSV3UserChangedEvent event)
{
msv3ServerPeerService.publishUserChangedEvent(event);
} | @GetMapping
public List<MSV3UserChangedEvent> getAllUsers()
{
return authService.getAllUsers()
.stream()
.map(this::toMSV3UserChangedEvent)
.collect(ImmutableList.toImmutableList());
}
private MSV3UserChangedEvent toMSV3UserChangedEvent(final MSV3User user)
{
return MSV3UserChangedEvent.prepareCreatedOrUpdatedEvent(user.getMetasfreshMSV3UserId())
.username(user.getUsername())
.password("N/A")
.bpartnerId(user.getBpartnerId().getBpartnerId())
.bpartnerLocationId(user.getBpartnerId().getBpartnerLocationId())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\security\sync\UserSyncRestEndpoint.java | 2 |
请完成以下Java代码 | public void setM_Inventory_ID (int M_Inventory_ID)
{
if (M_Inventory_ID < 1)
set_Value (COLUMNNAME_M_Inventory_ID, null);
else
set_Value (COLUMNNAME_M_Inventory_ID, Integer.valueOf(M_Inventory_ID));
}
/** Get Phys.Inventory.
@return Parameters for a Physical Inventory
*/
public int getM_Inventory_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Inventory_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Move Confirm.
@param M_MovementConfirm_ID
Inventory Move Confirmation
*/
public void setM_MovementConfirm_ID (int M_MovementConfirm_ID)
{
if (M_MovementConfirm_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_MovementConfirm_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_MovementConfirm_ID, Integer.valueOf(M_MovementConfirm_ID));
}
/** Get Move Confirm.
@return Inventory Move Confirmation
*/
public int getM_MovementConfirm_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementConfirm_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_Movement getM_Movement() throws RuntimeException
{
return (I_M_Movement)MTable.get(getCtx(), I_M_Movement.Table_Name)
.getPO(getM_Movement_ID(), get_TrxName()); }
/** Set Inventory Move.
@param M_Movement_ID
Movement of Inventory
*/
public void setM_Movement_ID (int M_Movement_ID)
{
if (M_Movement_ID < 1)
set_Value (COLUMNNAME_M_Movement_ID, null);
else
set_Value (COLUMNNAME_M_Movement_ID, Integer.valueOf(M_Movement_ID));
}
/** Get Inventory Move.
@return Movement of Inventory
*/ | public int getM_Movement_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Movement_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementConfirm.java | 1 |
请完成以下Java代码 | public static <T> void registerJUnitBean(@NonNull final T beanImpl)
{
instance.junitRegisteredBeans.registerJUnitBean(beanImpl);
}
public static <BT, T extends BT> void registerJUnitBean(@NonNull final Class<BT> beanType, @NonNull final T beanImpl)
{
instance.junitRegisteredBeans.registerJUnitBean(beanType, beanImpl);
}
public static <BT, T extends BT> void registerJUnitBeans(@NonNull final Class<BT> beanType, @NonNull final List<T> beansToAdd)
{
instance.junitRegisteredBeans.registerJUnitBeans(beanType, beansToAdd);
}
public static <T> Lazy<T> lazyBean(@NonNull final Class<T> requiredType)
{
return new Lazy<>(requiredType, null);
}
public static <T> Lazy<T> lazyBean(@NonNull final Class<T> requiredType, @Nullable final T initialBean)
{
return new Lazy<>(requiredType, initialBean);
}
public Optional<String> getProperty(@NonNull final String name)
{
if (applicationContext != null)
{
final String springContextValue = StringUtils.trimBlankToNull(applicationContext.getEnvironment().getProperty(name));
if (springContextValue != null)
{
logger.debug("Returning the spring context's value {}={} instead of looking up the AD_SysConfig record", name, springContextValue);
return Optional.of(springContextValue);
}
}
else
{
// If there is no Spring context then go an check JVM System Properties.
// Usually we will get here when we will run some tools based on metasfresh framework.
final Properties systemProperties = System.getProperties(); | final String systemPropertyValue = StringUtils.trimBlankToNull(systemProperties.getProperty(name));
if (systemPropertyValue != null)
{
logger.debug("Returning the JVM system property's value {}={} instead of looking up the AD_SysConfig record", name, systemPropertyValue);
return Optional.of(systemPropertyValue);
}
// If there is no JVM System Property then go and check environment variables
return StringUtils.trimBlankToOptional(System.getenv(name));
}
return Optional.empty();
}
//
//
//
@ToString
public static final class Lazy<T>
{
private final Class<T> requiredType;
private T bean;
private Lazy(@NonNull final Class<T> requiredType, @Nullable final T initialBean)
{
this.requiredType = requiredType;
this.bean = initialBean;
}
@NonNull
public T get()
{
T bean = this.bean;
if (bean == null)
{
bean = this.bean = instance.getBean(requiredType);
}
return bean;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\SpringContextHolder.java | 1 |
请完成以下Java代码 | public class SignalThrowingEventListener extends BaseDelegateEventListener {
protected String signalName;
protected boolean processInstanceScope = true;
@Override
public void onEvent(FlowableEvent event) {
if (isValidEvent(event) && event instanceof FlowableEngineEvent) {
FlowableEngineEvent engineEvent = (FlowableEngineEvent) event;
if (engineEvent.getProcessInstanceId() == null && processInstanceScope) {
throw new ActivitiIllegalArgumentException(
"Cannot throw process-instance scoped signal, since the dispatched event is not part of an ongoing process instance");
}
CommandContext commandContext = Context.getCommandContext();
List<SignalEventSubscriptionEntity> subscriptionEntities = null;
if (processInstanceScope) {
subscriptionEntities = commandContext.getEventSubscriptionEntityManager()
.findSignalEventSubscriptionsByProcessInstanceAndEventName(engineEvent.getProcessInstanceId(), signalName);
} else {
String tenantId = null;
if (engineEvent.getProcessDefinitionId() != null) {
ProcessDefinition processDefinition = commandContext.getProcessEngineConfiguration()
.getDeploymentManager().findDeployedProcessDefinitionById(engineEvent.getProcessDefinitionId());
tenantId = processDefinition.getTenantId();
}
subscriptionEntities = commandContext.getEventSubscriptionEntityManager()
.findSignalEventSubscriptionsByEventName(signalName, tenantId);
}
for (SignalEventSubscriptionEntity signalEventSubscriptionEntity : subscriptionEntities) {
signalEventSubscriptionEntity.eventReceived(null, false);
} | }
}
public void setSignalName(String signalName) {
this.signalName = signalName;
}
public void setProcessInstanceScope(boolean processInstanceScope) {
this.processInstanceScope = processInstanceScope;
}
@Override
public boolean isFailOnException() {
return true;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\SignalThrowingEventListener.java | 1 |
请完成以下Java代码 | public ServletOutputStream getOutputStream() {
return new ServletOutputStream() {
@Override
public boolean isReady() {
return true;
}
@Override
public void setWriteListener(WriteListener writeListener) {
}
@Override
public void write(int b) {
outputStream.write(b);
}
};
} | @Override
public PrintWriter getWriter() {
return writer;
}
@Override
public void flushBuffer() throws IOException {
super.flushBuffer();
writer.flush();
}
public String getBodyAsString() {
writer.flush();
return outputStream.toString();
}
} | repos\tutorials-master\logging-modules\log-all-requests\src\main\java\com\baeldung\logallrequests\ResponseWrapper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LocatorProperties getLocator() {
return this.locator;
}
public String[] getLocators() {
return this.locators;
}
public void setLocators(String[] locators) {
this.locators = locators;
}
public LoggingProperties getLogging() {
return this.logging;
}
public ManagementProperties getManagement() {
return this.management;
}
public ManagerProperties getManager() {
return this.manager;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
} | public PdxProperties getPdx() {
return this.pdx;
}
public PoolProperties getPool() {
return this.pool;
}
public SecurityProperties getSecurity() {
return this.security;
}
public ServiceProperties getService() {
return this.service;
}
public boolean isUseBeanFactoryLocator() {
return this.useBeanFactoryLocator;
}
public void setUseBeanFactoryLocator(boolean useBeanFactoryLocator) {
this.useBeanFactoryLocator = useBeanFactoryLocator;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\GemFireProperties.java | 2 |
请完成以下Java代码 | public AuthorizationDto getAuthorization(UriInfo context) {
Authorization dbAuthorization = getDbAuthorization();
return AuthorizationDto.fromAuthorization(dbAuthorization, getProcessEngine().getProcessEngineConfiguration());
}
public void deleteAuthorization() {
Authorization dbAuthorization = getDbAuthorization();
authorizationService.deleteAuthorization(dbAuthorization.getId());
}
public void updateAuthorization(AuthorizationDto dto) {
// get db auth
Authorization dbAuthorization = getDbAuthorization();
// copy values from dto
AuthorizationDto.update(dto, dbAuthorization, getProcessEngine().getProcessEngineConfiguration());
// save
authorizationService.saveAuthorization(dbAuthorization);
}
public ResourceOptionsDto availableOperations(UriInfo context) {
ResourceOptionsDto dto = new ResourceOptionsDto();
URI uri = context.getBaseUriBuilder()
.path(relativeRootResourcePath)
.path(AuthorizationRestService.PATH)
.path(resourceId)
.build();
dto.addReflexiveLink(uri, HttpMethod.GET, "self");
if (isAuthorized(DELETE)) {
dto.addReflexiveLink(uri, HttpMethod.DELETE, "delete"); | }
if (isAuthorized(UPDATE)) {
dto.addReflexiveLink(uri, HttpMethod.PUT, "update");
}
return dto;
}
// utils //////////////////////////////////////////////////
protected Authorization getDbAuthorization() {
Authorization dbAuthorization = authorizationService.createAuthorizationQuery()
.authorizationId(resourceId)
.singleResult();
if (dbAuthorization == null) {
throw new InvalidRequestException(Status.NOT_FOUND, "Authorization with id " + resourceId + " does not exist.");
} else {
return dbAuthorization;
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\sub\authorization\impl\AuthorizationResourceImpl.java | 1 |
请完成以下Java代码 | public ResponseEntity<Object> getRoleLevel(){
return new ResponseEntity<>(Dict.create().set("level", getLevels(null)),HttpStatus.OK);
}
@Log("新增角色")
@ApiOperation("新增角色")
@PostMapping
@PreAuthorize("@el.check('roles:add')")
public ResponseEntity<Object> createRole(@Validated @RequestBody Role resources){
if (resources.getId() != null) {
throw new BadRequestException("A new "+ ENTITY_NAME +" cannot already have an ID");
}
getLevels(resources.getLevel());
roleService.create(resources);
return new ResponseEntity<>(HttpStatus.CREATED);
}
@Log("修改角色")
@ApiOperation("修改角色")
@PutMapping
@PreAuthorize("@el.check('roles:edit')")
public ResponseEntity<Object> updateRole(@Validated(Role.Update.class) @RequestBody Role resources){
getLevels(resources.getLevel());
roleService.update(resources);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("修改角色菜单")
@ApiOperation("修改角色菜单")
@PutMapping(value = "/menu")
@PreAuthorize("@el.check('roles:edit')")
public ResponseEntity<Object> updateRoleMenu(@RequestBody Role resources){
RoleDto role = roleService.findById(resources.getId());
getLevels(role.getLevel());
roleService.updateMenu(resources,role);
return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}
@Log("删除角色")
@ApiOperation("删除角色")
@DeleteMapping | @PreAuthorize("@el.check('roles:del')")
public ResponseEntity<Object> deleteRole(@RequestBody Set<Long> ids){
for (Long id : ids) {
RoleDto role = roleService.findById(id);
getLevels(role.getLevel());
}
// 验证是否被用户关联
roleService.verification(ids);
roleService.delete(ids);
return new ResponseEntity<>(HttpStatus.OK);
}
/**
* 获取用户的角色级别
* @return /
*/
private int getLevels(Integer level){
List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
int min = Collections.min(levels);
if(level != null){
if(level < min){
throw new BadRequestException("权限不足,你的角色级别:" + min + ",低于操作的角色级别:" + level);
}
}
return min;
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\rest\RoleController.java | 1 |
请完成以下Java代码 | public void setJasperProcess(org.compiere.model.I_AD_Process JasperProcess)
{
set_ValueFromPO(COLUMNNAME_JasperProcess_ID, org.compiere.model.I_AD_Process.class, JasperProcess);
}
/** Set Jasper Process.
@param JasperProcess_ID
The Jasper Process used by the printengine if any process defined
*/
@Override
public void setJasperProcess_ID (int JasperProcess_ID)
{
if (JasperProcess_ID < 1)
set_Value (COLUMNNAME_JasperProcess_ID, null);
else
set_Value (COLUMNNAME_JasperProcess_ID, Integer.valueOf(JasperProcess_ID));
}
/** Get Jasper Process.
@return The Jasper Process used by the printengine if any process defined
*/
@Override
public int getJasperProcess_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_JasperProcess_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{ | return (java.lang.String)get_Value(COLUMNNAME_Name);
}
/** Set Betreff.
@param Subject
Mail Betreff
*/
@Override
public void setSubject (java.lang.String Subject)
{
set_Value (COLUMNNAME_Subject, Subject);
}
/** Get Betreff.
@return Mail Betreff
*/
@Override
public java.lang.String getSubject ()
{
return (java.lang.String)get_Value(COLUMNNAME_Subject);
}
/** Set Text.
@param TextSnippet Text */
@Override
public void setTextSnippet (java.lang.String TextSnippet)
{
set_Value (COLUMNNAME_TextSnippet, TextSnippet);
}
/** Get Text.
@return Text */
@Override
public java.lang.String getTextSnippet ()
{
return (java.lang.String)get_Value(COLUMNNAME_TextSnippet);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\letters\model\X_AD_BoilerPlate.java | 1 |
请完成以下Java代码 | protected ProjectType determineProjectType(InitializrServiceMetadata metadata) {
if (this.type != null) {
ProjectType result = metadata.getProjectTypes().get(this.type);
if (result == null) {
throw new ReportableException(
("No project type with id '" + this.type + "' - check the service capabilities (--list)"));
}
return result;
}
else if (isDetectType()) {
Map<String, ProjectType> types = new HashMap<>(metadata.getProjectTypes());
if (this.build != null) {
filter(types, "build", this.build);
}
if (this.format != null) {
filter(types, "format", this.format);
}
if (types.size() == 1) {
return types.values().iterator().next();
}
else if (types.isEmpty()) {
throw new ReportableException("No type found with build '" + this.build + "' and format '" + this.format
+ "' check the service capabilities (--list)");
}
else {
throw new ReportableException("Multiple types found with build '" + this.build + "' and format '"
+ this.format + "' use --type with a more specific value " + types.keySet());
}
}
else {
ProjectType defaultType = metadata.getDefaultType();
if (defaultType == null) {
throw new ReportableException(("No project type is set and no default is defined. "
+ "Check the service capabilities (--list)")); | }
return defaultType;
}
}
/**
* Resolve the artifactId to use or {@code null} if it should not be customized.
* @return the artifactId
*/
protected @Nullable String resolveArtifactId() {
if (this.artifactId != null) {
return this.artifactId;
}
if (this.output != null) {
int i = this.output.lastIndexOf('.');
return (i != -1) ? this.output.substring(0, i) : this.output;
}
return null;
}
private static void filter(Map<String, ProjectType> projects, String tag, String tagValue) {
projects.entrySet().removeIf((entry) -> !tagValue.equals(entry.getValue().getTags().get(tag)));
}
} | repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\init\ProjectGenerationRequest.java | 1 |
请完成以下Java代码 | public String[] namedEntityRecognize(String[] wordArray, String[] posArray)
{
if (neRecognizer == null)
{
throw new IllegalStateException("未提供命名实体识别模型");
}
return recognize(wordArray, posArray);
}
/**
* 在线学习
*
* @param segmentedTaggedSentence 已分词、标好词性和命名实体的人民日报2014格式的句子
* @return 是否学习成果(失败的原因是句子格式不合法)
*/
public boolean learn(String segmentedTaggedSentence)
{
Sentence sentence = Sentence.create(segmentedTaggedSentence);
return learn(sentence);
}
/**
* 在线学习
*
* @param sentence 已分词、标好词性和命名实体的人民日报2014格式的句子
* @return 是否学习成果(失败的原因是句子格式不合法)
*/
public boolean learn(Sentence sentence)
{
CharTable.normalize(sentence);
if (!getPerceptronSegmenter().learn(sentence)) return false;
if (posTagger != null && !getPerceptronPOSTagger().learn(sentence)) return false;
if (neRecognizer != null && !getPerceptionNERecognizer().learn(sentence)) return false;
return true;
} | /**
* 获取分词器
*
* @return
*/
public PerceptronSegmenter getPerceptronSegmenter()
{
return (PerceptronSegmenter) segmenter;
}
/**
* 获取词性标注器
*
* @return
*/
public PerceptronPOSTagger getPerceptronPOSTagger()
{
return (PerceptronPOSTagger) posTagger;
}
/**
* 获取命名实体识别器
*
* @return
*/
public PerceptronNERecognizer getPerceptionNERecognizer()
{
return (PerceptronNERecognizer) neRecognizer;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronLexicalAnalyzer.java | 1 |
请完成以下Java代码 | public String setValue(final String columnName, final Object value)
{
final Document document = getDocument();
document.setValue(columnName, value, REASON_Value_DirectSetOnCalloutRecord);
return "";
}
@Override
public void dataRefresh()
{
final Document document = getDocument();
document.refreshFromRepository();
}
@Override
public void dataRefreshAll()
{
// NOTE: there is no "All" concept here, so we are just refreshing this document
final Document document = getDocument();
document.refreshFromRepository();
}
@Override
public void dataRefreshRecursively() | {
// TODO dataRefreshRecursively: refresh document and it's children
throw new UnsupportedOperationException();
}
@Override
public boolean dataSave(final boolean manualCmd)
{
// TODO dataSave: save document but also update the DocumentsCollection!
throw new UnsupportedOperationException();
}
@Override
public boolean isLookupValuesContainingId(@NonNull final String columnName, @NonNull final RepoIdAware id)
{
//Querying all values because getLookupValueById doesn't take validation rul into consideration.
// TODO: Implement possibility to fetch sqllookupbyid with validation rule considered.
return getDocument().getFieldLookupValues(columnName).containsId(id);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentAsCalloutRecord.java | 1 |
请完成以下Java代码 | public boolean load(ByteArray byteArray)
{
template = byteArray.nextUTF();
int size = byteArray.nextInt();
offsetList = new ArrayList<int[]>(size);
for (int i = 0; i < size; ++i)
{
offsetList.add(new int[]{byteArray.nextInt(), byteArray.nextInt()});
}
size = byteArray.nextInt();
delimiterList = new ArrayList<String>(size);
for (int i = 0; i < size; ++i)
{
delimiterList.add(byteArray.nextUTF());
}
return true;
} | @Override
public String toString()
{
final StringBuilder sb = new StringBuilder("FeatureTemplate{");
sb.append("template='").append(template).append('\'');
sb.append(", delimiterList=").append(delimiterList);
sb.append('}');
return sb.toString();
}
public String getTemplate()
{
return template;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\FeatureTemplate.java | 1 |
请完成以下Java代码 | public void setM_Product_ID (final int M_Product_ID)
{
if (M_Product_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Product_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID);
}
@Override
public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setPostCalculationAmt (final BigDecimal PostCalculationAmt)
{
set_Value (COLUMNNAME_PostCalculationAmt, PostCalculationAmt);
}
@Override
public BigDecimal getPostCalculationAmt()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PostCalculationAmt);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setPP_Order_Cost_ID (final int PP_Order_Cost_ID)
{
if (PP_Order_Cost_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Cost_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Cost_ID, PP_Order_Cost_ID);
}
@Override
public int getPP_Order_Cost_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Cost_ID);
}
/**
* PP_Order_Cost_TrxType AD_Reference_ID=540941
* Reference name: PP_Order_Cost_TrxType
*/
public static final int PP_ORDER_COST_TRXTYPE_AD_Reference_ID=540941;
/** MainProduct = MR */
public static final String PP_ORDER_COST_TRXTYPE_MainProduct = "MR";
/** MaterialIssue = MI */
public static final String PP_ORDER_COST_TRXTYPE_MaterialIssue = "MI";
/** ResourceUtilization = RU */
public static final String PP_ORDER_COST_TRXTYPE_ResourceUtilization = "RU";
/** ByProduct = BY */
public static final String PP_ORDER_COST_TRXTYPE_ByProduct = "BY";
/** CoProduct = CO */
public static final String PP_ORDER_COST_TRXTYPE_CoProduct = "CO";
@Override
public void setPP_Order_Cost_TrxType (final java.lang.String PP_Order_Cost_TrxType)
{
set_Value (COLUMNNAME_PP_Order_Cost_TrxType, PP_Order_Cost_TrxType);
} | @Override
public java.lang.String getPP_Order_Cost_TrxType()
{
return get_ValueAsString(COLUMNNAME_PP_Order_Cost_TrxType);
}
@Override
public org.eevolution.model.I_PP_Order getPP_Order()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class);
}
@Override
public void setPP_Order(final org.eevolution.model.I_PP_Order PP_Order)
{
set_ValueFromPO(COLUMNNAME_PP_Order_ID, org.eevolution.model.I_PP_Order.class, PP_Order);
}
@Override
public void setPP_Order_ID (final int PP_Order_ID)
{
if (PP_Order_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_ID, PP_Order_ID);
}
@Override
public int getPP_Order_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Cost.java | 1 |
请完成以下Java代码 | public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
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_T_Report.java | 1 |
请完成以下Java代码 | public int getDLM_Partition_Config_ID()
{
final Integer ii = (Integer)get_Value(COLUMNNAME_DLM_Partition_Config_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/**
* Set Standard.
*
* @param IsDefault
* Default value
*/
@Override
public void setIsDefault(final boolean IsDefault)
{
set_Value(COLUMNNAME_IsDefault, Boolean.valueOf(IsDefault));
}
/**
* Get Standard.
*
* @return Default value
*/
@Override
public boolean isDefault()
{
final Object oo = get_Value(COLUMNNAME_IsDefault);
if (oo != null)
{
if (oo instanceof Boolean)
{
return ((Boolean)oo).booleanValue();
}
return "Y".equals(oo);
}
return false;
}
/** | * Set Name.
*
* @param Name
* Alphanumeric identifier of the entity
*/
@Override
public void setName(final java.lang.String Name)
{
set_Value(COLUMNNAME_Name, Name);
}
/**
* Get Name.
*
* @return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java-gen\de\metas\dlm\model\X_DLM_Partition_Config.java | 1 |
请完成以下Java代码 | public void walk() {
}
/**
* Check this {@link #move(String) Move} method for direction oriented movement.
*/
public void move() {
}
public void move(String direction) {
}
/**
* Additionally, check this {@link Animal#run(String) Run} method for direction based run.
*/
public void run() { | }
/**
* Also consider checking {@link com.baeldung.vehicle.Vehicle#Vehicle() Vehicle} constructor to initialize vehicle object.
*/
public void goToWork() {
}
/**
* Have a look at {@link Car#getNumberOfSeats() SeatsAvailability} method for checking the available seats needed for driving.
*/
public void drive() {
}
} | repos\tutorials-master\core-java-modules\core-java-lang-4\src\main\java\com\baeldung\javadocmemberreference\Person.java | 1 |
请完成以下Java代码 | public class LieferavisBestaetigenType {
@XmlElement(name = "Lieferscheinnummer", required = true)
protected List<String> lieferscheinnummer;
/**
* Gets the value of the lieferscheinnummer property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the lieferscheinnummer property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre> | * getLieferscheinnummer().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link String }
*
*
*/
public List<String> getLieferscheinnummer() {
if (lieferscheinnummer == null) {
lieferscheinnummer = new ArrayList<String>();
}
return this.lieferscheinnummer;
}
} | 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\LieferavisBestaetigenType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ZonedDateTime convert(LocalDateTime localDateTime) {
// Be aware - we are using the UTC timezone
return ZonedDateTime.of(localDateTime, ZoneOffset.UTC);
}
}
@WritingConverter
public enum ZonedDateTimeWriteConverter implements Converter<ZonedDateTime, LocalDateTime> {
INSTANCE;
@Override
public LocalDateTime convert(ZonedDateTime zonedDateTime) {
return zonedDateTime.toLocalDateTime();
}
}
@WritingConverter
public enum DurationWriteConverter implements Converter<Duration, Long> {
INSTANCE;
@Override | public Long convert(Duration source) {
return source != null ? source.toMillis() : null;
}
}
@ReadingConverter
public enum DurationReadConverter implements Converter<Long, Duration> {
INSTANCE;
@Override
public Duration convert(Long source) {
return source != null ? Duration.ofMillis(source) : null;
}
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\config\DatabaseConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | GoogleCredentials googleCredentials() {
try {
if (firebaseProperties.getServiceAccount() != null) {
try( InputStream is = firebaseProperties.getServiceAccount().getInputStream()) {
return GoogleCredentials.fromStream(is);
}
}
else {
// Use standard credentials chain. Useful when running inside GKE
return GoogleCredentials.getApplicationDefault();
}
}
catch (IOException ioe) {
throw new RuntimeException(ioe);
}
} | @Bean
FirebaseApp firebaseApp(GoogleCredentials credentials) {
FirebaseOptions options = FirebaseOptions.builder()
.setCredentials(credentials)
.build();
return FirebaseApp.initializeApp(options);
}
@Bean
FirebaseMessaging firebaseMessaging(FirebaseApp firebaseApp) {
return FirebaseMessaging.getInstance(firebaseApp);
}
} | repos\tutorials-master\gcp-firebase\src\main\java\com\baeldung\gcp\firebase\publisher\config\FirebaseConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static void main(String[] args) {
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("orderPrice", "0.11");
paramMap.put("payWayCode", "WEIXIN");// 支付方式编码 支付宝: ALIPAY 微信:WEIXIN
String orderNo = String.valueOf(System.currentTimeMillis()); // 订单编号
paramMap.put("orderNo", orderNo);
Date orderDate = new Date();//订单日期
String orderDateStr = new SimpleDateFormat("yyyyMMdd").format(orderDate);// 订单日期
paramMap.put("orderDate", orderDateStr);
Date orderTime = new Date();//订单时间
String orderTimeStr = new SimpleDateFormat("yyyyMMddHHmmss").format(orderTime);// 订单时间
paramMap.put("orderTime", orderTimeStr);
paramMap.put("payKey", PayConfigUtil.readConfig("payKey"));
paramMap.put("productName", "test");
String notifyUrl = "https://www.baidu.com"; // 后台消息通知Url
paramMap.put("notifyUrl", notifyUrl);
paramMap.put("openId", "okocOwGt2w6uasvHEakh3SlhjcT4");
String orderIp = PayConfigUtil.readConfig("orderIp"); // 下单IP
paramMap.put("orderIp", orderIp);
paramMap.put("remark", "test");
////////////扩展字段,选填,原值返回///////////
String field1 = "1"; // 扩展字段1
paramMap.put("field1", field1);
String field2 = "2"; // 扩展字段2
paramMap.put("field2", field2);
String field3 = "3"; // 扩展字段3
paramMap.put("field3", field3);
String field4 = "4"; // 扩展字段4
paramMap.put("field4", field4);
String field5 = "5"; // 扩展字段5
paramMap.put("field5", field5);
/////签名及生成请求API的方法///
String sign = MerchantApiUtil.getSign(paramMap, PayConfigUtil.readConfig("paySecret"));
paramMap.put("sign", sign); | //String buildRequest = MerchantApiUtil.buildRequest(paramMap, "get", "确定", PayConfigUtil.readConfig("programpayUrl"));
HttpClient httpClient = HttpClients.createDefault();
HttpPost post = new HttpPost(PayConfigUtil.readConfig("programpayUrl"));
try {
List<NameValuePair> list = new ArrayList<>();
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
list.add(new BasicNameValuePair(entry.getKey(),String.valueOf(entry.getValue())));
}
post.setEntity(new UrlEncodedFormEntity(list,"UTF-8"));
HttpResponse httpResponse = httpClient.execute(post);
String result = EntityUtils.toString(httpResponse.getEntity());
System.out.println(result);
} catch (Exception e) {
e.printStackTrace();
}
// System.out.println(buildRequest);
}
} | repos\roncoo-pay-master\roncoo-pay-web-sample-shop\src\main\java\com\roncoo\pay\controller\RoncooPayController.java | 2 |
请完成以下Java代码 | public de.metas.async.model.I_C_Queue_WorkPackage getC_Queue_WorkPackage()
{
return get_ValueAsPO(COLUMNNAME_C_Queue_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class);
}
@Override
public void setC_Queue_WorkPackage(de.metas.async.model.I_C_Queue_WorkPackage C_Queue_WorkPackage)
{
set_ValueFromPO(COLUMNNAME_C_Queue_WorkPackage_ID, de.metas.async.model.I_C_Queue_WorkPackage.class, C_Queue_WorkPackage);
}
/** Set WorkPackage Queue.
@param C_Queue_WorkPackage_ID WorkPackage Queue */
@Override
public void setC_Queue_WorkPackage_ID (int C_Queue_WorkPackage_ID)
{
if (C_Queue_WorkPackage_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_ID, Integer.valueOf(C_Queue_WorkPackage_ID));
}
/** Get WorkPackage Queue.
@return WorkPackage Queue */
@Override
public int getC_Queue_WorkPackage_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Workpackage audit/log table.
@param C_Queue_WorkPackage_Log_ID Workpackage audit/log table */
@Override
public void setC_Queue_WorkPackage_Log_ID (int C_Queue_WorkPackage_Log_ID)
{
if (C_Queue_WorkPackage_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Queue_WorkPackage_Log_ID, Integer.valueOf(C_Queue_WorkPackage_Log_ID));
}
/** Get Workpackage audit/log table.
@return Workpackage audit/log table */
@Override
public int getC_Queue_WorkPackage_Log_ID () | {
Integer ii = (Integer)get_Value(COLUMNNAME_C_Queue_WorkPackage_Log_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Message Text.
@param MsgText
Textual Informational, Menu or Error Message
*/
@Override
public void setMsgText (java.lang.String MsgText)
{
set_ValueNoCheck (COLUMNNAME_MsgText, MsgText);
}
/** Get Message Text.
@return Textual Informational, Menu or Error Message
*/
@Override
public java.lang.String getMsgText ()
{
return (java.lang.String)get_Value(COLUMNNAME_MsgText);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java-gen\de\metas\async\model\X_C_Queue_WorkPackage_Log.java | 1 |
请完成以下Java代码 | public void setLastPages (int LastPages)
{
set_Value (COLUMNNAME_LastPages, Integer.valueOf(LastPages));
}
/** Get Letzte Seiten.
@return Letzte Seiten */
@Override
public int getLastPages ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_LastPages);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override | public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_PrinterRouting.java | 1 |
请完成以下Java代码 | public int getGrade() {
return grade;
}
public void setGrade(int grade) {
this.grade = grade;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) | return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
CourseRegistration other = (CourseRegistration) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
} | repos\tutorials-master\persistence-modules\spring-jpa\src\main\java\com\baeldung\manytomany\model\CourseRegistration.java | 1 |
请完成以下Java代码 | private ImmutableList<String> getValueList(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider)
{
return streamEligibleConfigs(attributeType, valueProvider)
.map(config -> valueProvider.apply(config.getAttributeValue()))
.filter(Check::isNotBlank)
.collect(ImmutableList.toImmutableList());
}
public ImmutableList<String> getDetailGroupKeysForType(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider)
{
return streamEligibleConfigs(attributeType, valueProvider)
.map(JsonMappingConfig::getGroupKey)
.filter(Check::isNotBlank)
.distinct()
.collect(ImmutableList.toImmutableList());
}
public List<JsonDetail> getDetailsForGroupAndType(
@NonNull final String attributeGroupKey,
@NonNull final String attributeType,
@NonNull final Function<String, String> valueProvider)
{
final Map<Integer, String> detailsByKindId = streamEligibleConfigs(attributeType, valueProvider)
.filter(config -> attributeGroupKey.equals(config.getGroupKey())) | .filter(config -> Check.isNotBlank(config.getAttributeKey()))
.map(config -> new AbstractMap.SimpleImmutableEntry<>(
Integer.parseInt(config.getAttributeKey()),
valueProvider.apply(config.getAttributeValue())))
.filter(entry -> Check.isNotBlank(entry.getValue()))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.joining(" "))));
return detailsByKindId.entrySet().stream()
.map(entry -> JsonDetail.builder()
.kindId(entry.getKey())
.value(entry.getValue())
.build())
.collect(Collectors.toList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftMappingConfigs.java | 1 |
请完成以下Java代码 | public void deleteHistoricIdentityLinksLogByTaskProcessInstanceIds(List<String> processInstanceIds) {
getDbEntityManager().deletePreserveOrder(HistoricIdentityLinkLogEntity.class, "deleteHistoricIdentityLinksByTaskProcessInstanceIds", processInstanceIds);
}
public void deleteHistoricIdentityLinksLogByTaskCaseInstanceIds(List<String> caseInstanceIds) {
getDbEntityManager().deletePreserveOrder(HistoricIdentityLinkLogEntity.class, "deleteHistoricIdentityLinksByTaskCaseInstanceIds", caseInstanceIds);
}
public DbOperation deleteHistoricIdentityLinkLogByRemovalTime(Date removalTime, int minuteFrom, int minuteTo, int batchSize) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("removalTime", removalTime);
if (minuteTo - minuteFrom + 1 < 60) {
parameters.put("minuteFrom", minuteFrom);
parameters.put("minuteTo", minuteTo);
}
parameters.put("batchSize", batchSize); | return getDbEntityManager()
.deletePreserveOrder(HistoricIdentityLinkLogEntity.class, "deleteHistoricIdentityLinkLogByRemovalTime",
new ListQueryParameterObject(parameters, 0, batchSize));
}
protected void configureQuery(HistoricIdentityLinkLogQueryImpl query) {
getAuthorizationManager().configureHistoricIdentityLinkQuery(query);
getTenantManager().configureQuery(query);
}
protected boolean isHistoryEventProduced() {
HistoryLevel historyLevel = Context.getProcessEngineConfiguration().getHistoryLevel();
return historyLevel.isHistoryEventProduced(HistoryEventTypes.IDENTITY_LINK_ADD, null) ||
historyLevel.isHistoryEventProduced(HistoryEventTypes.IDENTITY_LINK_DELETE, null);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricIdentityLinkLogManager.java | 1 |
请完成以下Java代码 | public void setK_INDEX_ID (int K_INDEX_ID)
{
if (K_INDEX_ID < 1)
set_ValueNoCheck (COLUMNNAME_K_INDEX_ID, null);
else
set_ValueNoCheck (COLUMNNAME_K_INDEX_ID, Integer.valueOf(K_INDEX_ID));
}
/** Get Index.
@return Text Search Index
*/
public int getK_INDEX_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_INDEX_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_R_RequestType getR_RequestType() throws RuntimeException
{
return (I_R_RequestType)MTable.get(getCtx(), I_R_RequestType.Table_Name) | .getPO(getR_RequestType_ID(), get_TrxName()); }
/** Set Request Type.
@param R_RequestType_ID
Type of request (e.g. Inquiry, Complaint, ..)
*/
public void setR_RequestType_ID (int R_RequestType_ID)
{
if (R_RequestType_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_R_RequestType_ID, Integer.valueOf(R_RequestType_ID));
}
/** Get Request Type.
@return Type of request (e.g. Inquiry, Complaint, ..)
*/
public int getR_RequestType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_RequestType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Source Updated.
@param SourceUpdated
Date the source document was updated
*/
public void setSourceUpdated (Timestamp SourceUpdated)
{
set_Value (COLUMNNAME_SourceUpdated, SourceUpdated);
}
/** Get Source Updated.
@return Date the source document was updated
*/
public Timestamp getSourceUpdated ()
{
return (Timestamp)get_Value(COLUMNNAME_SourceUpdated);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Index.java | 1 |
请完成以下Java代码 | public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
/**
* PersonalDataCategory AD_Reference_ID=540857
* Reference name: PersonalDataCategory
*/
public static final int PERSONALDATACATEGORY_AD_Reference_ID=540857;
/** NotPersonal = NP */
public static final String PERSONALDATACATEGORY_NotPersonal = "NP";
/** Personal = P */
public static final String PERSONALDATACATEGORY_Personal = "P";
/** SensitivePersonal = SP */
public static final String PERSONALDATACATEGORY_SensitivePersonal = "SP";
@Override
public void setPersonalDataCategory (final @Nullable java.lang.String PersonalDataCategory)
{
set_Value (COLUMNNAME_PersonalDataCategory, PersonalDataCategory);
}
@Override
public java.lang.String getPersonalDataCategory()
{
return get_ValueAsString(COLUMNNAME_PersonalDataCategory);
}
@Override
public void setReadOnlyLogic (final @Nullable java.lang.String ReadOnlyLogic)
{
set_Value (COLUMNNAME_ReadOnlyLogic, ReadOnlyLogic);
}
@Override
public java.lang.String getReadOnlyLogic()
{
return get_ValueAsString(COLUMNNAME_ReadOnlyLogic);
}
@Override
public void setSelectionColumnSeqNo (final int SelectionColumnSeqNo)
{
set_Value (COLUMNNAME_SelectionColumnSeqNo, SelectionColumnSeqNo);
}
@Override
public int getSelectionColumnSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SelectionColumnSeqNo);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setTechnicalNote (final @Nullable java.lang.String TechnicalNote)
{
set_Value (COLUMNNAME_TechnicalNote, TechnicalNote);
} | @Override
public java.lang.String getTechnicalNote()
{
return get_ValueAsString(COLUMNNAME_TechnicalNote);
}
@Override
public void setValueMax (final @Nullable java.lang.String ValueMax)
{
set_Value (COLUMNNAME_ValueMax, ValueMax);
}
@Override
public java.lang.String getValueMax()
{
return get_ValueAsString(COLUMNNAME_ValueMax);
}
@Override
public void setValueMin (final @Nullable java.lang.String ValueMin)
{
set_Value (COLUMNNAME_ValueMin, ValueMin);
}
@Override
public java.lang.String getValueMin()
{
return get_ValueAsString(COLUMNNAME_ValueMin);
}
@Override
public void setVersion (final BigDecimal Version)
{
set_Value (COLUMNNAME_Version, Version);
}
@Override
public BigDecimal getVersion()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Version);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVFormat (final @Nullable java.lang.String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
@Override
public java.lang.String getVFormat()
{
return get_ValueAsString(COLUMNNAME_VFormat);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Column.java | 1 |
请完成以下Java代码 | public List<LaneSet> getLaneSets() {
if(laneSets == null) {
laneSets = new ArrayList<LaneSet>();
}
return laneSets;
}
public void setParticipantProcess(ParticipantProcess participantProcess) {
this.participantProcess = participantProcess;
}
public ParticipantProcess getParticipantProcess() {
return participantProcess;
}
public boolean isScope() {
return true;
} | public PvmScope getEventScope() {
return null;
}
public ScopeImpl getFlowScope() {
return null;
}
public PvmScope getLevelOfSubprocessScope() {
return null;
}
@Override
public boolean isSubProcessScope() {
return true;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\ProcessDefinitionImpl.java | 1 |
请完成以下Java代码 | public void setMovementLine (MMovementLine line)
{
setM_MovementLine_ID(line.getM_MovementLine_ID());
setTargetQty(line.getMovementQty());
setConfirmedQty(getTargetQty()); // suggestion
m_line = line;
} // setMovementLine
/**
* Get Movement Line
* @return line
*/
public MMovementLine getLine()
{
if (m_line == null)
m_line = new MMovementLine (getCtx(), getM_MovementLine_ID(), get_TrxName());
return m_line;
} // getLine
/**
* Process Confirmation Line.
* - Update Movement Line
* @return success
*/
public boolean processLine ()
{
MMovementLine line = getLine();
line.setTargetQty(getTargetQty());
line.setMovementQty(getConfirmedQty());
line.setConfirmedQty(getConfirmedQty());
line.setScrappedQty(getScrappedQty());
return line.save(get_TrxName());
} // processConfirmation
/**
* Is Fully Confirmed
* @return true if Target = Confirmed qty
*/
public boolean isFullyConfirmed()
{ | return getTargetQty().compareTo(getConfirmedQty()) == 0;
} // isFullyConfirmed
/**
* Before Delete - do not delete
* @return false
*/
protected boolean beforeDelete ()
{
return false;
} // beforeDelete
/**
* Before Save
* @param newRecord new
* @return true
*/
protected boolean beforeSave (boolean newRecord)
{
// Calculate Difference = Target - Confirmed - Scrapped
BigDecimal difference = getTargetQty();
difference = difference.subtract(getConfirmedQty());
difference = difference.subtract(getScrappedQty());
setDifferenceQty(difference);
//
return true;
} // beforeSave
} // M_MovementLineConfirm | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MMovementLineConfirm.java | 1 |
请完成以下Java代码 | public void writeDefaultNamespace(String namespaceURI) throws XMLStreamException {
writer.writeDefaultNamespace(namespaceURI);
}
@Override
public void writeComment(String data) throws XMLStreamException {
writer.writeComment(data);
}
@Override
public void writeProcessingInstruction(String target) throws XMLStreamException {
writer.writeProcessingInstruction(target);
}
@Override
public void writeProcessingInstruction(String target, String data) throws XMLStreamException {
writer.writeProcessingInstruction(target, data);
}
@Override
public void writeCData(String data) throws XMLStreamException {
writer.writeCData(data);
}
@Override
public void writeDTD(String dtd) throws XMLStreamException {
writer.writeDTD(dtd);
}
@Override
public void writeEntityRef(String name) throws XMLStreamException {
writer.writeEntityRef(name);
}
@Override
public void writeStartDocument() throws XMLStreamException {
writer.writeStartDocument();
}
@Override
public void writeStartDocument(String version) throws XMLStreamException {
writer.writeStartDocument(version);
}
@Override
public void writeStartDocument(String encoding, String version) throws XMLStreamException {
writer.writeStartDocument(encoding, version);
}
@Override
public void writeCharacters(String text) throws XMLStreamException {
writer.writeCharacters(text);
}
@Override
public void writeCharacters(char[] text, int start, int len) throws XMLStreamException {
writer.writeCharacters(text, start, len);
} | @Override
public String getPrefix(String uri) throws XMLStreamException {
return writer.getPrefix(uri);
}
@Override
public void setPrefix(String prefix, String uri) throws XMLStreamException {
writer.setPrefix(prefix, uri);
}
@Override
public void setDefaultNamespace(String uri) throws XMLStreamException {
writer.setDefaultNamespace(uri);
}
@Override
public void setNamespaceContext(NamespaceContext context) throws XMLStreamException {
writer.setNamespaceContext(context);
}
@Override
public NamespaceContext getNamespaceContext() {
return writer.getNamespaceContext();
}
@Override
public Object getProperty(String name) throws IllegalArgumentException {
return writer.getProperty(name);
}
} | repos\flowable-engine-main\modules\flowable-bpmn-converter\src\main\java\org\flowable\bpmn\converter\DelegatingXMLStreamWriter.java | 1 |
请完成以下Java代码 | protected final ITranslatableString buildParametersString()
{
final Map<String, Object> parameters = getParameters();
if (parameters.isEmpty())
{
return TranslatableStrings.empty();
}
final TranslatableStringBuilder message = TranslatableStrings.builder();
message.append("Additional parameters:");
for (final Map.Entry<String, Object> paramName2Value : parameters.entrySet())
{
message.append("\n ").append(paramName2Value.getKey()).append(": ").appendObj(paramName2Value.getValue());
}
return message.build();
}
/**
* Utility method to convert parameters to string and append them to given <code>message</code>
*
* @see #buildParametersString()
*/
protected final void appendParameters(final TranslatableStringBuilder message)
{
final ITranslatableString parametersStr = buildParametersString();
if (TranslatableStrings.isBlank(parametersStr))
{
return;
}
if (!message.isEmpty())
{
message.append("\n");
}
message.append(parametersStr);
}
public String getMDC(@NonNull final String name)
{
return mdcContextMap.get(name);
}
/**
* Marks this exception as user validation error.
* In case an exception is a user validation error, the framework assumes the message is user friendly and can be displayed directly.
* More, the webui auto-saving will not hide/ignore this error put it will propagate it directly to user.
*/
@OverridingMethodsMustInvokeSuper
public AdempiereException markAsUserValidationError() | {
userValidationError = true;
return this;
}
public final boolean isUserValidationError()
{
return userValidationError;
}
public static boolean isUserValidationError(final Throwable ex)
{
return (ex instanceof AdempiereException) && ((AdempiereException)ex).isUserValidationError();
}
/**
* Fluent version of {@link #addSuppressed(Throwable)}
*/
public AdempiereException suppressing(@NonNull final Throwable exception)
{
addSuppressed(exception);
return this;
}
/**
* Override with a method returning false if your exception is more of a signal than an error
* and shall not clutter the log when it is caught and rethrown by the transaction manager.
* <p>
* To be invoked by {@link AdempiereException#isThrowableLoggedInTrxManager(Throwable)}.
*/
protected boolean isLoggedInTrxManager()
{
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\exceptions\AdempiereException.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class NotificationServiceImpl extends NotificationServiceGrpc.NotificationServiceImplBase {
private static final Logger logger = LoggerFactory.getLogger(NotificationServiceImpl.class);
@Override
public void notify(NotificationRequest request, StreamObserver<NotificationResponse> responseObserver) {
String message = request.getMessage();
String msgType = request.getType();
int msgID = request.getMessageID();
logger.info("message:{}\tmessage type:{}\tmessage id:{}", message, msgType, msgID);
String response = new StringBuilder().append("Message received: ")
.append(msgType)
.append(" - ")
.append(message)
.toString();
if (!saveAndSendMsg(msgID, response)) {
responseObserver.onError(Status.UNAVAILABLE.withDescription("Service temporarily unavailable...")
.asRuntimeException());
logger.error("Service temporarily unavailable would go for retry if the policy permits");
} else {
NotificationResponse notificationResponse = NotificationResponse.newBuilder()
.setResponse(response)
.build();
responseObserver.onNext(notificationResponse);
responseObserver.onCompleted();
}
}
/** | * created for demo purpose, it would return true only when the generated random number is a prime number
* @param msgID
* @param response
* @return
*/
private boolean saveAndSendMsg(int msgID, String response) {
boolean result = false;
int randomNum = new Random().nextInt(100) + 1;
if (isPrime(randomNum)) {
result = true;
}
logger.error("Will work only when the random number {} is prime", randomNum);
return result;
}
private static boolean isPrime(int number) {
if (number <= 1) {
return false;
}
for (int i = 2; i <= Math.sqrt(number); i++) {
if (number % i == 0) {
return false;
}
}
return true;
}
} | repos\tutorials-master\grpc\src\main\java\com\baeldung\grpc\retrypolicy\NotificationServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public List<Rfq> getActiveRfqs(@Nullable final User user)
{
final BPartner bpartner = user != null ? user.getBpartner() : null;
return getActiveRfqs(bpartner);
}
@Override
public List<Rfq> getActiveRfqs(@Nullable final BPartner bpartner)
{
return rfqRepo.findActive(bpartner);
}
@Override
public Rfq getUserActiveRfq(@NonNull final User user, final long rfqId)
{
final Rfq rfq = getRfqById(rfqId);
if (!Objects.equals(rfq.getBpartnerId(), user.getBpartnerId()))
{
throw new RuntimeException("RfQ not found");
}
if (rfq.isClosed())
{
throw new RuntimeException("RfQ already closed");
}
return rfq;
}
@Override
public Rfq getRfqById(final long rfq_id)
{
return rfqRepo.getOne(rfq_id);
}
@Override
@Nullable
public Rfq getRfqByUUID(@NonNull final String rfq_uuid)
{
return rfqRepo.findByUuid(rfq_uuid);
}
private void saveRecursivelyAndPush(@NonNull final Rfq rfq)
{
saveRecursively(rfq);
pushToMetasfresh(rfq);
}
@Override
public void saveRecursively(@NonNull final Rfq rfq)
{
//rfqQuantityRepo.saveAll(rfq.getQuantities()); // not needed
rfqRepo.save(rfq);
}
private void pushToMetasfresh(@NonNull final Rfq rfq)
{
final ISyncAfterCommitCollector syncAfterCommitCollector = senderToMetasfreshService.syncAfterCommit();
syncAfterCommitCollector.add(rfq); | }
@Override
@Transactional
public Rfq changeActiveRfq(
@NonNull final JsonChangeRfqRequest request,
@NonNull final User loggedUser)
{
final Rfq rfq = getUserActiveRfq(
loggedUser,
Long.parseLong(request.getRfqId()));
for (final JsonChangeRfqQtyRequest qtyChangeRequest : request.getQuantities())
{
rfq.setQtyPromised(qtyChangeRequest.getDate(), qtyChangeRequest.getQtyPromised());
}
if (request.getPrice() != null)
{
rfq.setPricePromisedUserEntered(request.getPrice());
}
saveRecursively(rfq);
return rfq;
}
@Override
public long getCountUnconfirmed(@NonNull final User user)
{
return rfqRepo.countUnconfirmed(user.getBpartner());
}
@Override
@Transactional
public void confirmUserEntries(@NonNull final User user)
{
final BPartner bpartner = user.getBpartner();
final List<Rfq> rfqs = rfqRepo.findUnconfirmed(bpartner);
for (final Rfq rfq : rfqs)
{
rfq.confirmByUser();
saveRecursivelyAndPush(rfq);
}
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\impl\RfQService.java | 2 |
请完成以下Java代码 | public void setWithoutTenantId(Boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
@CamundaQueryParam(value = "compact", converter = BooleanConverter.class)
public void setCompact(Boolean compact) {
this.compact = compact;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected CleanableHistoricDecisionInstanceReport createNewQuery(ProcessEngine engine) {
return engine.getHistoryService().createCleanableHistoricDecisionInstanceReport();
}
@Override
protected void applyFilters(CleanableHistoricDecisionInstanceReport query) {
if (decisionDefinitionIdIn != null && decisionDefinitionIdIn.length > 0) { | query.decisionDefinitionIdIn(decisionDefinitionIdIn);
}
if (decisionDefinitionKeyIn != null && decisionDefinitionKeyIn.length > 0) {
query.decisionDefinitionKeyIn(decisionDefinitionKeyIn);
}
if (Boolean.TRUE.equals(withoutTenantId)) {
query.withoutTenantId();
}
if (tenantIdIn != null && tenantIdIn.length > 0) {
query.tenantIdIn(tenantIdIn);
}
if (Boolean.TRUE.equals(compact)) {
query.compact();
}
}
@Override
protected void applySortBy(CleanableHistoricDecisionInstanceReport query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_FINISHED_VALUE)) {
query.orderByFinished();
}
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\CleanableHistoricDecisionInstanceReportDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MSV3User implements UserDetails
{
private final MSV3MetasfreshUserId metasfreshMSV3UserId;
private final String username;
private final String password;
private final BPartnerId bpartnerId;
private final List<GrantedAuthority> authorities;
private static final List<GrantedAuthority> AUTHORITIES_CLIENT = ImmutableList.of(new SimpleGrantedAuthority(SecurityConfig.ROLE_CLIENT));
private static final List<GrantedAuthority> AUTHORITIES_SERVER_ADMIN = ImmutableList.of(
new SimpleGrantedAuthority(SecurityConfig.ROLE_CLIENT), // FIXME: delete it
new SimpleGrantedAuthority(SecurityConfig.ROLE_SERVER_ADMIN));
@Builder
private MSV3User(
final MSV3MetasfreshUserId metasfreshMSV3UserId,
@NonNull final String username,
@NonNull final String password,
final boolean serverAdmin,
final BPartnerId bpartnerId)
{
this.metasfreshMSV3UserId = metasfreshMSV3UserId;
this.username = username;
this.password = password;
this.authorities = serverAdmin ? AUTHORITIES_SERVER_ADMIN : AUTHORITIES_CLIENT;
if (serverAdmin)
{
this.bpartnerId = null;
}
else
{
Preconditions.checkNotNull(bpartnerId, "bpartnerId"); | this.bpartnerId = bpartnerId;
}
}
@Override
public boolean isAccountNonExpired()
{
return true;
}
@Override
public boolean isAccountNonLocked()
{
return true;
}
@Override
public boolean isCredentialsNonExpired()
{
return true;
}
@Override
public boolean isEnabled()
{
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\security\MSV3User.java | 2 |
请完成以下Spring Boot application配置 | server:
port: 5003
spring:
application:
name: seata-product
cloud:
nacos:
config:
import-check:
enabled: false
main:
allow-bean-definition-overriding: true
autoconfigure:
exclude: com.baomidou.dynamic.datasource.spring.boot.autoconfigure.DynamicDataSourceAutoConfiguration
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/jeecg_product?useUnicode=true&characterEncoding=utf8&rewriteBatchedStatements=true&useSSL=false
username: root
password: root
sql:
init:
schema-locations: classpath:sql/schema-product.sql
seata:
enable-auto-dat | a-source-proxy: false
service:
grouplist:
default: 127.0.0.1:8091
vgroup-mapping:
springboot-seata-group: default
# seata 事务组编号 用于TC集群名
tx-service-group: springboot-seata-group
# 无用配置,为了避免扫码全代码导致启动慢
minidao:
base-package: org.jeecg.modules.jmreport.* | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-test\jeecg-cloud-test-seata\jeecg-cloud-test-seata-product\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public boolean isStateless() {
return CAS_STATELESS_IDENTIFIER.equals(this.identifier);
}
@Override
public @Nullable Object getCredentials() {
return this.credentials;
}
@Override
public Object getPrincipal() {
return this.identifier;
}
@Override
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
Assert.isTrue(!isAuthenticated,
"Cannot set this token to trusted - use constructor which takes a GrantedAuthority list instead");
super.setAuthenticated(false);
}
@Override
public void eraseCredentials() {
super.eraseCredentials();
this.credentials = null;
}
public Builder<?> toBuilder() {
return new Builder<>(this);
}
/**
* A builder of {@link CasServiceTicketAuthenticationToken} instances
*
* @since 7.0
*/
public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> {
private String principal; | private @Nullable Object credentials;
protected Builder(CasServiceTicketAuthenticationToken token) {
super(token);
this.principal = token.identifier;
this.credentials = token.credentials;
}
@Override
public B principal(@Nullable Object principal) {
Assert.isInstanceOf(String.class, principal, "principal must be of type String");
this.principal = (String) principal;
return (B) this;
}
@Override
public B credentials(@Nullable Object credentials) {
Assert.notNull(credentials, "credentials cannot be null");
this.credentials = credentials;
return (B) this;
}
@Override
public CasServiceTicketAuthenticationToken build() {
return new CasServiceTicketAuthenticationToken(this);
}
}
} | repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\authentication\CasServiceTicketAuthenticationToken.java | 1 |
请完成以下Java代码 | public String getLanguage() {
return language;
}
/**
* Sets the value of the language property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLanguage(String value) {
this.language = value;
}
/**
* Gets the value of the modus property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getModus() {
if (modus == null) {
return "production";
} else {
return modus;
}
}
/**
* Sets the value of the modus property.
*
* @param value
* allowed object is
* {@link String }
*
*/ | public void setModus(String value) {
this.modus = value;
}
/**
* Gets the value of the validationStatus property.
*
* @return
* possible object is
* {@link Long }
*
*/
public Long getValidationStatus() {
return validationStatus;
}
/**
* Sets the value of the validationStatus property.
*
* @param value
* allowed object is
* {@link Long }
*
*/
public void setValidationStatus(Long value) {
this.validationStatus = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RequestType.java | 1 |
请完成以下Java代码 | public boolean hasStartFormKey() {
return hasStartFormKey;
}
public boolean getHasStartFormKey() {
return hasStartFormKey;
}
public void setStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
}
public void setHasStartFormKey(boolean hasStartFormKey) {
this.hasStartFormKey = hasStartFormKey;
}
public boolean isGraphicalNotationDefined() {
return isGraphicalNotationDefined;
}
public boolean hasGraphicalNotation() {
return isGraphicalNotationDefined;
}
public void setGraphicalNotationDefined(boolean isGraphicalNotationDefined) {
this.isGraphicalNotationDefined = isGraphicalNotationDefined;
}
public int getSuspensionState() {
return suspensionState;
}
public void setSuspensionState(int suspensionState) {
this.suspensionState = suspensionState;
}
public boolean isSuspended() {
return suspensionState == SuspensionState.SUSPENDED.getStateCode();
}
public String getEngineVersion() {
return engineVersion;
} | public void setEngineVersion(String engineVersion) {
this.engineVersion = engineVersion;
}
public IOSpecification getIoSpecification() {
return ioSpecification;
}
public void setIoSpecification(IOSpecification ioSpecification) {
this.ioSpecification = ioSpecification;
}
public String toString() {
return "ProcessDefinitionEntity[" + id + "]";
}
public void setAppVersion(Integer appVersion) {
this.appVersion = appVersion;
}
public Integer getAppVersion() {
return this.appVersion;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionEntityImpl.java | 1 |
请完成以下Java代码 | private IExternalReferenceType extractTargetType(@NonNull final String externalReferenceType)
{
return externalReferenceTypes.ofCode(externalReferenceType)
.orElseThrow(() -> new AdempiereException("Unknown Type=")
.appendParametersToMessage()
.setParameter("externalReferenceType", externalReferenceType));
}
@NonNull
private AttachmentTags extractAttachmentTags(@Nullable final List<JsonTag> tags)
{
if (tags == null || Check.isEmpty(tags))
{
return AttachmentTags.EMPTY;
}
final ImmutableMap<String, String> tagName2Value = tags.stream()
.collect(ImmutableMap.toImmutableMap(JsonTag::getName, JsonTag::getValue));
return AttachmentTags.ofMap(tagName2Value);
}
@NonNull
private List<TableRecordReference> extractTableRecordReferences(@NonNull final JsonAttachmentRequest request)
{
final ImmutableList.Builder<TableRecordReference> tableRecordReferenceBuilder = ImmutableList.builder();
request.getTargets()
.stream()
.map(target -> extractTableRecordReference(request.getOrgCode(), target))
.forEach(tableRecordReferenceBuilder::add);
request.getReferences()
.stream() | .map(AttachmentRestService::extractTableRecordReference)
.forEach(tableRecordReferenceBuilder::add);
return tableRecordReferenceBuilder.build();
}
@NonNull
private static TableRecordReference extractTableRecordReference(@NonNull final JsonTableRecordReference reference)
{
return TableRecordReference.of(reference.getTableName(), reference.getRecordId().getValue());
}
private static void validateLocalFileURL(@NonNull final URL url)
{
if (!url.getProtocol().equals("file"))
{
throw new AdempiereException("Protocol " + url.getProtocol() + " not supported!");
}
final Path filePath = FileUtil.getFilePath(url);
if (!filePath.toFile().isFile())
{
throw new AdempiereException("Provided local file with URL: " + url + " is not accessible!")
.appendParametersToMessage()
.setParameter("ParsedPath", filePath.toString());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\attachment\AttachmentRestService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void init() {
visitors.forEach((visitor) -> {
visitorsMap.put(visitor.getClass(), visitor);
});
}
@Override
public void accept(Class<? extends Visitor> clazzVisitor) {
List<Book> allBooks = bookRepository.findAll();
if (!allBooks.isEmpty()) {
Visitor currentVisitor = visitorsMap.get(clazzVisitor);
for (Book book : allBooks) {
ClazzName clazzName = ClazzName.valueOf(book.getClass().getSimpleName());
switch (clazzName) { | case Ebook:
currentVisitor.visit((Ebook) book);
break;
case Paperback:
currentVisitor.visit((Paperback) book);
break;
default:
throw new IllegalArgumentException("Unkown book type!");
}
}
}
}
enum ClazzName {
Ebook, Paperback
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootJoinedAndVisitor\src\main\java\com\bookstore\service\VisitorService.java | 2 |
请完成以下Java代码 | public int getC_Remuneration_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Remuneration_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/ | public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobRemuneration.java | 1 |
请完成以下Java代码 | public List<FieldExtension> getFieldExtensions() {
return fieldExtensions;
}
public void setFieldExtensions(List<FieldExtension> fieldExtensions) {
this.fieldExtensions = fieldExtensions;
}
public String getOnTransaction() {
return onTransaction;
}
public void setOnTransaction(String onTransaction) {
this.onTransaction = onTransaction;
}
public String getCustomPropertiesResolverImplementationType() {
return customPropertiesResolverImplementationType;
}
public void setCustomPropertiesResolverImplementationType(String customPropertiesResolverImplementationType) {
this.customPropertiesResolverImplementationType = customPropertiesResolverImplementationType;
}
public String getCustomPropertiesResolverImplementation() {
return customPropertiesResolverImplementation;
}
public void setCustomPropertiesResolverImplementation(String customPropertiesResolverImplementation) {
this.customPropertiesResolverImplementation = customPropertiesResolverImplementation;
}
public Object getInstance() {
return instance;
}
public void setInstance(Object instance) {
this.instance = instance; | }
public ActivitiListener clone() {
ActivitiListener clone = new ActivitiListener();
clone.setValues(this);
return clone;
}
public void setValues(ActivitiListener otherListener) {
setEvent(otherListener.getEvent());
setImplementation(otherListener.getImplementation());
setImplementationType(otherListener.getImplementationType());
fieldExtensions = new ArrayList<FieldExtension>();
if (otherListener.getFieldExtensions() != null && !otherListener.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherListener.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ActivitiListener.java | 1 |
请完成以下Spring Boot application配置 | knife4j:
gateway:
enabled: true
tags-sorter: order
operations-sorter: order
# 指定服务发现的模式聚合微服务文档,并且是默认`default`分组
strategy: discover
discover:
enabled: true
# 指定版本号(Swagger2|OpenAPI3)
version : openapi3
# | 需要排除的微服务(eg:网关服务)
excluded-services:
- blade-admin
- blade-gateway
- blade-log | repos\SpringBlade-master\blade-gateway\src\main\resources\application.yml | 2 |
请完成以下Java代码 | class AdempiereTreeModel extends DefaultTreeModel {
/**
*
*/
private static final long serialVersionUID = 8503954687681402088L;
/** Logger */
private static Logger log = LogManager.getLogger(AdempiereTreeModel.class);
private MTree m_MTree;
public AdempiereTreeModel()
{
this(null); // root=null
}
public AdempiereTreeModel(final MTreeNode root)
{
super(root, true); // asksAllowsChildren=true
}
public void setMTree(MTree tree)
{
m_MTree = tree;
}
@Override
public MTreeNode getRoot()
{
return (MTreeNode)super.getRoot();
} | public boolean saveChildren(MTreeNode parent)
{
return saveChildren(parent, parent.getChildrenList());
}
public boolean saveChildren(MTreeNode parent, List<MTreeNode> children)
{
try
{
m_MTree.updateNodeChildren(parent, children);
}
catch (Exception e)
{
ADialog.error(0, null, "Error", e.getLocalizedMessage());
log.error(e.getLocalizedMessage(), e);
return false;
}
return true;
}
// metas: begin
public void filterIds(final List<Integer> ids)
{
Check.assumeNotNull(ids, "Param 'ids' is not null");
Services.get(IADTreeBL.class).filterIds(getRoot(), ids);
reload();
}
// metas: end
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\AdempiereTreeModel.java | 1 |
请完成以下Java代码 | public void createParameters()
{
deleteParameters();
for (final Parameter param : getConnector().getParameters())
{
final MImpexConnectorParam mParam = new MImpexConnectorParam(
getCtx(), 0, get_TrxName());
mParam.setParamName(param.displayName);
mParam.setDescription(param.description);
mParam.setAD_Reference_ID(param.displayType);
mParam.setName(param.name);
mParam.setSeqNo(param.seqNo);
mParam.setImpEx_Connector_ID(this.get_ID());
mParam.saveEx();
}
}
private void deleteParameters()
{
for (final MImpexConnectorParam mParam : MImpexConnectorParam.retrieve(this))
{
mParam.deleteEx(false);
}
}
@Override
protected boolean beforeDelete()
{ | deleteParameters();
return true;
}
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
if (success
&& (newRecord || is_ValueChanged(COLUMNNAME_ImpEx_ConnectorType_ID)))
{
createParameters();
}
return success;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\impex\model\MImpExConnector.java | 1 |
请完成以下Java代码 | public void setImplementationType(String implementationType) {
this.implementationType = implementationType;
}
public String getResultVariableName() {
return resultVariableName;
}
public void setResultVariableName(String resultVariableName) {
this.resultVariableName = resultVariableName;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public List<CustomProperty> getCustomProperties() {
return customProperties;
}
public void setCustomProperties(List<CustomProperty> customProperties) {
this.customProperties = customProperties;
}
public String getOperationRef() {
return operationRef;
}
public void setOperationRef(String operationRef) {
this.operationRef = operationRef;
}
public String getExtensionId() {
return extensionId;
}
public void setExtensionId(String extensionId) {
this.extensionId = extensionId;
}
public boolean isExtended() {
return extensionId != null && !extensionId.isEmpty();
}
public String getSkipExpression() {
return skipExpression;
}
public void setSkipExpression(String skipExpression) {
this.skipExpression = skipExpression;
} | public boolean hasBoundaryErrorEvents() {
if (this.boundaryEvents != null && !this.boundaryEvents.isEmpty()) {
return this.boundaryEvents.stream().anyMatch(boundaryEvent -> boundaryEvent.hasErrorEventDefinition());
}
return false;
}
public ServiceTask clone() {
ServiceTask clone = new ServiceTask();
clone.setValues(this);
return clone;
}
public void setValues(ServiceTask otherElement) {
super.setValues(otherElement);
setImplementation(otherElement.getImplementation());
setImplementationType(otherElement.getImplementationType());
setResultVariableName(otherElement.getResultVariableName());
setType(otherElement.getType());
setOperationRef(otherElement.getOperationRef());
setExtensionId(otherElement.getExtensionId());
setSkipExpression(otherElement.getSkipExpression());
fieldExtensions = new ArrayList<FieldExtension>();
if (otherElement.getFieldExtensions() != null && !otherElement.getFieldExtensions().isEmpty()) {
for (FieldExtension extension : otherElement.getFieldExtensions()) {
fieldExtensions.add(extension.clone());
}
}
customProperties = new ArrayList<CustomProperty>();
if (otherElement.getCustomProperties() != null && !otherElement.getCustomProperties().isEmpty()) {
for (CustomProperty property : otherElement.getCustomProperties()) {
customProperties.add(property.clone());
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ServiceTask.java | 1 |
请完成以下Java代码 | public abstract class ShapeImpl extends NodeImpl implements Shape {
protected static ChildElement<Bounds> boundsChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Shape.class, DI_ELEMENT_SHAPE)
.namespaceUri(DI_NS)
.extendsType(Node.class)
.abstractType();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
boundsChild = sequenceBuilder.element(Bounds.class)
.required()
.build(); | typeBuilder.build();
}
public ShapeImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Bounds getBounds() {
return boundsChild.getChild(this);
}
public void setBounds(Bounds bounds) {
boundsChild.setChild(this, bounds);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\di\ShapeImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HttpCookieOAuth2AuthorizationRequestRepository implements AuthorizationRequestRepository<OAuth2AuthorizationRequest> {
public static final String OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME = "oauth2_auth_request";
public static final String PREV_URI_PARAMETER = "prevUri";
public static final String PREV_URI_COOKIE_NAME = "prev_uri";
private static final int cookieExpireSeconds = 180;
@Override
public OAuth2AuthorizationRequest loadAuthorizationRequest(HttpServletRequest request) {
return CookieUtils.getCookie(request, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME)
.map(cookie -> CookieUtils.deserialize(cookie, OAuth2AuthorizationRequest.class))
.orElse(null);
}
@Override
public void saveAuthorizationRequest(OAuth2AuthorizationRequest authorizationRequest, HttpServletRequest request, HttpServletResponse response) {
if (authorizationRequest == null) {
CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME);
return;
} | if (request.getParameter(PREV_URI_PARAMETER) != null) {
CookieUtils.addCookie(response, PREV_URI_COOKIE_NAME, request.getParameter(PREV_URI_PARAMETER), cookieExpireSeconds);
}
CookieUtils.addCookie(response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME, CookieUtils.serialize(authorizationRequest), cookieExpireSeconds);
}
@Override
public OAuth2AuthorizationRequest removeAuthorizationRequest(HttpServletRequest request, HttpServletResponse response) {
return this.loadAuthorizationRequest(request);
}
public void removeAuthorizationRequestCookies(HttpServletRequest request, HttpServletResponse response) {
CookieUtils.deleteCookie(request, response, OAUTH2_AUTHORIZATION_REQUEST_COOKIE_NAME);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\oauth2\HttpCookieOAuth2AuthorizationRequestRepository.java | 2 |
请完成以下Java代码 | public PrivilegeQuery privilegeId(String id) {
this.id = id;
return this;
}
@Override
public PrivilegeQuery privilegeIds(List<String> ids) {
this.ids = ids;
return this;
}
@Override
public PrivilegeQuery privilegeName(String name) {
this.name = name;
return this;
}
@Override
public PrivilegeQuery userId(String userId) {
this.userId = userId;
return this;
}
@Override
public PrivilegeQuery groupId(String groupId) {
this.groupId = groupId;
return this;
}
@Override
public PrivilegeQuery groupIds(List<String> groupIds) {
this.groupIds = groupIds;
return this;
}
@Override
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public List<String> getIds() {
return ids;
}
public void setIds(List<String> ids) {
this.ids = ids;
}
public String getName() {
return name; | }
public void setName(String name) {
this.name = name;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getGroupId() {
return groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public List<String> getGroupIds() {
return groupIds;
}
public void setGroupIds(List<String> groupIds) {
this.groupIds = groupIds;
}
@Override
public long executeCount(CommandContext commandContext) {
return CommandContextUtil.getPrivilegeEntityManager(commandContext).findPrivilegeCountByQueryCriteria(this);
}
@Override
public List<Privilege> executeList(CommandContext commandContext) {
return CommandContextUtil.getPrivilegeEntityManager(commandContext).findPrivilegeByQueryCriteria(this);
}
} | repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\PrivilegeQueryImpl.java | 1 |
请完成以下Java代码 | private static final String encodeURLValue(final String value)
{
try
{
return URLEncoder.encode(value, StandardCharsets.UTF_8.toString());
}
catch (UnsupportedEncodingException e)
{
log.warn("Failed encoding '{}'. Returning it as is.", value, e);
return value;
}
}
private static final String bytesToString(final long sizeBytes)
{
if (sizeBytes < 1024)
{
return sizeBytes + " bytes";
}
else
{
final long sizeKb = sizeBytes / 1024;
if (sizeKb < 1024)
{
return sizeKb + "k";
}
else
{
final long sizeMb = sizeKb / 1024;
return sizeMb + "M";
}
}
}
/**************************************************************************
* Init
*
* @param config config
* @throws javax.servlet.ServletException
*/
@Override
public void init(ServletConfig config) throws ServletException
{
// NOTE: actually here we are starting all servers
m_serverMgr = AdempiereServerMgr.get();
}
/**
* Destroy
*/
@Override
public void destroy()
{ | log.info("destroy");
m_serverMgr = null;
} // destroy
/**
* Log error/warning
*
* @param message message
* @param e exception
*/
@Override
public void log(final String message, final Throwable e)
{
if (e == null)
{
log.warn(message);
}
log.error(message, e);
} // log
/**
* Log debug
*
* @param message message
*/
@Override
public void log(String message)
{
log.debug(message);
} // log
@Override
public String getServletName()
{
return NAME;
}
@Override
public String getServletInfo()
{
return "Server Monitor";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\adempiere\serverRoot\servlet\ServerMonitor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<FilterDefinition> getDefaultFilters() {
return defaultFilters;
}
public void setDefaultFilters(List<FilterDefinition> defaultFilters) {
this.defaultFilters = defaultFilters;
}
public List<MediaType> getStreamingMediaTypes() {
return streamingMediaTypes;
}
public void setStreamingMediaTypes(List<MediaType> streamingMediaTypes) {
this.streamingMediaTypes = streamingMediaTypes;
}
public boolean isFailOnRouteDefinitionError() {
return failOnRouteDefinitionError;
}
public void setFailOnRouteDefinitionError(boolean failOnRouteDefinitionError) {
this.failOnRouteDefinitionError = failOnRouteDefinitionError;
} | public String getTrustedProxies() {
return trustedProxies;
}
public void setTrustedProxies(String trustedProxies) {
this.trustedProxies = trustedProxies;
}
@Override
public String toString() {
return new ToStringCreator(this).append("routes", routes)
.append("defaultFilters", defaultFilters)
.append("streamingMediaTypes", streamingMediaTypes)
.append("failOnRouteDefinitionError", failOnRouteDefinitionError)
.append("routeFilterCacheEnabled", routeFilterCacheEnabled)
.append("trustedProxies", trustedProxies)
.toString();
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GatewayProperties.java | 2 |
请完成以下Java代码 | DeliveryOrder createDeliveryOrderFromParams(
@NonNull final Set<CreateDraftDeliveryOrderRequest.PackageInfo> packageInfos,
@NonNull final I_C_BPartner pickupFromBPartner,
@NonNull final I_C_Location pickupFromLocation,
@NonNull final LocalDate pickupDate,
@NonNull final I_C_BPartner deliverToBPartner,
@NonNull final I_C_Location deliverToLocation,
@Nullable final String deliverToPhoneNumber,
@NonNull final DhlShipperProduct serviceType,
final ShipperId shipperId,
final String customerReference,
final ShipperTransportationId shipperTransportationId,
@NonNull final PackageDimensions packageDimensions,
final CustomDeliveryData customDeliveryData)
{
final List<DeliveryOrderParcel> deliveryOrderParcels = packageInfos.stream()
.map(packageInfo -> DeliveryOrderParcel.builder()
.packageDimensions(packageDimensions)
.packageId(packageInfo.getPackageId())
.grossWeightKg(packageInfo.getWeightInKgOr(DEFAULT_PackageWeightInKg))
.build())
.collect(ImmutableList.toImmutableList());
return DeliveryOrder.builder()
.shipperId(shipperId)
.shipperTransportationId(shipperTransportationId)
//
.shipperProduct(serviceType) // todo this should be made user-selectable. Ref: https://github.com/metasfresh/me03/issues/3128
.customerReference(customerReference)
.customDeliveryData(customDeliveryData)
//
// Pickup aka Shipper | .pickupAddress(DeliveryOrderUtil.prepareAddressFromLocationBP(pickupFromLocation, pickupFromBPartner)
.build())
.pickupDate(PickupDate.builder()
.date(pickupDate)
.build())
//
// Delivery aka Receiver
.deliveryAddress(DeliveryOrderUtil.prepareAddressFromLocationBP(deliverToLocation, deliverToBPartner)
.bpartnerId(deliverToBPartner.getC_BPartner_ID()) // afaics used only for logging
.build())
.deliveryContact(ContactPerson.builder()
.name(deliverToBPartner.getName())
.emailAddress(deliverToBPartner.getEMail())
.simplePhoneNumber(deliverToPhoneNumber)
.build())
//
// Delivery content
.deliveryOrderParcels(deliveryOrderParcels)
//
.build();
}
/**
* Assume that all the packages inside a delivery position are of the same type and therefore have the same size.
*/
@NonNull
private PackageDimensions getPackageDimensions(@NonNull final Set<CreateDraftDeliveryOrderRequest.PackageInfo> packageInfos)
{
return packageInfos.iterator().next().getPackageDimension();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\DhlDraftDeliveryOrderCreator.java | 1 |
请完成以下Java代码 | public <T extends TypedValue> T getValueTyped(String name) {
if (name == null) {
throw new IllegalArgumentException("This map does not support 'null' keys.");
}
return getVariableTyped(name);
}
@Override
public Object put(String key, Object value) {
if(key == null) {
throw new IllegalArgumentException("This map does not support 'null' keys.");
}
Object variableBefore = getVariable(key);
setVariable(key, value);
return variableBefore;
}
@Override
public void putAll(Map< ? extends String, ? extends Object> m) {
for (java.util.Map.Entry< ? extends String, ? extends Object> newEntry : m.entrySet()) {
setVariable(newEntry.getKey(), newEntry.getValue());
}
}
@Override
public VariableMap putValue(String name, Object value) {
put(name, value);
return this;
}
@Override
public VariableMap putValueTyped(String name, TypedValue value) {
if(name == null) {
throw new IllegalArgumentException("This map does not support 'null' names.");
}
setVariable(name, value);
return this;
}
@Override
public int size() {
throw new UnsupportedOperationException(getClass().getName()+".size() is not supported.");
}
@Override
public boolean isEmpty() {
throw new UnsupportedOperationException(getClass().getName()+".isEmpty() is not supported.");
}
@Override
public boolean containsKey(Object key) {
throw new UnsupportedOperationException(getClass().getName()+".containsKey() is not supported.");
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException(getClass().getName()+".containsValue() is not supported.");
}
@Override
public Object remove(Object key) { | throw new UnsupportedOperationException(getClass().getName()+".remove is unsupported. Use " + getClass().getName() + ".put(key, null)");
}
@Override
public void clear() {
throw new UnsupportedOperationException(getClass().getName()+".clear() is not supported.");
}
@Override
public Set<String> keySet() {
throw new UnsupportedOperationException(getClass().getName()+".keySet() is not supported.");
}
@Override
public Collection<Object> values() {
throw new UnsupportedOperationException(getClass().getName()+".values() is not supported.");
}
@Override
public Set<java.util.Map.Entry<String, Object>> entrySet() {
throw new UnsupportedOperationException(getClass().getName()+".entrySet() is not supported.");
}
public VariableContext asVariableContext() {
throw new UnsupportedOperationException(getClass().getName()+".asVariableContext() is not supported.");
}
} | repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\AbstractVariableMap.java | 1 |
请完成以下Java代码 | public CmmnCaseInstance createCaseInstance() {
return createCaseInstance(null);
}
public CmmnCaseInstance createCaseInstance(String businessKey) {
// create a new case instance
CmmnExecution caseInstance = newCaseInstance();
// set the definition...
caseInstance.setCaseDefinition(this);
// ... and the case instance (identity)
caseInstance.setCaseInstance(caseInstance);
// set the business key | caseInstance.setBusinessKey(businessKey);
// get the case plan model as "initial" activity
CmmnActivity casePlanModel = getActivities().get(0);
// set the case plan model activity
caseInstance.setActivity(casePlanModel);
return caseInstance;
}
protected CmmnExecution newCaseInstance() {
return new CaseExecutionImpl();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\model\CmmnCaseDefinition.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductSupply extends AbstractSyncConfirmAwareEntity
{
@ManyToOne
@Lazy
@NonNull
private BPartner bpartner;
@ManyToOne
@NonNull
private Product product;
@ManyToOne
@NotFound(action = NotFoundAction.IGNORE) // don't fail if the record was not found
@SuppressWarnings("deprecation")
@org.hibernate.annotations.ForeignKey(name = "none") // deprecated but see http://stackoverflow.com/questions/27040735/jpa-association-without-foreign-key
@Nullable
@Getter
@Setter
private ContractLine contractLine;
@NonNull
@Getter
@Setter
private BigDecimal qty = BigDecimal.ZERO;
@NonNull
@Getter
@Setter
private BigDecimal qtyUserEntered = BigDecimal.ZERO;
@NonNull
private java.sql.Date day;
protected ProductSupply()
{
}
@Builder
private ProductSupply(
@NonNull final BPartner bpartner,
@NonNull final Product product,
@Nullable final ContractLine contractLine,
@NonNull final LocalDate day)
{
//
// Validate
if (contractLine != null)
{
final BPartner contractBPartner = contractLine.getContract().getBpartner();
if (!Objects.equals(bpartner, contractBPartner))
{
throw new IllegalArgumentException("BPartner not matching the contract");
}
final Product contractProduct = contractLine.getProduct();
if (!Objects.equals(product, contractProduct))
{
throw new IllegalArgumentException("Product not matching the contract");
}
}
this.bpartner = bpartner;
this.product = product;
this.contractLine = contractLine;
this.day = DateUtils.toSqlDate(day);
} | @Override
protected void toString(final MoreObjects.ToStringHelper toStringHelper)
{
toStringHelper
.omitNullValues()
.add("product", product)
.add("bpartner", bpartner)
.add("day", day)
.add("qtyUserEntered", qtyUserEntered)
.add("qty", qty)
.add("contractLine", contractLine);
}
public String getBpartnerUUID()
{
return bpartner.getUuid();
}
public String getProductUUID()
{
return product.getUuid();
}
public Long getProductId()
{
return product.getId();
}
public LocalDate getDay()
{
return day.toLocalDate();
}
public boolean isQtyConfirmedByUser()
{
return getQty().compareTo(getQtyUserEntered()) == 0;
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\ProductSupply.java | 2 |
请完成以下Java代码 | public static Optional<OrderAndLineId> optionalOfRepoIds(final int orderRepoId, final int orderLineRepoId)
{
return Optional.ofNullable(ofRepoIdsOrNull(orderRepoId, orderLineRepoId));
}
public static int toOrderRepoId(@Nullable final OrderAndLineId orderAndLineId)
{
return getOrderRepoIdOr(orderAndLineId, -1);
}
public static int getOrderRepoIdOr(@Nullable final OrderAndLineId orderAndLineId, final int defaultValue)
{
return orderAndLineId != null ? orderAndLineId.getOrderRepoId() : defaultValue;
}
public static int toOrderLineRepoId(@Nullable final OrderAndLineId orderAndLineId)
{
return getOrderLineRepoIdOr(orderAndLineId, -1);
}
public static int getOrderLineRepoIdOr(@Nullable final OrderAndLineId orderAndLineId, final int defaultValue)
{
return orderAndLineId != null ? orderAndLineId.getOrderLineRepoId() : defaultValue;
}
public static Set<Integer> getOrderLineRepoIds(final Collection<OrderAndLineId> orderAndLineIds)
{
return orderAndLineIds.stream().map(OrderAndLineId::getOrderLineRepoId).collect(ImmutableSet.toImmutableSet());
}
public static Set<OrderId> getOrderIds(final Collection<OrderAndLineId> orderAndLineIds)
{
return orderAndLineIds.stream().map(OrderAndLineId::getOrderId).collect(ImmutableSet.toImmutableSet());
}
public static Set<OrderLineId> getOrderLineIds(final Collection<OrderAndLineId> orderAndLineIds)
{
return orderAndLineIds.stream().map(OrderAndLineId::getOrderLineId).collect(ImmutableSet.toImmutableSet());
}
OrderId orderId;
OrderLineId orderLineId; | private OrderAndLineId(@NonNull final OrderId orderId, @NonNull final OrderLineId orderLineId)
{
this.orderId = orderId;
this.orderLineId = orderLineId;
}
public int getOrderRepoId()
{
return orderId.getRepoId();
}
public int getOrderLineRepoId()
{
return orderLineId.getRepoId();
}
public static boolean equals(@Nullable final OrderAndLineId o1, @Nullable final OrderAndLineId o2)
{
return Objects.equals(o1, o2);
}
@JsonValue
public String toJson()
{
return orderId.getRepoId() + "_" + orderLineId.getRepoId();
}
@JsonCreator
public static OrderAndLineId ofJson(@NonNull String json)
{
try
{
final int idx = json.indexOf("_");
return ofRepoIds(Integer.parseInt(json.substring(0, idx)), Integer.parseInt(json.substring(idx + 1)));
}
catch (Exception ex)
{
throw new AdempiereException("Invalid JSON: " + json, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderAndLineId.java | 1 |
请完成以下Java代码 | public class ProcessDefinitionInfoCacheObject {
protected String id;
protected int revision;
protected ObjectNode infoNode;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getRevision() { | return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public ObjectNode getInfoNode() {
return infoNode;
}
public void setInfoNode(ObjectNode infoNode) {
this.infoNode = infoNode;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\deploy\ProcessDefinitionInfoCacheObject.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Mono<UserDetails> findByUsername(final String login) {
log.debug("Authenticating {}", login);
if (new EmailValidator().isValid(login, null)) {
return userRepository
.findOneWithAuthoritiesByEmailIgnoreCase(login)
.switchIfEmpty(Mono.error(new UsernameNotFoundException("User with email " + login + " was not found in the database")))
.map(user -> createSpringSecurityUser(login, user));
}
String lowercaseLogin = login.toLowerCase(Locale.ENGLISH);
return userRepository
.findOneWithAuthoritiesByLogin(lowercaseLogin)
.switchIfEmpty(Mono.error(new UsernameNotFoundException("User " + lowercaseLogin + " was not found in the database")))
.map(user -> createSpringSecurityUser(lowercaseLogin, user)); | }
private org.springframework.security.core.userdetails.User createSpringSecurityUser(String lowercaseLogin, User user) {
if (!user.isActivated()) {
throw new UserNotActivatedException("User " + lowercaseLogin + " was not activated");
}
List<SimpleGrantedAuthority> grantedAuthorities = user
.getAuthorities()
.stream()
.map(Authority::getName)
.map(SimpleGrantedAuthority::new)
.toList();
return new org.springframework.security.core.userdetails.User(user.getLogin(), user.getPassword(), grantedAuthorities);
}
} | repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\security\DomainUserDetailsService.java | 2 |
请完成以下Java代码 | public class M_DeliveryDay_Alloc
{
@ModelChange(timings = ModelValidator.TYPE_AFTER_NEW)
public void onCreate(final I_M_DeliveryDay_Alloc deliveryDayAlloc)
{
final I_M_DeliveryDay deliveryDay = deliveryDayAlloc.getM_DeliveryDay();
final I_M_DeliveryDay_Alloc deliveryDayAllocNew = deliveryDayAlloc;
final I_M_DeliveryDay_Alloc deliveryDayAllocOld = null;
updateDeliveryDayWhenAllocationChanged(deliveryDay, deliveryDayAllocNew, deliveryDayAllocOld);
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE)
public void onChange(final I_M_DeliveryDay_Alloc deliveryDayAlloc)
{
final I_M_DeliveryDay deliveryDay = deliveryDayAlloc.getM_DeliveryDay();
final I_M_DeliveryDay_Alloc deliveryDayAllocNew = deliveryDayAlloc;
final I_M_DeliveryDay_Alloc deliveryDayAllocOld = InterfaceWrapperHelper.createOld(deliveryDayAlloc, I_M_DeliveryDay_Alloc.class);
updateDeliveryDayWhenAllocationChanged(deliveryDay, deliveryDayAllocNew, deliveryDayAllocOld);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE)
public void onBeforeDelete(final I_M_DeliveryDay_Alloc deliveryDayAlloc)
{
final I_M_DeliveryDay deliveryDay = deliveryDayAlloc.getM_DeliveryDay();
if (deliveryDay.isProcessed())
{
throw new AdempiereException("@CannotDelete@: @M_DeliveryDay_Alloc_ID@ (@M_DeliveryDay_ID@ @Processed@=@Y@)");
}
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_DELETE)
public void onAfterDelete(final I_M_DeliveryDay_Alloc deliveryDayAlloc)
{
final I_M_DeliveryDay deliveryDay = deliveryDayAlloc.getM_DeliveryDay();
final I_M_DeliveryDay_Alloc deliveryDayAllocNew = null;
final I_M_DeliveryDay_Alloc deliveryDayAllocOld = deliveryDayAlloc;
updateDeliveryDayWhenAllocationChanged(deliveryDay, deliveryDayAllocNew, deliveryDayAllocOld);
} | private final void updateDeliveryDayWhenAllocationChanged(final I_M_DeliveryDay deliveryDay,
final I_M_DeliveryDay_Alloc deliveryDayAllocNew,
final I_M_DeliveryDay_Alloc deliveryDayAllocOld)
{
final boolean deliveryDayProcessed = deliveryDay.isProcessed();
//
// Call handlers to update the delivery day record
Services.get(IDeliveryDayBL.class)
.getDeliveryDayHandlers()
.updateDeliveryDayWhenAllocationChanged(deliveryDay, deliveryDayAllocNew, deliveryDayAllocOld);
//
// Prohibit changing delivery day if it was processed
if (deliveryDayProcessed)
{
if (InterfaceWrapperHelper.hasChanges(deliveryDay))
{
throw new AdempiereException("Cannot change a delivery day which was already processed"
+ "\n @M_DeliveryDay_ID@: " + deliveryDay
+ "\n @M_DeliveryDay_Alloc_ID@ @New@: " + deliveryDayAllocNew
+ "\n @M_DeliveryDay_Alloc_ID@ @Old@: " + deliveryDayAllocOld);
}
// return it because there is no need to save the changes
return;
}
//
// Save delivery day changes
InterfaceWrapperHelper.save(deliveryDay);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\M_DeliveryDay_Alloc.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getPaymentCondition() {
return paymentCondition;
}
/**
* Sets the value of the paymentCondition property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPaymentCondition(String value) {
this.paymentCondition = value;
}
/**
* Payment means coded. Please use EDIFACT code list values. (PAI 4461)
*
* @return
* possible object is
* {@link String }
*
*/
public String getPaymentMeans() { | return paymentMeans;
}
/**
* Sets the value of the paymentMeans property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPaymentMeans(String value) {
this.paymentMeans = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\PaymentConditionsExtensionType.java | 2 |
请完成以下Java代码 | public class UserCheckFilter implements Filter {
public static void forward(HttpServletRequest request, HttpServletResponse response, String page) throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/user.check" + page)
.forward(request, response);
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if (!(req instanceof HttpServletRequest)) {
throw new ServletException("Can only process HttpServletRequest");
}
if (!(res instanceof HttpServletResponse)) {
throw new ServletException("Can only process HttpServletResponse");
}
HttpServletRequest request = (HttpServletRequest) req; | HttpServletResponse response = (HttpServletResponse) res;
request.setAttribute("origin", request.getRequestURI());
if (!request.getRequestURI()
.contains("login") && request.getSession(false) == null) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
forward(request, response, "/login.jsp");
// we return here so the original servlet is not processed
return;
}
chain.doFilter(request, response);
}
public void init(FilterConfig arg) throws ServletException {
}
} | repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\user\check\UserCheckFilter.java | 1 |
请完成以下Java代码 | private static AuthenticationException newNoCredentialsException(final AccessDeniedException denied) {
return new BadCredentialsException("No credentials found in the request", denied);
}
/**
* A call listener that will set the authentication context using {@link SecurityContextHolder} before each
* invocation and clear it afterwards.
*
* @param <ReqT> The type of the request.
*/
private static class AuthenticatingServerCallListener<ReqT> extends AbstractAuthenticatingServerCallListener<ReqT> {
private final SecurityContext securityContext;
/**
* Creates a new AuthenticatingServerCallListener which will attach the given security context before delegating
* to the given listener.
*
* @param delegate The listener to delegate to.
* @param grpcContext The context to attach.
* @param securityContext The security context instance to attach.
*/
public AuthenticatingServerCallListener(final Listener<ReqT> delegate, final Context grpcContext,
final SecurityContext securityContext) {
super(delegate, grpcContext);
this.securityContext = securityContext;
}
@Override
protected void attachAuthenticationContext() {
SecurityContextHolder.setContext(this.securityContext);
}
@Override
protected void detachAuthenticationContext() {
SecurityContextHolder.clearContext(); | }
@Override
public void onHalfClose() {
try {
super.onHalfClose();
} catch (final AccessDeniedException e) {
if (this.securityContext.getAuthentication() instanceof AnonymousAuthenticationToken) {
throw newNoCredentialsException(e);
} else {
throw e;
}
}
}
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\interceptors\DefaultAuthenticatingServerInterceptor.java | 1 |
请完成以下Java代码 | protected Object getAllocationRequestReferencedModel()
{
return getCoByProductOrderBOMLine();
}
@Override
protected IAllocationSource createAllocationSource()
{
final I_PP_Order_BOMLine coByProductOrderBOMLine = getCoByProductOrderBOMLine();
final PPOrderBOMLineProductStorage ppOrderBOMLineProductStorage = new PPOrderBOMLineProductStorage(coByProductOrderBOMLine);
return new GenericAllocationSourceDestination(
ppOrderBOMLineProductStorage,
coByProductOrderBOMLine // referenced model
);
}
@Override
protected IDocumentLUTUConfigurationManager createReceiptLUTUConfigurationManager()
{
final I_PP_Order_BOMLine coByProductOrderBOMLine = getCoByProductOrderBOMLine();
return huPPOrderBL.createReceiptLUTUConfigurationManager(coByProductOrderBOMLine);
}
@Override
protected ReceiptCandidateRequestProducer newReceiptCandidateRequestProducer()
{
final I_PP_Order_BOMLine coByProductOrderBOMLine = getCoByProductOrderBOMLine();
final PPOrderBOMLineId coByProductOrderBOMLineId = PPOrderBOMLineId.ofRepoId(coByProductOrderBOMLine.getPP_Order_BOMLine_ID());
final PPOrderId orderId = PPOrderId.ofRepoId(coByProductOrderBOMLine.getPP_Order_ID());
final OrgId orgId = OrgId.ofRepoId(coByProductOrderBOMLine.getAD_Org_ID()); | return ReceiptCandidateRequestProducer.builder()
.orderId(orderId)
.coByProductOrderBOMLineId(coByProductOrderBOMLineId)
.orgId(orgId)
.date(getMovementDate())
.locatorId(getLocatorId())
.pickingCandidateId(getPickingCandidateId())
.build();
}
@Override
protected void addAssignedHUs(final Collection<I_M_HU> hus)
{
final I_PP_Order_BOMLine bomLine = getCoByProductOrderBOMLine();
huPPOrderBL.addAssignedHandlingUnits(bomLine, hus);
}
@Override
public IPPOrderReceiptHUProducer withPPOrderLocatorId()
{
final I_PP_Order order = huPPOrderBL.getById(PPOrderId.ofRepoId(coByProductOrderBOMLine.getPP_Order_ID()));
return locatorId(LocatorId.ofRepoId(order.getM_Warehouse_ID(), order.getM_Locator_ID()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\CostCollectorCandidateCoProductHUProducer.java | 1 |
请完成以下Java代码 | public ManufacturingJobActivity withRawMaterialsIssue(@Nullable RawMaterialsIssue rawMaterialsIssue)
{
return Objects.equals(this.rawMaterialsIssue, rawMaterialsIssue) ? this : toBuilder().rawMaterialsIssue(rawMaterialsIssue).build();
}
public ManufacturingJobActivity withChangedReceiveLine(
@NonNull final FinishedGoodsReceiveLineId id,
@NonNull UnaryOperator<FinishedGoodsReceiveLine> mapper)
{
if (finishedGoodsReceive != null)
{
return withFinishedGoodsReceive(finishedGoodsReceive.withChangedReceiveLine(id, mapper));
}
else
{
return this;
}
}
public ManufacturingJobActivity withFinishedGoodsReceive(@Nullable FinishedGoodsReceive finishedGoodsReceive)
{ | return Objects.equals(this.finishedGoodsReceive, finishedGoodsReceive) ? this : toBuilder().finishedGoodsReceive(finishedGoodsReceive).build();
}
@NonNull
public ManufacturingJobActivity withChangedRawMaterialsIssue(@NonNull final UnaryOperator<RawMaterialsIssue> mapper)
{
if (rawMaterialsIssue != null)
{
return withRawMaterialsIssue(mapper.apply(rawMaterialsIssue));
}
else
{
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\ManufacturingJobActivity.java | 1 |
请完成以下Java代码 | public class CategoryCodeRule implements IFillRuleHandler {
public static final String ROOT_PID_VALUE = "0";
@Override
public Object execute(JSONObject params, JSONObject formData) {
log.info("系统自定义编码规则[category_code_rule],params:{} ,formData: {}", params, formData);
String categoryPid = ROOT_PID_VALUE;
String categoryCode = null;
if (formData != null && formData.size() > 0) {
Object obj = formData.get("pid");
if (oConvertUtils.isNotEmpty(obj)) {
categoryPid = obj.toString();
}
} else {
if (params != null) {
Object obj = params.get("pid");
if (oConvertUtils.isNotEmpty(obj)) {
categoryPid = obj.toString();
}
}
}
/*
* 分成三种情况
* 1.数据库无数据 调用YouBianCodeUtil.getNextYouBianCode(null);
* 2.添加子节点,无兄弟元素 YouBianCodeUtil.getSubYouBianCode(parentCode,null);
* 3.添加子节点有兄弟元素 YouBianCodeUtil.getNextYouBianCode(lastCode); | * */
//找同类 确定上一个最大的code值
SysCategoryMapper baseMapper = (SysCategoryMapper) SpringContextUtils.getBean("sysCategoryMapper");
// 代码逻辑说明: 【issues/4846】开启saas多租户功能后,租户管理员在添加分类字典时,报错------------
Page<SysCategory> page = new Page<>(1,1);
List<SysCategory> list = baseMapper.getMaxCategoryCodeByPage(page,categoryPid);
if (list == null || list.size() == 0) {
if (ROOT_PID_VALUE.equals(categoryPid)) {
//情况1
categoryCode = YouBianCodeUtil.getNextYouBianCode(null);
} else {
//情况2
SysCategory parent = (SysCategory) baseMapper.selectSysCategoryById(categoryPid);
categoryCode = YouBianCodeUtil.getSubYouBianCode(parent.getCode(), null);
}
} else {
//情况3
categoryCode = YouBianCodeUtil.getNextYouBianCode(list.get(0).getCode());
}
return categoryCode;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\rule\CategoryCodeRule.java | 1 |
请完成以下Java代码 | public void setIsUserUpdateable (boolean IsUserUpdateable)
{
set_Value (COLUMNNAME_IsUserUpdateable, Boolean.valueOf(IsUserUpdateable));
}
/** Get User updateable.
@return The field can be updated by the user
*/
public boolean isUserUpdateable ()
{
Object oo = get_Value(COLUMNNAME_IsUserUpdateable);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | /** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Win.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private List<RedisNode> createSentinels(Sentinel sentinel) {
List<RedisNode> nodes = new ArrayList<>();
for (Node node : sentinel.getNodes()) {
nodes.add(asRedisNode(node));
}
return nodes;
}
protected final DataRedisConnectionDetails getConnectionDetails() {
return this.connectionDetails;
}
private Mode determineMode() {
if (getSentinelConfig() != null) {
return Mode.SENTINEL;
} | if (getClusterConfiguration() != null) {
return Mode.CLUSTER;
}
if (getMasterReplicaConfiguration() != null) {
return Mode.MASTER_REPLICA;
}
return Mode.STANDALONE;
}
enum Mode {
STANDALONE, CLUSTER, MASTER_REPLICA, SENTINEL
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisConnectionConfiguration.java | 2 |
请完成以下Java代码 | public Description getDescription() {
return descriptionChild.getChild(this);
}
public void setDescription(Description description) {
descriptionChild.setChild(this, description);
}
public ExtensionElements getExtensionElements() {
return extensionElementsChild.getChild(this);
}
public void setExtensionElements(ExtensionElements extensionElements) {
extensionElementsChild.setChild(this, extensionElements);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(DmnElement.class, DMN_ELEMENT)
.namespaceUri(LATEST_DMN_NS)
.abstractType();
idAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_ID)
.idAttribute() | .build();
labelAttribute = typeBuilder.stringAttribute(DMN_ATTRIBUTE_LABEL)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
descriptionChild = sequenceBuilder.element(Description.class)
.build();
extensionElementsChild = sequenceBuilder.element(ExtensionElements.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\dmn-model\src\main\java\org\camunda\bpm\model\dmn\impl\instance\DmnElementImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getReferenceType() {
return referenceType;
}
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
public String getEntryCriterionId() {
return entryCriterionId;
}
public void setEntryCriterionId(String entryCriterionId) {
this.entryCriterionId = entryCriterionId;
}
public String getExitCriterionId() {
return exitCriterionId;
}
public void setExitCriterionId(String exitCriterionId) {
this.exitCriterionId = exitCriterionId;
}
public String getFormKey() {
return formKey;
}
public void setFormKey(String formKey) {
this.formKey = formKey;
}
public String getExtraValue() {
return extraValue;
}
public void setExtraValue(String extraValue) {
this.extraValue = extraValue;
}
public boolean isShowInOverview() {
return showInOverview;
}
public void setShowInOverview(boolean showInOverview) {
this.showInOverview = showInOverview;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-planitem-instances/5")
public String getUrl() { | return url;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/12345")
public String getCaseInstanceUrl() {
return caseInstanceUrl;
}
public void setCaseInstanceUrl(String caseInstanceUrl) {
this.caseInstanceUrl = caseInstanceUrl;
}
@ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/myCaseId%3A1%3A4")
public String getCaseDefinitionUrl() {
return caseDefinitionUrl;
}
public void setCaseDefinitionUrl(String caseDefinitionUrl) {
this.caseDefinitionUrl = caseDefinitionUrl;
}
public String getDerivedCaseDefinitionUrl() {
return derivedCaseDefinitionUrl;
}
public void setDerivedCaseDefinitionUrl(String derivedCaseDefinitionUrl) {
this.derivedCaseDefinitionUrl = derivedCaseDefinitionUrl;
}
public String getStageInstanceUrl() {
return stageInstanceUrl;
}
public void setStageInstanceUrl(String stageInstanceUrl) {
this.stageInstanceUrl = stageInstanceUrl;
}
public void setLocalVariables(List<RestVariable> localVariables){
this.localVariables = localVariables;
}
public List<RestVariable> getLocalVariables() {
return localVariables;
}
public void addLocalVariable(RestVariable restVariable) {
localVariables.add(restVariable);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\planitem\HistoricPlanItemInstanceResponse.java | 2 |
请完成以下Java代码 | public static CaseExecutionState getStateForCode(Integer stateCode) {
return CASE_EXECUTION_STATES.get(stateCode);
}
public int getStateCode() {
return stateCode;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + stateCode;
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false; | if (getClass() != obj.getClass())
return false;
CaseExecutionStateImpl other = (CaseExecutionStateImpl) obj;
if (stateCode != other.stateCode)
return false;
return true;
}
@Override
public String toString() {
return name;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\execution\CaseExecutionState.java | 1 |
请完成以下Java代码 | public IAsyncBatchBuilder setContext(final Properties ctx)
{
_ctx = ctx;
return this;
}
private final Properties getCtx()
{
Check.assumeNotNull(_ctx, "ctx not null");
return _ctx;
}
@Override
public IAsyncBatchBuilder setCountExpected(final int expected)
{
_countExpected = expected;
return this;
}
private final int getCountExpected()
{
return _countExpected;
}
@Override
public IAsyncBatchBuilder setAD_PInstance_Creator_ID(final PInstanceId adPInstanceId)
{
this.adPInstanceId = adPInstanceId;
return this;
}
private final PInstanceId getAD_PInstance_Creator_ID()
{
return adPInstanceId;
}
private AsyncBatchId getParentAsyncBatchId()
{
return Optional.ofNullable(_parentAsyncBatchId)
.orElse(contextFactory.getThreadInheritedWorkpackageAsyncBatch());
}
@Override
public IAsyncBatchBuilder setParentAsyncBatchId(final AsyncBatchId parentAsyncBatchId)
{
_parentAsyncBatchId = parentAsyncBatchId;
return this;
}
@Override
public IAsyncBatchBuilder setName(final String name)
{
_name = name;
return this;
}
public String getName()
{
return _name;
} | @Override
public IAsyncBatchBuilder setDescription(final String description)
{
_description = description;
return this;
}
private String getDescription()
{
return _description;
}
private OrgId getOrgId()
{
return orgId;
}
@Override
public IAsyncBatchBuilder setC_Async_Batch_Type(final String internalName)
{
_asyncBatchType = asyncBatchDAO.retrieveAsyncBatchType(getCtx(), internalName);
return this;
}
public I_C_Async_Batch_Type getC_Async_Batch_Type()
{
Check.assumeNotNull(_asyncBatchType, "_asyncBatchType not null");
return _asyncBatchType;
}
@Override
public IAsyncBatchBuilder setOrgId(final OrgId orgId)
{
this.orgId = orgId;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\api\impl\AsyncBatchBuilder.java | 1 |
请完成以下Java代码 | public String getColumnName()
{
return m_columnName;
} // getColumnName
/**
* Set Confirmed toggle
*
* @param confirmed confirmed
*/
public void setConfirmed(final boolean confirmed)
{
m_confirmed = confirmed;
} // setConfirmed
/**
* Is Confirmed (e.g. user has seen it)
*
* @return true if confirmed
*/
public boolean isConfirmed()
{
return m_confirmed;
} // isConfirmed
public void setCreated(final Integer createdBy, final Timestamp created)
{
this.createdBy = createdBy;
this.created = created;
}
public void setUpdated(final Integer updatedBy, final Timestamp updated)
{
this.updatedBy = updatedBy;
this.updated = updated;
}
public void setAdTableId(final int adTableId)
{
this.adTableId = adTableId;
this.recordId = null; | }
public void setSingleKeyRecord(final int adTableId, @NonNull final String keyColumnName, final int recordId)
{
setRecord(adTableId, ComposedRecordId.singleKey(keyColumnName, recordId));
}
public void setRecord(final int adTableId, @NonNull final ComposedRecordId recordId)
{
Check.assumeGreaterThanZero(adTableId, "adTableId");
this.adTableId = adTableId;
this.recordId = recordId;
}
public OptionalInt getSingleRecordId()
{
if (recordId == null)
{
return OptionalInt.empty();
}
return recordId.getSingleRecordId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\DataStatusEvent.java | 1 |
请完成以下Java代码 | public int getHR_Year_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_Year_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Net Days.
@param NetDays
Net Days in which payment is due
*/
public void setNetDays (int NetDays)
{
set_Value (COLUMNNAME_NetDays, Integer.valueOf(NetDays));
}
/** Get Net Days.
@return Net Days in which payment is due
*/
public int getNetDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NetDays);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Quantity.
@param Qty
Quantity
*/ | public void setQty (int Qty)
{
set_Value (COLUMNNAME_Qty, Integer.valueOf(Qty));
}
/** Get Quantity.
@return Quantity
*/
public int getQty ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Qty);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Year.java | 1 |
请完成以下Java代码 | final class WorkpackageLoggable implements ILoggable
{
private static final Logger logger = LogManager.getLogger(WorkpackageLoggable.class);
private final IWorkpackageLogsRepository logsRepository;
private final IErrorManager errorManager = Services.get(IErrorManager.class);
private final QueueWorkPackageId workpackageId;
private final ClientId adClientId;
private final UserId userId;
private final int bufferSize;
@Nullable
private List<WorkpackageLogEntry> buffer;
@Builder
public WorkpackageLoggable(
@NonNull final IWorkpackageLogsRepository logsRepository,
@NonNull final QueueWorkPackageId workpackageId,
@NonNull final ClientId adClientId,
@NonNull final UserId userId,
final int bufferSize)
{
Check.assumeGreaterThanZero(bufferSize, "bufferSize");
this.logsRepository = logsRepository;
this.workpackageId = workpackageId;
this.adClientId = adClientId;
this.userId = userId;
this.bufferSize = bufferSize;
this.buffer = null;
}
/**
* @param msgParameters The last parameter may be a {@link Throwable}. In that case, an AD_Issue is created and added to the log.
*/
@Override
public ILoggable addLog(final String msg, final Object... msgParameters)
{
final WorkpackageLogEntry logEntry = createLogEntry(msg, msgParameters);
List<WorkpackageLogEntry> buffer = this.buffer;
if (buffer == null)
{
buffer = this.buffer = new ArrayList<>(bufferSize);
}
buffer.add(logEntry);
if (buffer.size() >= bufferSize)
{
flush();
} | return this;
}
private WorkpackageLogEntry createLogEntry(@NonNull final String msg, final Object... msgParameters)
{
final FormattedMsgWithAdIssueId msgAndAdIssueId = LoggableWithThrowableUtil.extractMsgAndAdIssue(msg, msgParameters);
return WorkpackageLogEntry.builder()
.message(msgAndAdIssueId.getFormattedMessage())
.adIssueId(msgAndAdIssueId.getAdIsueId().orElse(null))
.timestamp(SystemTime.asInstant())
.workpackageId(workpackageId)
.adClientId(adClientId)
.userId(userId)
.build();
}
@Override
public void flush()
{
final List<WorkpackageLogEntry> logEntries = buffer;
this.buffer = null;
if (logEntries == null || logEntries.isEmpty())
{
return;
}
try
{
logsRepository.saveLogs(logEntries);
}
catch (final Exception ex)
{
// make sure flush never fails
logger.warn("Failed saving {} log entries but IGNORED: {}", logEntries.size(), logEntries, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\WorkpackageLoggable.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class NotificationServiceImpl implements NotificationService {
private final Logger log = LoggerFactory.getLogger(getClass());
@Autowired
private AccountServiceClient client;
@Autowired
private RecipientService recipientService;
@Autowired
private EmailService emailService;
@Override
@Scheduled(cron = "${backup.cron}")
public void sendBackupNotifications() {
final NotificationType type = NotificationType.BACKUP;
List<Recipient> recipients = recipientService.findReadyToNotify(type);
log.info("found {} recipients for backup notification", recipients.size());
recipients.forEach(recipient -> CompletableFuture.runAsync(() -> {
try {
String attachment = client.getAccount(recipient.getAccountName());
emailService.send(type, recipient, attachment); | recipientService.markNotified(type, recipient);
} catch (Throwable t) {
log.error("an error during backup notification for {}", recipient, t);
}
}));
}
@Override
@Scheduled(cron = "${remind.cron}")
public void sendRemindNotifications() {
final NotificationType type = NotificationType.REMIND;
List<Recipient> recipients = recipientService.findReadyToNotify(type);
log.info("found {} recipients for remind notification", recipients.size());
recipients.forEach(recipient -> CompletableFuture.runAsync(() -> {
try {
emailService.send(type, recipient, null);
recipientService.markNotified(type, recipient);
} catch (Throwable t) {
log.error("an error during remind notification for {}", recipient, t);
}
}));
}
} | repos\piggymetrics-master\notification-service\src\main\java\com\piggymetrics\notification\service\NotificationServiceImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String delete(Model model, DwzAjax dwz, @RequestParam("id") String id) {
RpPayWay rpPayWay = rpPayWayService.getDataById(id);
RpPayProduct rpPayProduct = rpPayProductService.getByProductCode(rpPayWay.getPayProductCode(), null);
if(rpPayProduct.getAuditStatus().equals(PublicEnum.YES.name())){
throw new PayBizException(PayBizException.PAY_PRODUCT_IS_EFFECTIVE,"支付产品已生效,无法删除!");
}
rpPayWay.setStatus(PublicStatusEnum.UNACTIVE.name());
rpPayWayService.updateData(rpPayWay);
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
/**
* 函数功能说明 :根据支付方式获取支付类型
*
* @参数: @return
* @return String
* @throws
*/
@RequestMapping(value = "/getPayType", method = RequestMethod.GET)
@ResponseBody
public List getPayType(@RequestParam("payWayCode") String payWayCode) {
return PayTypeEnum.getWayList(payWayCode);
}
/**
* 函数功能说明 :根据支付产品获取支付方式
*
* @参数: @return | * @return String
* @throws
*/
@RequestMapping(value = "/getPayWay", method = RequestMethod.GET)
@ResponseBody
public List getPayWay(@RequestParam("productCode") String productCode) {
List<RpPayWay> payWayList = rpPayWayService.listByProductCode(productCode);
Map<String, String> map = new HashMap<String, String>();
//过滤重复数据
for(RpPayWay payWay : payWayList){
map.put(payWay.getPayWayCode(), payWay.getPayWayName());
}
//转换json
List list = new ArrayList();
for (String key : map.keySet()) {
Map<String, String> mapJson = new HashMap<String, String>();
mapJson.put("desc", map.get(key));
mapJson.put("name", key);
list.add(mapJson);
}
return list;
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\pay\PayWayController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Customer {
@Id
@GeneratedValue
private Long id;
private String firstName;
private String lastName;
@Column(name = "email")
private String emailAddress;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName; | }
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmailAddress() {
return emailAddress;
}
public void setEmailAddress(String emailAddress) {
this.emailAddress = emailAddress;
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\namingstrategy\Customer.java | 2 |
请完成以下Java代码 | public class EncryptionPropertiesType {
@XmlElement(name = "EncryptionProperty", namespace = "http://www.w3.org/2001/04/xmlenc#", required = true)
protected List<EncryptionPropertyType> encryptionProperty;
@XmlAttribute(name = "Id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
@XmlSchemaType(name = "ID")
protected String id;
/**
* Gets the value of the encryptionProperty property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the encryptionProperty property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getEncryptionProperty().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link EncryptionPropertyType }
*
*
*/
public List<EncryptionPropertyType> getEncryptionProperty() {
if (encryptionProperty == null) {
encryptionProperty = new ArrayList<EncryptionPropertyType>();
}
return this.encryptionProperty;
} | /**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\EncryptionPropertiesType.java | 1 |
请完成以下Java代码 | public class DeptrackIngressResource extends CRUDKubernetesDependentResource<Ingress,DeptrackResource> {
private static final String COMPONENT = "ingress";
private final Ingress template;
public DeptrackIngressResource() {
super(Ingress.class);
this.template = BuilderHelper.loadTemplate(Ingress.class, "templates/ingress.yaml");
}
@Override
protected Ingress desired(DeptrackResource primary, Context<DeptrackResource> context) {
ObjectMeta meta = fromPrimary(primary,COMPONENT)
.build();
return new IngressBuilder(template)
.withMetadata(meta)
.editSpec()
.editDefaultBackend()
.editOrNewService()
.withName(primary.getFrontendServiceName())
.endService()
.endDefaultBackend()
.editFirstRule()
.withHost(primary.getSpec().getIngressHostname())
.withHttp(buildHttpRule(primary))
.endRule()
.endSpec()
.build();
}
private HTTPIngressRuleValue buildHttpRule(DeptrackResource primary) {
return new HTTPIngressRuleValueBuilder()
// Backend route
.addNewPath()
.withPath("/api")
.withPathType("Prefix")
.withNewBackend()
.withNewService()
.withName(primary.getApiServerServiceName())
.withNewPort()
.withName("http") | .endPort()
.endService()
.endBackend()
.endPath()
// Frontend route
.addNewPath()
.withPath("/")
.withPathType("Prefix")
.withNewBackend()
.withNewService()
.withName(primary.getFrontendServiceName())
.withNewPort()
.withName("http")
.endPort()
.endService()
.endBackend()
.endPath()
.build();
}
} | repos\tutorials-master\kubernetes-modules\k8s-operator\src\main\java\com\baeldung\operators\deptrack\resources\deptrack\DeptrackIngressResource.java | 1 |
请完成以下Java代码 | public void beforeSaveOfNextTermForPredecessor(
@NonNull final I_C_Flatrate_Term next,
@NonNull final I_C_Flatrate_Term predecessor)
{
final I_C_Flatrate_Conditions conditions = next.getC_Flatrate_Conditions();
if (X_C_Flatrate_Conditions.ONFLATRATETERMEXTEND_CalculatePrice.equals(conditions.getOnFlatrateTermExtend()))
{
final IPricingResult pricingInfo = FlatrateTermPricing.builder()
.termRelatedProductId(ProductId.ofRepoIdOrNull(next.getM_Product_ID()))
.term(next)
.priceDate(TimeUtil.asLocalDate(next.getStartDate()))
.qty(next.getPlannedQtyPerUnit())
.build()
.computeOrThrowEx();
next.setPriceActual(pricingInfo.getPriceStd());
next.setC_Currency_ID(pricingInfo.getCurrencyRepoId());
next.setC_UOM_ID(UomId.toRepoId(pricingInfo.getPriceUomId()));
next.setC_TaxCategory_ID(TaxCategoryId.toRepoId(pricingInfo.getTaxCategoryId())); | next.setIsTaxIncluded(pricingInfo.isTaxIncluded());
}
else if (X_C_Flatrate_Conditions.ONFLATRATETERMEXTEND_CopyPrice.equals(conditions.getOnFlatrateTermExtend()))
{
next.setPriceActual(predecessor.getPriceActual());
next.setC_Currency_ID(predecessor.getC_Currency_ID());
next.setC_UOM_ID(predecessor.getC_UOM_ID());
next.setC_TaxCategory_ID(predecessor.getC_TaxCategory_ID());
next.setIsTaxIncluded(predecessor.isTaxIncluded());
}
else
{
throw new AdempiereException("Unexpected OnFlatrateTermExtend=" + conditions.getOnFlatrateTermExtend())
.appendParametersToMessage()
.setParameter("conditions", conditions)
.setParameter("predecessor", predecessor)
.setParameter("next", next);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\impl\SubscriptionTermEventListener.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNoSelection();
}
return ProcessPreconditionsResolution.accept();
}
@NonNull
protected Iterator<GenericPO> retrieveDocumentsToProcess()
{
final String tableName = Check.assumeNotNull(getTableName(), "The process must be associated with a table!"); | final IQueryBuilder<Object> queryBuilder = queryBL.createQueryBuilder(tableName)
.addOnlyActiveRecordsFilter()
.filter(getProcessInfo().getQueryFilterOrElseFalse());
if (p_DocStatus != null)
{
queryBuilder.addEqualsFilter(PARAM_DocStatus, p_DocStatus);
}
return queryBuilder.create().iterate(GenericPO.class);
}
@Override
protected String getDocAction() {return p_DocAction;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\process\ProcessDocumentsBySelection.java | 1 |
请完成以下Java代码 | public ReadableByteChannel readableChannel() throws IOException {
ReadableByteChannel readableChannel = super.readableChannel();
return new ReadableByteChannel() {
@Override
public boolean isOpen() {
return readableChannel.isOpen();
}
@Override
public void close() throws IOException {
closeThenDeleteFile(readableChannel);
}
@Override
public int read(ByteBuffer dst) throws IOException {
return readableChannel.read(dst);
}
};
}
@Override
public InputStream getInputStream() throws IOException {
return new FilterInputStream(super.getInputStream()) {
@Override
public void close() throws IOException {
closeThenDeleteFile(this.in);
}
};
}
private void closeThenDeleteFile(Closeable closeable) throws IOException {
try {
closeable.close();
}
finally {
deleteFile();
} | }
private void deleteFile() {
try {
Files.delete(getFile().toPath());
}
catch (IOException ex) {
TemporaryFileSystemResource.this.logger
.warn("Failed to delete temporary heap dump file '" + getFile() + "'", ex);
}
}
@Override
public boolean isFile() {
// Prevent zero-copy so we can delete the file on close
return false;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\management\HeapDumpWebEndpoint.java | 1 |
请完成以下Java代码 | public void send(TopicPartitionInfo tpi, T msg, TbQueueCallback callback) {
send(tpi, msg.getKey().toString(), msg, callback);
}
public void send(TopicPartitionInfo tpi, String key, T msg, TbQueueCallback callback) {
try {
String topic = tpi.getFullTopicName();
createTopicIfNotExist(topic);
byte[] data = msg.getData();
ProducerRecord<String, byte[]> record;
List<Header> headers = msg.getHeaders().getData().entrySet().stream().map(e -> new RecordHeader(e.getKey(), e.getValue())).collect(Collectors.toList());
if (log.isDebugEnabled()) {
addAnalyticHeaders(headers);
}
Integer partition = tpi.isUseInternalPartition() ? tpi.getPartition().orElse(null) : null;
record = new ProducerRecord<>(topic, partition, key, data, headers);
producer.send(record, (metadata, exception) -> {
if (exception == null) {
if (callback != null) {
callback.onSuccess(new KafkaTbQueueMsgMetadata(metadata));
}
} else {
if (callback != null) {
callback.onFailure(exception);
} else {
log.warn("Producer template failure", exception);
}
}
});
} catch (Exception e) {
if (callback != null) {
callback.onFailure(e);
} else {
log.warn("Producer template failure (send method wrapper): {}", e.getMessage(), e);
}
throw e;
} | }
private void createTopicIfNotExist(String topic) {
if (topics.contains(topic)) {
return;
}
admin.createTopicIfNotExists(topic);
topics.add(topic);
}
@Override
public void stop() {
if (producer != null) {
producer.close();
}
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\kafka\TbKafkaProducerTemplate.java | 1 |
请完成以下Java代码 | public Collection<NotificationFilter> getFilters() {
return filteringNotifier.getNotificationFilters().values();
}
@PostMapping(path = "/notifications/filters", produces = MimeTypeUtils.APPLICATION_JSON_VALUE)
public ResponseEntity<?> addFilter(@RequestParam(name = "instanceId", required = false) String instanceId,
@RequestParam(name = "applicationName", required = false) String name,
@RequestParam(name = "ttl", required = false) Long ttl) {
if (hasText(instanceId) || hasText(name)) {
NotificationFilter filter = createFilter(hasText(instanceId) ? InstanceId.of(instanceId) : null, name, ttl);
filteringNotifier.addFilter(filter);
return ResponseEntity.ok(filter);
}
else {
return ResponseEntity.badRequest().body("Either 'instanceId' or 'applicationName' must be set");
}
}
@DeleteMapping(path = "/notifications/filters/{id}")
public ResponseEntity<Void> deleteFilter(@PathVariable("id") String id) {
NotificationFilter deleted = filteringNotifier.removeFilter(id); | if (deleted != null) {
return ResponseEntity.ok().build();
}
else {
return ResponseEntity.notFound().build();
}
}
private NotificationFilter createFilter(@Nullable InstanceId id, String name, @Nullable Long ttl) {
Instant expiry = ((ttl != null) && (ttl >= 0)) ? Instant.now().plusMillis(ttl) : null;
if (id != null) {
return new InstanceIdNotificationFilter(id, expiry);
}
else {
return new ApplicationNameNotificationFilter(name, expiry);
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\filter\web\NotificationFilterController.java | 1 |
请完成以下Java代码 | private Duration getElapsedTimeInSeconds(CachedResponse cachedResponse) {
return Duration.ofMillis(clock.millis() - cachedResponse.timestamp().getTime());
}
private static void rewriteCacheControlMaxAge(HttpHeaders headers, long seconds) {
boolean isMaxAgePresent = headers.getCacheControl() != null
&& headers.getCacheControl().contains(MAX_AGE_PREFIX);
List<String> newCacheControlDirectives = new ArrayList<>();
if (isMaxAgePresent) {
List<String> cacheControlHeaders = headers.get(HttpHeaders.CACHE_CONTROL);
cacheControlHeaders = cacheControlHeaders == null ? Collections.emptyList() : cacheControlHeaders;
for (String value : cacheControlHeaders) {
if (value.contains(MAX_AGE_PREFIX)) {
if (seconds == -1) {
List<String> removedMaxAgeList = Arrays.stream(value.split(","))
.filter(i -> !i.trim().startsWith(MAX_AGE_PREFIX))
.collect(Collectors.toList());
value = String.join(",", removedMaxAgeList); | }
else {
value = value.replaceFirst("\\bmax-age=\\d+\\b", MAX_AGE_PREFIX + seconds);
}
}
newCacheControlDirectives.add(value);
}
}
else {
List<String> cacheControlHeaders = headers.get(HttpHeaders.CACHE_CONTROL);
newCacheControlDirectives = cacheControlHeaders == null ? new ArrayList<>()
: new ArrayList<>(cacheControlHeaders);
newCacheControlDirectives.add("max-age=" + seconds);
}
headers.remove(HttpHeaders.CACHE_CONTROL);
headers.addAll(HttpHeaders.CACHE_CONTROL, newCacheControlDirectives);
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\postprocessor\SetMaxAgeHeaderAfterCacheExchangeMutator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BPartnerStats
{
int repoId;
BPartnerId bpartnerId;
BigDecimal openItems;
BigDecimal actualLifeTimeValue;
BigDecimal soCreditUsed;
String soCreditStatus;
@Builder
public BPartnerStats(
final int repoId,
@NonNull final BPartnerId bpartnerId,
@Nullable final BigDecimal openItems,
@Nullable final BigDecimal actualLifeTimeValue,
@Nullable final BigDecimal soCreditUsed,
@Nullable final String soCreditStatus)
{ | Check.assume(repoId > 0, "Given parameter repoId is > 0");
this.repoId = repoId;
this.bpartnerId = bpartnerId;
this.openItems = CoalesceUtil.coalesce(openItems, ZERO);
this.actualLifeTimeValue = CoalesceUtil.coalesce(actualLifeTimeValue, ZERO);
this.soCreditUsed = CoalesceUtil.coalesce(soCreditUsed, ZERO);
this.soCreditStatus = CoalesceUtil.coalesce(soCreditStatus, X_C_BPartner_Stats.SOCREDITSTATUS_NoCreditCheck);
}
public BigDecimal getSOCreditUsed()
{
return soCreditUsed;
}
public String getSOCreditStatus()
{
return soCreditStatus;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\BPartnerStats.java | 2 |
请完成以下Java代码 | public static String geCalendarNameFromConfiguration(String jobHandlerConfiguration) {
try {
JSONObject cfgJson = new JSONObject(jobHandlerConfiguration);
return cfgJson.get(PROPERTYNAME_CALENDAR_NAME_EXPRESSION).toString();
} catch (JSONException ex) {
// calendar name is not specified
return "";
}
}
public static String setEndDateToConfiguration(String jobHandlerConfiguration, String endDate) {
JSONObject cfgJson = null;
try {
cfgJson = new JSONObject(jobHandlerConfiguration);
} catch (JSONException ex) {
// create the json config
cfgJson = new JSONObject();
cfgJson.put(PROPERTYNAME_TIMER_ACTIVITY_ID, jobHandlerConfiguration); | }
if (endDate != null) {
cfgJson.put(PROPERTYNAME_END_DATE_EXPRESSION, endDate);
}
return cfgJson.toString();
}
public static String getEndDateFromConfiguration(String jobHandlerConfiguration) {
try {
JSONObject cfgJson = new JSONObject(jobHandlerConfiguration);
return cfgJson.get(PROPERTYNAME_END_DATE_EXPRESSION).toString();
} catch (JSONException ex) {
return null;
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\jobexecutor\TimerEventHandler.java | 1 |
请完成以下Java代码 | final class TimeZoneTranslatableString implements ITranslatableString
{
public static TimeZoneTranslatableString ofZoneId(@NonNull final ZoneId zoneId, @NonNull final TextStyle textStyle)
{
return new TimeZoneTranslatableString(zoneId, textStyle);
}
private final ZoneId zoneId;
private final TextStyle textStyle;
private TimeZoneTranslatableString(@NonNull final ZoneId zoneId, @NonNull final TextStyle textStyle)
{
this.zoneId = zoneId;
this.textStyle = textStyle;
}
@Deprecated
@Override
public String toString()
{
return zoneId.toString();
}
@Override | public String translate(final String adLanguage)
{
final Language language = Language.getLanguage(adLanguage);
final Locale locale = language.getLocale();
return zoneId.getDisplayName(textStyle, locale);
}
@Override
public String getDefaultValue()
{
return zoneId.getId();
}
@Override
public Set<String> getAD_Languages()
{
return ImmutableSet.of();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\TimeZoneTranslatableString.java | 1 |
请完成以下Java代码 | default void addInitializers(ServletContextInitializer... initializers) {
getSettings().addInitializers(initializers);
}
/**
* Sets the configuration that will be applied to the server's JSP servlet.
* @param jsp the JSP servlet configuration
*/
default void setJsp(Jsp jsp) {
getSettings().setJsp(jsp);
}
/**
* Sets the Locale to Charset mappings.
* @param localeCharsetMappings the Locale to Charset mappings
*/
default void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) {
getSettings().setLocaleCharsetMappings(localeCharsetMappings);
}
/**
* Sets the init parameters that are applied to the container's
* {@link ServletContext}.
* @param initParameters the init parameters
*/
default void setInitParameters(Map<String, String> initParameters) {
getSettings().setInitParameters(initParameters);
} | /**
* Sets {@link CookieSameSiteSupplier CookieSameSiteSuppliers} that should be used to
* obtain the {@link SameSite} attribute of any added cookie. This method will replace
* any previously set or added suppliers.
* @param cookieSameSiteSuppliers the suppliers to add
* @see #addCookieSameSiteSuppliers
*/
default void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) {
getSettings().setCookieSameSiteSuppliers(cookieSameSiteSuppliers);
}
/**
* Add {@link CookieSameSiteSupplier CookieSameSiteSuppliers} to those that should be
* used to obtain the {@link SameSite} attribute of any added cookie.
* @param cookieSameSiteSuppliers the suppliers to add
* @see #setCookieSameSiteSuppliers
*/
default void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) {
getSettings().addCookieSameSiteSuppliers(cookieSameSiteSuppliers);
}
@Override
default void addWebListeners(String... webListenerClassNames) {
getSettings().addWebListenerClassNames(webListenerClassNames);
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ConfigurableServletWebServerFactory.java | 1 |
请完成以下Java代码 | public void setF_EDITTIME(Timestamp f_EDITTIME) {
F_EDITTIME = f_EDITTIME;
}
public String getF_PLATFORM_ID() {
return F_PLATFORM_ID;
}
public void setF_PLATFORM_ID(String f_PLATFORM_ID) {
F_PLATFORM_ID = f_PLATFORM_ID;
}
public String getF_ISENTERPRISES() {
return F_ISENTERPRISES;
}
public void setF_ISENTERPRISES(String f_ISENTERPRISES) {
F_ISENTERPRISES = f_ISENTERPRISES; | }
public String getF_ISCLEAR() {
return F_ISCLEAR;
}
public void setF_ISCLEAR(String f_ISCLEAR) {
F_ISCLEAR = f_ISCLEAR;
}
public String getF_PARENTID() {
return F_PARENTID;
}
public void setF_PARENTID(String f_PARENTID) {
F_PARENTID = f_PARENTID;
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\common\vo\BscTollItem.java | 1 |
请完成以下Java代码 | public void setAD_FieldGroup_ID (int AD_FieldGroup_ID)
{
if (AD_FieldGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_FieldGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_FieldGroup_ID, Integer.valueOf(AD_FieldGroup_ID));
}
/** Get Field Group.
@return Logical grouping of fields
*/
public int getAD_FieldGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_FieldGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** EntityType AD_Reference_ID=389 */
public static final int ENTITYTYPE_AD_Reference_ID=389;
/** Set Entity Type.
@param EntityType
Dictionary Entity Type; Determines ownership and synchronization
*/
public void setEntityType (String EntityType)
{
set_Value (COLUMNNAME_EntityType, EntityType);
}
/** Get Entity Type.
@return Dictionary Entity Type; Determines ownership and synchronization
*/
public String getEntityType ()
{
return (String)get_Value(COLUMNNAME_EntityType);
}
/** FieldGroupType AD_Reference_ID=53000 */
public static final int FIELDGROUPTYPE_AD_Reference_ID=53000;
/** Tab = T */
public static final String FIELDGROUPTYPE_Tab = "T";
/** Label = L */
public static final String FIELDGROUPTYPE_Label = "L";
/** Collapse = C */
public static final String FIELDGROUPTYPE_Collapse = "C";
/** Set Field Group Type.
@param FieldGroupType Field Group Type */
public void setFieldGroupType (String FieldGroupType)
{
set_Value (COLUMNNAME_FieldGroupType, FieldGroupType);
}
/** Get Field Group Type.
@return Field Group Type */
public String getFieldGroupType ()
{
return (String)get_Value(COLUMNNAME_FieldGroupType);
}
/** Set Collapsed By Default.
@param IsCollapsedByDefault
Flag to set the initial state of collapsible field group.
*/ | public void setIsCollapsedByDefault (boolean IsCollapsedByDefault)
{
set_Value (COLUMNNAME_IsCollapsedByDefault, Boolean.valueOf(IsCollapsedByDefault));
}
/** Get Collapsed By Default.
@return Flag to set the initial state of collapsible field group.
*/
public boolean isCollapsedByDefault ()
{
Object oo = get_Value(COLUMNNAME_IsCollapsedByDefault);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_FieldGroup.java | 1 |
请完成以下Java代码 | public void setExternalSystem_Service_Instance_ID (final int ExternalSystem_Service_Instance_ID)
{
if (ExternalSystem_Service_Instance_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_Instance_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Service_Instance_ID, ExternalSystem_Service_Instance_ID);
}
@Override
public int getExternalSystem_Service_Instance_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Service_Instance_ID);
}
@Override
public void setExternalSystem_Status_ID (final int ExternalSystem_Status_ID)
{
if (ExternalSystem_Status_ID < 1)
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Status_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ExternalSystem_Status_ID, ExternalSystem_Status_ID);
}
@Override
public int getExternalSystem_Status_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Status_ID);
}
@Override
public void setExternalSystemMessage (final @Nullable java.lang.String ExternalSystemMessage)
{
set_Value (COLUMNNAME_ExternalSystemMessage, ExternalSystemMessage); | }
@Override
public java.lang.String getExternalSystemMessage()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemMessage);
}
/**
* ExternalSystemStatus AD_Reference_ID=541502
* Reference name: ExpectedStatus
*/
public static final int EXTERNALSYSTEMSTATUS_AD_Reference_ID=541502;
/** Active = Active */
public static final String EXTERNALSYSTEMSTATUS_Active = "Active";
/** Inactive = Inactive */
public static final String EXTERNALSYSTEMSTATUS_Inactive = "Inactive";
/** Error = Error */
public static final String EXTERNALSYSTEMSTATUS_Error = "Error ";
/** Down = Down */
public static final String EXTERNALSYSTEMSTATUS_Down = "Down";
@Override
public void setExternalSystemStatus (final java.lang.String ExternalSystemStatus)
{
set_Value (COLUMNNAME_ExternalSystemStatus, ExternalSystemStatus);
}
@Override
public java.lang.String getExternalSystemStatus()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemStatus);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Status.java | 1 |
请完成以下Java代码 | public class Node {
private Node next;
private String data;
public Node(String data) {
this.data = data;
}
public String data() {
return data;
}
public void setData(String data) {
this.data = data;
} | public boolean hasNext() {
return next != null;
}
public Node next() {
return next;
}
public void setNext(Node next) {
this.next = next;
}
public String toString() {
return this.data;
}
} | repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-4\src\main\java\com\baeldung\algorithms\middleelementlookup\Node.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private UserService userService;
@Bean
public JwtTokenFilter authenticationTokenFilterBean() throws Exception {
return new JwtTokenFilter();
}
@Bean
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
@Override
protected void configure( AuthenticationManagerBuilder auth ) throws Exception {
auth.userDetailsService( userService ).passwordEncoder( new BCryptPasswordEncoder() );
}
@Override | protected void configure( HttpSecurity httpSecurity ) throws Exception {
httpSecurity.csrf().disable()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()
.authorizeRequests()
.antMatchers(HttpMethod.OPTIONS, "/**").permitAll()
.antMatchers(HttpMethod.POST, "/authentication/**").permitAll()
.antMatchers(HttpMethod.POST).authenticated()
.antMatchers(HttpMethod.PUT).authenticated()
.antMatchers(HttpMethod.DELETE).authenticated()
.antMatchers(HttpMethod.GET).authenticated();
httpSecurity
.addFilterBefore(authenticationTokenFilterBean(), UsernamePasswordAuthenticationFilter.class);
httpSecurity.headers().cacheControl();
}
} | repos\Spring-Boot-In-Action-master\springbt_security_jwt\src\main\java\cn\codesheep\springbt_security_jwt\config\WebSecurityConfig.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.