instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String getName() {
return this.command.getName();
}
@Override
public String getDescription() {
return this.command.getDescription();
}
@Override
public @Nullable String getUsageHelp() {
return this.command.getUsageHelp();
}
@Override
public @Nullable String getHelp() {
return this.command.getHelp();
} | @Override
public Collection<OptionHelp> getOptionsHelp() {
return this.command.getOptionsHelp();
}
@Override
public ExitStatus run(String... args) throws Exception {
List<String> fullArgs = new ArrayList<>();
fullArgs.add("-cp");
fullArgs.add(System.getProperty("java.class.path"));
fullArgs.add(MAIN_CLASS);
fullArgs.add(this.command.getName());
fullArgs.addAll(Arrays.asList(args));
run(fullArgs);
return ExitStatus.OK;
}
} | repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\shell\ForkProcessCommand.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public LegacyReference legacyItemId(String legacyItemId)
{
this.legacyItemId = legacyItemId;
return this;
}
/**
* The unique identifier of a listing in legacy/Trading API format. Note: Both legacyItemId and legacyTransactionId are needed to identify an order line item.
*
* @return legacyItemId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The unique identifier of a listing in legacy/Trading API format. Note: Both legacyItemId and legacyTransactionId are needed to identify an order line item.")
public String getLegacyItemId()
{
return legacyItemId;
}
public void setLegacyItemId(String legacyItemId)
{
this.legacyItemId = legacyItemId;
}
public LegacyReference legacyTransactionId(String legacyTransactionId)
{
this.legacyTransactionId = legacyTransactionId;
return this;
}
/**
* The unique identifier of a sale/transaction in legacy/Trading API format. A 'transaction ID' is created once a buyer purchases a 'Buy It Now' item or if an auction listing ends with a winning bidder. Note: Both legacyItemId and legacyTransactionId are needed to identify an order line item.
*
* @return legacyTransactionId
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The unique identifier of a sale/transaction in legacy/Trading API format. A 'transaction ID' is created once a buyer purchases a 'Buy It Now' item or if an auction listing ends with a winning bidder. Note: Both legacyItemId and legacyTransactionId are needed to identify an order line item.")
public String getLegacyTransactionId()
{
return legacyTransactionId;
}
public void setLegacyTransactionId(String legacyTransactionId)
{
this.legacyTransactionId = legacyTransactionId;
}
@Override | public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
LegacyReference legacyReference = (LegacyReference)o;
return Objects.equals(this.legacyItemId, legacyReference.legacyItemId) &&
Objects.equals(this.legacyTransactionId, legacyReference.legacyTransactionId);
}
@Override
public int hashCode()
{
return Objects.hash(legacyItemId, legacyTransactionId);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class LegacyReference {\n");
sb.append(" legacyItemId: ").append(toIndentedString(legacyItemId)).append("\n");
sb.append(" legacyTransactionId: ").append(toIndentedString(legacyTransactionId)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\LegacyReference.java | 2 |
请完成以下Java代码 | public ExecutionEntity createProcessInstanceWithInitialFlowElement(
ProcessDefinition processDefinition,
String businessKey,
String processInstanceName,
FlowElement initialFlowElement,
Process process) {
CommandContext commandContext = Context.getCommandContext();
// Create the process instance
String initiatorVariableName = null;
if (initialFlowElement instanceof StartEvent) {
initiatorVariableName = ((StartEvent) initialFlowElement).getInitiator();
}
ExecutionEntity processInstance = commandContext
.getExecutionEntityManager()
.createProcessInstanceExecution(
processDefinition,
businessKey,
processDefinition.getTenantId(),
initiatorVariableName);
// Set processInstance name
setProcessInstanceName(commandContext, processInstance, processInstanceName);
// Create the first execution that will visit all the process definition elements
ExecutionEntity execution = commandContext.getExecutionEntityManager().createChildExecution(processInstance);
execution.setCurrentFlowElement(initialFlowElement);
return processInstance;
}
private void setProcessInstanceName(
CommandContext commandContext,
ExecutionEntity processInstance,
String processInstanceName
) {
if (processInstanceName != null) {
processInstance.setName(processInstanceName);
commandContext
.getHistoryManager() | .recordProcessInstanceNameChange(processInstance.getId(), processInstanceName);
}
}
protected void dispatchStartMessageReceivedEvent(
ExecutionEntity processInstance,
String messageName,
Map<String, Object> variables
) {
// Dispatch message received event
if (Context.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
// There will always be one child execution created
DelegateExecution execution = processInstance.getExecutions().get(0);
ActivitiEventDispatcher eventDispatcher = Context.getProcessEngineConfiguration().getEventDispatcher();
eventDispatcher.dispatchEvent(
ActivitiEventBuilder.createMessageReceivedEvent(execution, messageName, null, variables)
);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\ProcessInstanceHelper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void configure(HttpSecurity http) throws Exception{
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/", "/home**", "/about**").permitAll()
.antMatchers("/user/**").hasAnyRole("USER")
.antMatchers("/admin").access("hasAnyAuthority('ADMIN')")
.anyRequest().authenticated()
.and()
.formLogin()
.loginPage("/login")
.permitAll()
.and()
.logout()
.permitAll()
.and()
.exceptionHandling().accessDeniedHandler(accessDeniedHandler);
// http
// .csrf().disable()
// .authorizeRequests()
//
// .antMatchers("/login**", "/").permitAll()
// .antMatchers("/user/**").access("hasAnyAuthority('USER')") | // .antMatchers("/admin/**").access("hasAnyAuthority('ADMIN')")
//
// .anyRequest().fullyAuthenticated()
// .and()
// .formLogin();
//
}
// Create two users, admin and user
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("user").password("12345").roles("USER")
.and()
.withUser("admin").password("admin12345").roles("ADMIN");
}
} | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\12.SpringSecuritySimpleExample\src\main\java\spring\security\config\SpringSecurityConfig.java | 2 |
请完成以下Spring Boot application配置 | spring:
application:
name: demo-consumer
cloud:
# Sentinel 配置项,对应 SentinelProperties 配置属性类
sentinel:
enabled: true # 是否开启。默认为 true 开启
eager: true # 是否饥饿加载。默认为 false 关闭
transport:
dashboard: 127.0.0.1:7070 # Sentinel 控制台地址
filter:
url-pat | terns: /** # 拦截请求的地址。默认为 /*
server:
port: 8081
feign:
sentinel:
enabled: true # 开启 Sentinel 对 Feign 的支持,默认为 false 关闭。 | repos\SpringBoot-Labs-master\labx-04-spring-cloud-alibaba-sentinel\labx-04-sca-sentinel-feign-consumer\src\main\resources\application.yaml | 2 |
请完成以下Java代码 | public Builder setAttributesProvider(@Nullable final HUEditorRowAttributesProvider attributesProvider)
{
this.attributesProvider = attributesProvider;
return this;
}
public Builder addIncludedRow(@NonNull final HUEditorRow includedRow)
{
if (includedRows == null)
{
includedRows = new ArrayList<>();
}
includedRows.add(includedRow);
return this;
}
private List<HUEditorRow> buildIncludedRows()
{
if (includedRows == null || includedRows.isEmpty())
{
return ImmutableList.of();
}
return ImmutableList.copyOf(includedRows);
}
public Builder setReservedForOrderLine(@Nullable final OrderLineId orderLineId)
{
orderLineReservation = orderLineId;
huReserved = orderLineId != null;
return this;
}
public Builder setClearanceStatus(@Nullable final JSONLookupValue clearanceStatusLookupValue)
{
clearanceStatus = clearanceStatusLookupValue;
return this;
}
public Builder setCustomProcessApplyPredicate(@Nullable final BiPredicate<HUEditorRow, ProcessDescriptor> processApplyPredicate)
{
this.customProcessApplyPredicate = processApplyPredicate;
return this;
} | @Nullable
private BiPredicate<HUEditorRow, ProcessDescriptor> getCustomProcessApplyPredicate()
{
return this.customProcessApplyPredicate;
}
/**
* @param currentRow the row that is currently constructed using this builder
*/
private ImmutableMultimap<OrderLineId, HUEditorRow> prepareIncludedOrderLineReservations(@NonNull final HUEditorRow currentRow)
{
final ImmutableMultimap.Builder<OrderLineId, HUEditorRow> includedOrderLineReservationsBuilder = ImmutableMultimap.builder();
for (final HUEditorRow includedRow : buildIncludedRows())
{
includedOrderLineReservationsBuilder.putAll(includedRow.getIncludedOrderLineReservations());
}
if (orderLineReservation != null)
{
includedOrderLineReservationsBuilder.put(orderLineReservation, currentRow);
}
return includedOrderLineReservationsBuilder.build();
}
}
@lombok.Builder
@lombok.Value
public static class HUEditorRowHierarchy
{
@NonNull HUEditorRow cuRow;
@Nullable
HUEditorRow parentRow;
@Nullable
HUEditorRow topLevelRow;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorRow.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebEndpointProperties {
private final Exposure exposure = new Exposure();
/**
* Base path for Web endpoints. Relative to the servlet context path
* (server.servlet.context-path) or WebFlux base path (spring.webflux.base-path) when
* the management server is sharing the main server port. Relative to the management
* server base path (management.server.base-path) when a separate management server
* port (management.server.port) is configured.
*/
private String basePath = "/actuator";
/**
* Mapping between endpoint IDs and the path that should expose them.
*/
private final Map<String, String> pathMapping = new LinkedHashMap<>();
private final Discovery discovery = new Discovery();
public Exposure getExposure() {
return this.exposure;
}
public String getBasePath() {
return this.basePath;
}
public void setBasePath(String basePath) {
Assert.isTrue(basePath.isEmpty() || basePath.startsWith("/"), "'basePath' must start with '/' or be empty");
this.basePath = cleanBasePath(basePath);
}
private String cleanBasePath(String basePath) {
if (StringUtils.hasText(basePath) && basePath.endsWith("/")) {
return basePath.substring(0, basePath.length() - 1);
}
return basePath;
}
public Map<String, String> getPathMapping() {
return this.pathMapping;
}
public Discovery getDiscovery() {
return this.discovery;
}
public static class Exposure {
/**
* Endpoint IDs that should be included or '*' for all.
*/
private Set<String> include = new LinkedHashSet<>();
/**
* Endpoint IDs that should be excluded or '*' for all.
*/
private Set<String> exclude = new LinkedHashSet<>();
public Set<String> getInclude() {
return this.include;
}
public void setInclude(Set<String> include) {
this.include = include;
} | public Set<String> getExclude() {
return this.exclude;
}
public void setExclude(Set<String> exclude) {
this.exclude = exclude;
}
}
public static class Discovery {
/**
* Whether the discovery page is enabled.
*/
private boolean enabled = true;
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\web\WebEndpointProperties.java | 2 |
请完成以下Java代码 | public void setAD_Val_Rule_Dep_ID (int AD_Val_Rule_Dep_ID)
{
if (AD_Val_Rule_Dep_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_Dep_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_Dep_ID, Integer.valueOf(AD_Val_Rule_Dep_ID));
}
/** Get Validation Rule Depends On.
@return Validation Rule Depends On */
@Override
public int getAD_Val_Rule_Dep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Val_Rule_Dep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Val_Rule getAD_Val_Rule() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class);
}
@Override
public void setAD_Val_Rule(org.compiere.model.I_AD_Val_Rule AD_Val_Rule)
{
set_ValueFromPO(COLUMNNAME_AD_Val_Rule_ID, org.compiere.model.I_AD_Val_Rule.class, AD_Val_Rule);
}
/** Set Dynamische Validierung.
@param AD_Val_Rule_ID
Regel für die dynamische Validierung
*/
@Override
public void setAD_Val_Rule_ID (int AD_Val_Rule_ID)
{
if (AD_Val_Rule_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Val_Rule_ID, Integer.valueOf(AD_Val_Rule_ID)); | }
/** Get Dynamische Validierung.
@return Regel für die dynamische Validierung
*/
@Override
public int getAD_Val_Rule_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Val_Rule_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Technical note.
@param TechnicalNote
A note that is not indended for the user documentation, but for developers, customizers etc
*/
@Override
public void setTechnicalNote (java.lang.String TechnicalNote)
{
set_Value (COLUMNNAME_TechnicalNote, TechnicalNote);
}
/** Get Technical note.
@return A note that is not indended for the user documentation, but for developers, customizers etc
*/
@Override
public java.lang.String getTechnicalNote ()
{
return (java.lang.String)get_Value(COLUMNNAME_TechnicalNote);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Val_Rule_Dep.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String addUI(Model model) {
model.addAttribute("wxCityNoList", WxCityNo.getList());
return "trade/micro/submit/record/add";
}
/**
* 添加数据
*
* @param model
* @param rpMicroSubmitRecord
* @param dwz
* @return
*/
@RequiresPermissions("trade:micro:submit:record:add")
@RequestMapping(value = "/add", method = RequestMethod.POST)
public String add(Model model, RpMicroSubmitRecord rpMicroSubmitRecord, DwzAjax dwz) {
Map<String, Object> returnMap = rpMicroSubmitRecordService.microSubmit(rpMicroSubmitRecord);
if ("SUCCESS".equals(returnMap.get("return_code"))) {
if ("SUCCESS".equals(returnMap.get("result_code"))) {
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage(DWZ.SUCCESS_MSG);
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
} else {
dwz.setStatusCode(DWZ.ERROR);
dwz.setMessage(returnMap.get("err_code_des").toString());
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
} else {
dwz.setStatusCode(DWZ.ERROR);
dwz.setMessage(returnMap.get("return_msg").toString());
model.addAttribute("dwz", dwz);
return DWZ.AJAX_DONE;
}
} | @RequiresPermissions("trade:micro:submit:record:add")
@ResponseBody
@RequestMapping(value = "/uploadImage", method = RequestMethod.POST)
public Map<String, Object> upload(@RequestBody MultipartFile file) {
// 获取文件名
String fileName = file.getOriginalFilename();
// 获取文件后缀
String prefix = fileName.substring(fileName.lastIndexOf("."));
Map<String, Object> storeEntrancePicMap = null;
try {
// 用uuid作为文件名,防止生成的临时文件重复
final File excelFile = File.createTempFile(StringUtil.get32UUID(), prefix);
// MultipartFile to File
file.transferTo(excelFile);
storeEntrancePicMap = UploadUtils.upload(excelFile);
UploadUtils.deleteFile(excelFile);
} catch (Exception e) {
e.printStackTrace();
}
return storeEntrancePicMap;
}
// @RequiresPermissions("trade:micro:submit:record:query")
@RequestMapping(value = "/query/{businessCode}")
public String checkNotify(ModelMap model, @PathVariable(name = "businessCode") String businessCode) {
Map<String, Object> returnMap = rpMicroSubmitRecordService.microQuery(businessCode);
model.addAttribute("sign_url", returnMap.get("sign_url"));
model.addAttribute("returnMap", returnMap);
return "trade/micro/submit/record/query";
}
} | repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\trade\MicroSubmitRecordController.java | 2 |
请完成以下Java代码 | public void delete(EntityImpl entity, boolean fireDeleteEvent) {
getDataManager().delete(entity);
if (fireDeleteEvent && getEventDispatcher().isEnabled()) {
getEventDispatcher().dispatchEvent(
ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, entity)
);
}
}
protected abstract DataManager<EntityImpl> getDataManager();
/* Execution related entity count methods */
protected boolean isExecutionRelatedEntityCountEnabledGlobally() {
return processEngineConfiguration.getPerformanceSettings().isEnableExecutionRelationshipCounts();
}
protected boolean isExecutionRelatedEntityCountEnabled(ExecutionEntity executionEntity) {
if (executionEntity instanceof CountingExecutionEntity) {
return isExecutionRelatedEntityCountEnabled((CountingExecutionEntity) executionEntity);
} | return false;
}
protected boolean isExecutionRelatedEntityCountEnabled(CountingExecutionEntity executionEntity) {
/*
* There are two flags here: a global flag and a flag on the execution entity.
* The global flag can be switched on and off between different reboots,
* however the flag on the executionEntity refers to the state at that particular moment.
*
* Global flag / ExecutionEntity flag : result
*
* T / T : T (all true, regular mode with flags enabled)
* T / F : F (global is true, but execution was of a time when it was disabled, thus treating it as disabled)
* F / T : F (execution was of time when counting was done. But this is overruled by the global flag and thus the queries will be done)
* F / F : F (all disabled)
*
* From this table it is clear that only when both are true, the result should be true,
* which is the regular AND rule for booleans.
*/
return isExecutionRelatedEntityCountEnabledGlobally() && executionEntity.isCountEnabled();
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractEntityManager.java | 1 |
请完成以下Java代码 | static class CaseExecutionStateImpl implements CaseExecutionState {
public final int stateCode;
protected final String name;
public CaseExecutionStateImpl(int stateCode, String string) {
this.stateCode = stateCode;
this.name = string;
CASE_EXECUTION_STATES.put(stateCode, this);
}
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 |
请在Spring Boot框架中完成以下Java代码 | public BeanDefinition parse(Element element, ParserContext pc) {
RootBeanDefinition authProvider = new RootBeanDefinition(DaoAuthenticationProvider.class);
authProvider.setSource(pc.extractSource(element));
Element passwordEncoderElt = DomUtils.getChildElementByTagName(element, Elements.PASSWORD_ENCODER);
PasswordEncoderParser pep = new PasswordEncoderParser(passwordEncoderElt, pc);
BeanMetadataElement passwordEncoder = pep.getPasswordEncoder();
if (passwordEncoder != null) {
authProvider.getPropertyValues().addPropertyValue("passwordEncoder", passwordEncoder);
}
Element userServiceElt = DomUtils.getChildElementByTagName(element, Elements.USER_SERVICE);
if (userServiceElt == null) {
userServiceElt = DomUtils.getChildElementByTagName(element, Elements.JDBC_USER_SERVICE);
}
if (userServiceElt == null) {
userServiceElt = DomUtils.getChildElementByTagName(element, Elements.LDAP_USER_SERVICE);
}
String ref = element.getAttribute(ATT_USER_DETAILS_REF);
if (StringUtils.hasText(ref)) {
if (userServiceElt != null) {
pc.getReaderContext()
.error("The " + ATT_USER_DETAILS_REF + " attribute cannot be used in combination with child"
+ "elements '" + Elements.USER_SERVICE + "', '" + Elements.JDBC_USER_SERVICE + "' or '"
+ Elements.LDAP_USER_SERVICE + "'", element);
}
ValueHolder userDetailsServiceValueHolder = new ValueHolder(new RuntimeBeanReference(ref));
userDetailsServiceValueHolder.setName("userDetailsService");
authProvider.getConstructorArgumentValues().addGenericArgumentValue(userDetailsServiceValueHolder); | }
else {
// Use the child elements to create the UserDetailsService
if (userServiceElt != null) {
pc.getDelegate().parseCustomElement(userServiceElt, authProvider);
}
else {
pc.getReaderContext().error("A user-service is required", element);
}
// Pinch the cache-ref from the UserDetailsService element, if set.
String cacheRef = userServiceElt.getAttribute(AbstractUserDetailsServiceBeanDefinitionParser.CACHE_REF);
if (StringUtils.hasText(cacheRef)) {
authProvider.getPropertyValues().addPropertyValue("userCache", new RuntimeBeanReference(cacheRef));
}
}
return authProvider;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\authentication\AuthenticationProviderBeanDefinitionParser.java | 2 |
请完成以下Java代码 | public class DefaultElResolverLookup {
private final static ProcessApplicationLogger LOG = ProcessEngineLogger.PROCESS_APPLICATION_LOGGER;
public final static ELResolver lookupResolver(AbstractProcessApplication processApplication) {
ServiceLoader<ProcessApplicationElResolver> providers = ServiceLoader.load(ProcessApplicationElResolver.class);
List<ProcessApplicationElResolver> sortedProviders = new ArrayList<ProcessApplicationElResolver>();
for (ProcessApplicationElResolver provider : providers) {
sortedProviders.add(provider);
}
if(sortedProviders.isEmpty()) {
return null;
} else {
// sort providers first
Collections.sort(sortedProviders, new ProcessApplicationElResolver.ProcessApplicationElResolverSorter());
// add all providers to a composite resolver
CompositeELResolver compositeResolver = new CompositeELResolver();
StringBuilder summary = new StringBuilder();
summary.append(String.format("ElResolvers found for Process Application %s", processApplication.getName()));
for (ProcessApplicationElResolver processApplicationElResolver : sortedProviders) { | ELResolver elResolver = processApplicationElResolver.getElResolver(processApplication);
if (elResolver != null) {
compositeResolver.add(elResolver);
summary.append(String.format("Class %s", processApplicationElResolver.getClass().getName()));
}
else {
LOG.noElResolverProvided(processApplication.getName(), processApplicationElResolver.getClass().getName());
}
}
LOG.paElResolversDiscovered(summary.toString());
return compositeResolver;
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\DefaultElResolverLookup.java | 1 |
请完成以下Java代码 | protected void prepare()
{
for (ProcessInfoParameter para : getParametersAsArray())
{
String name = para.getParameterName();
if (para.getParameter() == null)
;
else if (name.equals("IsReadWrite"))
p_IsReadWrite = para.getParameter() == null ? null : "Y".equals(para.getParameter());
}
if (getTable_ID() == MRolePermRequest.Table_ID)
{
p_AD_Role_PermRequest_ID = getRecord_ID();
}
}
@Override
protected String doIt() throws Exception
{
if (p_AD_Role_PermRequest_ID <= 0)
throw new FillMandatoryException(MRolePermRequest.COLUMNNAME_AD_Role_PermRequest_ID);
//
final MRolePermRequest req = new MRolePermRequest(getCtx(), p_AD_Role_PermRequest_ID, get_TrxName());
if (p_IsReadWrite != null)
{
req.setIsReadWrite(p_IsReadWrite);
} | RolePermGrandAccess.grantAccess(req);
req.saveEx();
return "Ok";
}
@Override
protected void postProcess(boolean success)
{
if (success)
{
Services.get(IUserRolePermissionsDAO.class).resetCacheAfterTrxCommit();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\process\AD_Role_GrantPermission.java | 1 |
请完成以下Java代码 | public class ReverseArrayElements {
public static void reverseRowsUsingSimpleForLoops(int[][] array) {
for (int row = 0; row < array.length; row++) {
for (int col = 0; col < array[row].length / 2; col++) {
int current = array[row][col];
array[row][col] = array[row][array[row].length - col - 1];
array[row][array[row].length - col - 1] = current;
}
}
}
public static void reverseRowsUsingNestedIntStreams(int[][] array) {
IntStream.range(0, array.length)
.forEach(row -> IntStream.range(0, array[row].length / 2)
.forEach(col -> {
int current = array[row][col];
array[row][col] = array[row][array[row].length - col - 1];
array[row][array[row].length - col - 1] = current;
}));
}
public static void reverseRowsUsingCollectionsReverse(int[][] array) {
for (int row = 0; row < array.length; row++) {
List<Integer> collectionBoxedRow = Arrays.stream(array[row])
.boxed()
.collect(Collectors.toList());
Collections.reverse(collectionBoxedRow);
array[row] = collectionBoxedRow.stream()
.mapToInt(Integer::intValue)
.toArray();
}
}
public static void reverseRowsUsingCollectionsReverse(List<List<Integer>> array) {
array.forEach(Collections::reverse);
} | static <T> Collector<T, ?, List<T>> toReversedList() {
return Collector.of(
ArrayDeque::new,
(Deque<T> deque, T element) -> deque.addFirst(element),
(d1, d2) -> {
d2.addAll(d1);
return d2;
},
ArrayList::new
);
}
static <T> List<T> reverse(List<T> input) {
Object[] temp = input.toArray();
Stream<T> stream = (Stream<T>) IntStream.range(0, temp.length)
.mapToObj(i -> temp[temp.length - i - 1]);
return stream.collect(Collectors.toList());
}
} | repos\tutorials-master\core-java-modules\core-java-arrays-multidimensional\src\main\java\com\baeldung\array\reversearray\ReverseArrayElements.java | 1 |
请完成以下Java代码 | public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/**
* ModerationType AD_Reference_ID=395
* Reference name: CM_Chat ModerationType
*/
public static final int MODERATIONTYPE_AD_Reference_ID=395;
/** Not moderated = N */
public static final String MODERATIONTYPE_NotModerated = "N";
/** Before Publishing = B */
public static final String MODERATIONTYPE_BeforePublishing = "B";
/** After Publishing = A */
public static final String MODERATIONTYPE_AfterPublishing = "A";
/** Set Moderation Type.
@param ModerationType
Type of moderation
*/
@Override
public void setModerationType (java.lang.String ModerationType)
{
set_Value (COLUMNNAME_ModerationType, ModerationType);
}
/** Get Moderation Type.
@return Type of moderation
*/
@Override
public java.lang.String getModerationType ()
{
return (java.lang.String)get_Value(COLUMNNAME_ModerationType);
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
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 Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Chat.java | 1 |
请完成以下Java代码 | private JSONLookupValuesPage toJson(final LookupValuesPage page)
{
return JSONLookupValuesPage.of(page, userSession.getAD_Language());
}
@PostMapping("/{emailId}/field/attachments")
@Operation(summary = "Attaches a file to email")
public JSONEmail attachFile(@PathVariable("emailId") final String emailId, @RequestParam("file") final MultipartFile file)
{
userSession.assertLoggedIn();
final WebuiEmail email = attachFile(emailId, () -> mailAttachmentsRepo.createAttachment(emailId, file));
return JSONEmail.of(email, userSession.getAD_Language());
}
private WebuiEmail attachFile(final String emailId, final Supplier<LookupValue> attachmentProducer)
{
// Ask the producer to create the attachment
@NonNull final LookupValue attachment = attachmentProducer.get();
try
{
final WebuiEmailChangeResult result = changeEmail(emailId, emailOld -> {
final LookupValuesList attachmentsOld = emailOld.getAttachments();
final LookupValuesList attachmentsNew = attachmentsOld.addIfAbsent(attachment);
return emailOld.toBuilder().attachments(attachmentsNew).build();
});
return result.getEmail();
}
catch (final Throwable ex)
{
mailAttachmentsRepo.deleteAttachment(emailId, attachment);
throw AdempiereException.wrapIfNeeded(ex);
}
}
@GetMapping("/templates") | @Operation(summary = "Available Email templates")
public JSONLookupValuesList getTemplates()
{
userSession.assertLoggedIn();
return MADBoilerPlate.streamAllReadable(userSession.getUserRolePermissions())
.map(adBoilerPlate -> JSONLookupValue.of(adBoilerPlate.getAD_BoilerPlate_ID(), adBoilerPlate.getName()))
.collect(JSONLookupValuesList.collect());
}
private void applyTemplate(final WebuiEmail email, final WebuiEmailBuilder newEmailBuilder, final LookupValue templateId)
{
final Properties ctx = Env.getCtx();
final MADBoilerPlate boilerPlate = MADBoilerPlate.get(ctx, templateId.getIdAsInt());
if (boilerPlate == null)
{
throw new AdempiereException("No template found for " + templateId);
}
//
// Attributes
final BoilerPlateContext attributes = documentCollection.createBoilerPlateContext(email.getContextDocumentPath());
//
// Subject
final String subject = MADBoilerPlate.parseText(ctx, boilerPlate.getSubject(), true, attributes, ITrx.TRXNAME_None);
newEmailBuilder.subject(subject);
// Message
newEmailBuilder.message(boilerPlate.getTextSnippetParsed(attributes));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\mail\MailRestController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<DictDto> queryAll(DictQueryCriteria dict) {
List<Dict> list = dictRepository.findAll((root, query, cb) -> QueryHelp.getPredicate(root, dict, cb));
return dictMapper.toDto(list);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(Dict resources) {
dictRepository.save(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(Dict resources) {
// 清理缓存
delCaches(resources);
Dict dict = dictRepository.findById(resources.getId()).orElseGet(Dict::new);
ValidationUtil.isNull( dict.getId(),"Dict","id",resources.getId());
dict.setName(resources.getName());
dict.setDescription(resources.getDescription());
dictRepository.save(dict);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Set<Long> ids) {
// 清理缓存
List<Dict> dicts = dictRepository.findByIdIn(ids);
for (Dict dict : dicts) {
delCaches(dict);
}
dictRepository.deleteByIdIn(ids);
}
@Override
public void download(List<DictDto> dictDtos, HttpServletResponse response) throws IOException {
List<Map<String, Object>> list = new ArrayList<>();
for (DictDto dictDTO : dictDtos) {
if(CollectionUtil.isNotEmpty(dictDTO.getDictDetails())){
for (DictDetailDto dictDetail : dictDTO.getDictDetails()) {
Map<String,Object> map = new LinkedHashMap<>();
map.put("字典名称", dictDTO.getName()); | map.put("字典描述", dictDTO.getDescription());
map.put("字典标签", dictDetail.getLabel());
map.put("字典值", dictDetail.getValue());
map.put("创建日期", dictDetail.getCreateTime());
list.add(map);
}
} else {
Map<String,Object> map = new LinkedHashMap<>();
map.put("字典名称", dictDTO.getName());
map.put("字典描述", dictDTO.getDescription());
map.put("字典标签", null);
map.put("字典值", null);
map.put("创建日期", dictDTO.getCreateTime());
list.add(map);
}
}
FileUtil.downloadExcel(list, response);
}
public void delCaches(Dict dict){
redisUtils.del(CacheKey.DICT_NAME + dict.getName());
}
} | repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\DictServiceImpl.java | 2 |
请完成以下Java代码 | public final PO copy()
{
final GenericPO po = (GenericPO)super.copy();
po.tableName = this.tableName;
po.tableID = this.tableID;
return po;
}
} // GenericPO
/**
* Wrapper class to workaround the limit of PO constructor that doesn't take a tableName or
* tableID parameter. Note that in the generated class scenario ( X_ ), tableName and tableId
* is generated as a static field.
*
* @author Low Heng Sin | *
*/
final class PropertiesWrapper extends Properties
{
/**
*
*/
private static final long serialVersionUID = 8887531951501323594L;
protected Properties source;
protected String tableName;
PropertiesWrapper(Properties source, String tableName)
{
this.source = source;
this.tableName = tableName;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\adempiere\model\GenericPO.java | 1 |
请完成以下Java代码 | public void setAD_Form(org.compiere.model.I_AD_Form AD_Form)
{
set_ValueFromPO(COLUMNNAME_AD_Form_ID, org.compiere.model.I_AD_Form.class, AD_Form);
}
/** Set Special Form.
@param AD_Form_ID
Special Form
*/
@Override
public void setAD_Form_ID (int AD_Form_ID)
{
if (AD_Form_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Form_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Form_ID, Integer.valueOf(AD_Form_ID));
}
/** Get Special Form.
@return Special Form
*/
@Override
public int getAD_Form_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Form_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Role getAD_Role() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class);
}
@Override
public void setAD_Role(org.compiere.model.I_AD_Role AD_Role)
{
set_ValueFromPO(COLUMNNAME_AD_Role_ID, org.compiere.model.I_AD_Role.class, AD_Role);
}
/** Set Rolle.
@param AD_Role_ID
Responsibility Role
*/
@Override
public void setAD_Role_ID (int AD_Role_ID)
{
if (AD_Role_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID));
}
/** Get Rolle. | @return Responsibility Role
*/
@Override
public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Lesen und Schreiben.
@param IsReadWrite
Field is read / write
*/
@Override
public void setIsReadWrite (boolean IsReadWrite)
{
set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite));
}
/** Get Lesen und Schreiben.
@return Field is read / write
*/
@Override
public boolean isReadWrite ()
{
Object oo = get_Value(COLUMNNAME_IsReadWrite);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Form_Access.java | 1 |
请在Spring Boot框架中完成以下Java代码 | EntityManagerFactoryBuilderCustomizer entityManagerFactoryBootstrapExecutorCustomizer(
Map<String, AsyncTaskExecutor> taskExecutors) {
return (builder) -> {
AsyncTaskExecutor bootstrapExecutor = determineBootstrapExecutor(taskExecutors);
if (bootstrapExecutor != null) {
builder.setBootstrapExecutor(bootstrapExecutor);
}
};
}
@Bean
static LazyInitializationExcludeFilter eagerJpaMetamodelCacheCleanup() {
return (name, definition, type) -> "org.springframework.data.jpa.util.JpaMetamodelCacheCleanup".equals(name);
}
private @Nullable AsyncTaskExecutor determineBootstrapExecutor(Map<String, AsyncTaskExecutor> taskExecutors) {
if (taskExecutors.size() == 1) {
return taskExecutors.values().iterator().next();
}
return taskExecutors.get(TaskExecutionAutoConfiguration.APPLICATION_TASK_EXECUTOR_BEAN_NAME);
}
private static final class BootstrapExecutorCondition extends AnyNestedCondition {
BootstrapExecutorCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnProperty(name = "spring.data.jpa.repositories.bootstrap-mode", havingValue = "deferred")
static class DeferredBootstrapMode {
}
@ConditionalOnProperty(name = "spring.data.jpa.repositories.bootstrap-mode", havingValue = "lazy")
static class LazyBootstrapMode {
}
} | static class JpaRepositoriesImportSelector implements ImportSelector {
private static final boolean ENVERS_AVAILABLE = ClassUtils.isPresent(
"org.springframework.data.envers.repository.config.EnableEnversRepositories",
JpaRepositoriesImportSelector.class.getClassLoader());
@Override
public String[] selectImports(AnnotationMetadata importingClassMetadata) {
return new String[] { determineImport() };
}
private String determineImport() {
return ENVERS_AVAILABLE ? EnversRevisionRepositoriesRegistrar.class.getName()
: DataJpaRepositoriesRegistrar.class.getName();
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-data-jpa\src\main\java\org\springframework\boot\data\jpa\autoconfigure\DataJpaRepositoriesAutoConfiguration.java | 2 |
请完成以下Java代码 | public static com.google.protobuf.Descriptors.FileDescriptor
getDescriptor() {
return descriptor;
}
private static com.google.protobuf.Descriptors.FileDescriptor
descriptor;
static {
java.lang.String[] descriptorData = {
"\n$src/main/resources/addressbook.proto\022\010" +
"protobuf\"B\n\006Person\022\014\n\004name\030\001 \002(\t\022\n\n\002id\030\002" +
" \002(\005\022\r\n\005email\030\003 \001(\t\022\017\n\007numbers\030\004 \003(\t\"/\n\013" +
"AddressBook\022 \n\006people\030\001 \003(\0132\020.protobuf.P" +
"ersonB*\n\025com.baeldung.protobufB\021AddressB" +
"ookProtos"
};
descriptor = com.google.protobuf.Descriptors.FileDescriptor
.internalBuildGeneratedFileFrom(descriptorData,
new com.google.protobuf.Descriptors.FileDescriptor[] {
});
internal_static_protobuf_Person_descriptor =
getDescriptor().getMessageTypes().get(0); | internal_static_protobuf_Person_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_protobuf_Person_descriptor,
new java.lang.String[] { "Name", "Id", "Email", "Numbers", });
internal_static_protobuf_AddressBook_descriptor =
getDescriptor().getMessageTypes().get(1);
internal_static_protobuf_AddressBook_fieldAccessorTable = new
com.google.protobuf.GeneratedMessage.FieldAccessorTable(
internal_static_protobuf_AddressBook_descriptor,
new java.lang.String[] { "People", });
descriptor.resolveAllFeaturesImmutable();
}
// @@protoc_insertion_point(outer_class_scope)
} | repos\tutorials-master\google-protocol-buffer\src\main\java\com\baeldung\protobuf\AddressBookProtos.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void check() throws IOException {
AdminSettings settings = adminSettingsService.findAdminSettingsByKey(TenantId.SYS_TENANT_ID, "mail");
if (settings != null && settings.getJsonValue().has("enableOauth2") && settings.getJsonValue().get("enableOauth2").asBoolean()) {
JsonNode jsonValue = settings.getJsonValue();
if (OFFICE_365.name().equals(jsonValue.get("providerId").asText()) && jsonValue.has("refreshToken")
&& jsonValue.has("refreshTokenExpires")) {
try {
long expiresIn = jsonValue.get("refreshTokenExpires").longValue();
long tokenLifeDuration = expiresIn - System.currentTimeMillis();
if (tokenLifeDuration < 0) {
((ObjectNode) jsonValue).put("tokenGenerated", false);
((ObjectNode) jsonValue).remove("refreshToken");
((ObjectNode) jsonValue).remove("refreshTokenExpires");
adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, settings);
} else if (tokenLifeDuration < 604800000L) { //less than 7 days
log.info("Trying to refresh refresh token.");
String clientId = jsonValue.get("clientId").asText();
String clientSecret = jsonValue.get("clientSecret").asText();
String refreshToken = jsonValue.get("refreshToken").asText(); | String tokenUri = jsonValue.get("tokenUri").asText();
TokenResponse tokenResponse = new RefreshTokenRequest(new NetHttpTransport(), new GsonFactory(),
new GenericUrl(tokenUri), refreshToken)
.setClientAuthentication(new ClientParametersAuthentication(clientId, clientSecret))
.execute();
((ObjectNode) jsonValue).put("refreshToken", tokenResponse.getRefreshToken());
((ObjectNode) jsonValue).put("refreshTokenExpires", Instant.now().plus(Duration.ofDays(AZURE_DEFAULT_REFRESH_TOKEN_LIFETIME_IN_DAYS)).toEpochMilli());
adminSettingsService.saveAdminSettings(TenantId.SYS_TENANT_ID, settings);
}
} catch (Exception e) {
log.error("Error occurred while checking token", e);
}
}
}
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\mail\RefreshTokenExpCheckService.java | 2 |
请完成以下Java代码 | public int getData_PrintFormatItem_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Data_PrintFormatItem_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);
}
public I_AD_PrintFormatItem getDescription_PrintFormatItem() throws RuntimeException
{
return (I_AD_PrintFormatItem)MTable.get(getCtx(), I_AD_PrintFormatItem.Table_Name)
.getPO(getDescription_PrintFormatItem_ID(), get_TrxName()); }
/** Set Description Column.
@param Description_PrintFormatItem_ID
Description Column for Pie/Line/Bar Charts
*/
public void setDescription_PrintFormatItem_ID (int Description_PrintFormatItem_ID)
{
if (Description_PrintFormatItem_ID < 1)
set_Value (COLUMNNAME_Description_PrintFormatItem_ID, null);
else
set_Value (COLUMNNAME_Description_PrintFormatItem_ID, Integer.valueOf(Description_PrintFormatItem_ID));
}
/** Get Description Column.
@return Description Column for Pie/Line/Bar Charts
*/
public int getDescription_PrintFormatItem_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Description_PrintFormatItem_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** GraphType AD_Reference_ID=265 */
public static final int GRAPHTYPE_AD_Reference_ID=265;
/** Pie Chart = P */
public static final String GRAPHTYPE_PieChart = "P";
/** Line Chart = L */
public static final String GRAPHTYPE_LineChart = "L";
/** Bar Chart = B */
public static final String GRAPHTYPE_BarChart = "B";
/** Set Graph Type.
@param GraphType
Type of graph to be painted
*/
public void setGraphType (String GraphType)
{ | set_Value (COLUMNNAME_GraphType, GraphType);
}
/** Get Graph Type.
@return Type of graph to be painted
*/
public String getGraphType ()
{
return (String)get_Value(COLUMNNAME_GraphType);
}
/** 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_PrintGraph.java | 1 |
请完成以下Java代码 | public class C_InvoiceLine
{
private final DimensionService dimensionService = SpringContextHolder.instance.getBean(DimensionService.class);
private final IProductAcctDAO productAcctDAO = Services.get(IProductAcctDAO.class);
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = { I_C_InvoiceLine.COLUMNNAME_M_Product_ID })
public void updateActivity(final I_C_InvoiceLine invoiceLine)
{
if (invoiceLine.getC_Activity_ID() > 0)
{
return; // was already set, so don't try to auto-fill it
}
final ProductId productId = ProductId.ofRepoIdOrNull(invoiceLine.getM_Product_ID());
if (productId == null)
{
return;
}
final ActivityId productActivityId = productAcctDAO.retrieveActivityForAcct( | ClientId.ofRepoId(invoiceLine.getAD_Client_ID()),
OrgId.ofRepoId(invoiceLine.getAD_Org_ID()),
productId);
if (productActivityId == null)
{
return;
}
final Dimension orderLineDimension = dimensionService.getFromRecord(invoiceLine);
if (orderLineDimension == null)
{
//nothing to do
return;
}
dimensionService.updateRecord(invoiceLine, orderLineDimension.withActivityId(productActivityId));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\activity\model\validator\C_InvoiceLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected void validateCreate(TenantId tenantId, Customer customer) {
validateNumberOfEntitiesPerTenant(tenantId, EntityType.CUSTOMER);
}
@Override
protected Customer validateUpdate(TenantId tenantId, Customer customer) {
Customer old = customerDao.findById(customer.getTenantId(), customer.getId().getId());
if (old == null) {
throw new DataValidationException("Can't update non existing customer!");
}
return old;
}
@Override
protected void validateDataImpl(TenantId tenantId, Customer customer) { | validateString("Customer title", customer.getTitle());
if (customer.getTitle().equals(CustomerServiceImpl.PUBLIC_CUSTOMER_TITLE)) {
throw new DataValidationException("'Public' title for customer is system reserved!");
}
if (!StringUtils.isEmpty(customer.getEmail())) {
validateEmail(customer.getEmail());
}
if (customer.getTenantId() == null) {
throw new DataValidationException("Customer should be assigned to tenant!");
} else {
if (!tenantService.tenantExists(customer.getTenantId())) {
throw new DataValidationException("Customer is referencing to non-existent tenant!");
}
}
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\CustomerDataValidator.java | 2 |
请完成以下Java代码 | private static void addTableHeader(PdfPTable table) {
Stream.of("column header 1", "column header 2", "column header 3")
.forEach(columnTitle -> {
PdfPCell header = new PdfPCell();
header.setBackgroundColor(BaseColor.LIGHT_GRAY);
header.setBorderWidth(2);
header.setPhrase(new Phrase(columnTitle));
table.addCell(header);
});
}
private static void setAbsoluteColumnWidths(PdfPTable table) throws DocumentException {
table.setTotalWidth(500); // Sets total table width to 500 points
table.setLockedWidth(true);
float[] columnWidths = {100f, 200f, 200f}; // Defines three columns with absolute widths
table.setWidths(columnWidths);
}
private static void setAbsoluteColumnWidthsInTableWidth(PdfPTable table) throws DocumentException {
table.setTotalWidth(new float[] {72f, 144f, 216f}); // First column 1 inch, second 2 inches, third 3 inches
table.setLockedWidth(true);
}
private static void setRelativeColumnWidths(PdfPTable table) throws DocumentException {
// Set column widths (relative)
table.setWidths(new float[] {1, 2, 1});
table.setWidthPercentage(80); // Table width as 80% of page width
}
private static void addRows(PdfPTable table) {
table.addCell("row 1, col 1");
table.addCell("row 1, col 2");
table.addCell("row 1, col 3");
} | private static void addCustomRows(PdfPTable table) throws URISyntaxException, BadElementException, IOException {
Path path = Paths.get(ClassLoader.getSystemResource("Java_logo.png").toURI());
Image img = Image.getInstance(path.toAbsolutePath().toString());
img.scalePercent(10);
PdfPCell imageCell = new PdfPCell(img);
table.addCell(imageCell);
PdfPCell horizontalAlignCell = new PdfPCell(new Phrase("row 2, col 2"));
horizontalAlignCell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(horizontalAlignCell);
PdfPCell verticalAlignCell = new PdfPCell(new Phrase("row 2, col 3"));
verticalAlignCell.setVerticalAlignment(Element.ALIGN_BOTTOM);
table.addCell(verticalAlignCell);
}
} | repos\tutorials-master\text-processing-libraries-modules\pdf\src\main\java\com\baeldung\pdf\PDFSampleMain.java | 1 |
请完成以下Java代码 | public boolean validateToken(String token, UserDetails userDetails) {
String username = getUserNameFromToken(token);
return username.equals(userDetails.getUsername()) && !isTokenExpired(token);
}
/**
* 判断token是否已经失效
*/
private boolean isTokenExpired(String token) {
Date expiredDate = getExpiredDateFromToken(token);
return expiredDate.before(new Date());
}
/**
* 从token中获取过期时间
*/
private Date getExpiredDateFromToken(String token) {
Claims claims = getClaimsFromToken(token);
return claims.getExpiration();
}
/**
* 根据用户信息生成token
*/
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
claims.put(CLAIM_KEY_USERNAME, userDetails.getUsername());
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
/**
* 当原来的token没过期时是可以刷新的
*
* @param oldToken 带tokenHead的token
*/
public String refreshHeadToken(String oldToken) {
if(StrUtil.isEmpty(oldToken)){
return null;
}
String token = oldToken.substring(tokenHead.length());
if(StrUtil.isEmpty(token)){
return null;
}
//token校验不通过
Claims claims = getClaimsFromToken(token);
if(claims==null){
return null;
}
//如果token已经过期,不支持刷新
if(isTokenExpired(token)){ | return null;
}
//如果token在30分钟之内刚刷新过,返回原token
if(tokenRefreshJustBefore(token,30*60)){
return token;
}else{
claims.put(CLAIM_KEY_CREATED, new Date());
return generateToken(claims);
}
}
/**
* 判断token在指定时间内是否刚刚刷新过
* @param token 原token
* @param time 指定时间(秒)
*/
private boolean tokenRefreshJustBefore(String token, int time) {
Claims claims = getClaimsFromToken(token);
Date created = claims.get(CLAIM_KEY_CREATED, Date.class);
Date refreshDate = new Date();
//刷新时间在创建时间的指定时间内
if(refreshDate.after(created)&&refreshDate.before(DateUtil.offsetSecond(created,time))){
return true;
}
return false;
}
} | repos\mall-master\mall-security\src\main\java\com\macro\mall\security\util\JwtTokenUtil.java | 1 |
请完成以下Java代码 | public class CommissionShare
{
/**
* can be null if this share was not yet persisted.
*/
private final CommissionShareId id;
private final CommissionConfig config;
private final HierarchyLevel level;
private final Beneficiary beneficiary;
private final Payer payer;
private final SOTrx soTrx;
@Setter(AccessLevel.NONE)
private CommissionPoints forecastedPointsSum;
@Setter(AccessLevel.NONE)
private CommissionPoints invoiceablePointsSum;
@Setter(AccessLevel.NONE)
private CommissionPoints invoicedPointsSum;
/**
* Chronological list of facts that make it clear what happened when
*/
private final ArrayList<CommissionFact> facts;
@JsonCreator
@Builder
private CommissionShare(
@JsonProperty("id") @Nullable final CommissionShareId id,
@JsonProperty("config") @NonNull final CommissionConfig config,
@JsonProperty("level") @NonNull final HierarchyLevel level,
@JsonProperty("beneficiary") @NonNull final Beneficiary beneficiary,
@JsonProperty("facts") @NonNull @Singular final List<CommissionFact> facts,
@JsonProperty("payer") @NonNull final Payer payer,
@JsonProperty("soTrx") @NonNull final SOTrx soTrx)
{
this.id = id;
this.config = config;
this.level = level;
this.beneficiary = beneficiary;
this.payer = payer;
this.soTrx = soTrx;
this.facts = new ArrayList<>();
this.forecastedPointsSum = CommissionPoints.ZERO;
this.invoiceablePointsSum = CommissionPoints.ZERO;
this.invoicedPointsSum = CommissionPoints.ZERO;
for (final CommissionFact fact : facts)
{
addFact(fact); | }
}
public final CommissionShare addFact(@NonNull final CommissionFact fact)
{
facts.add(fact);
switch (fact.getState())
{
case FORECASTED:
forecastedPointsSum = forecastedPointsSum.add(fact.getPoints());
break;
case INVOICEABLE:
invoiceablePointsSum = invoiceablePointsSum.add(fact.getPoints());
break;
case INVOICED:
invoicedPointsSum = invoicedPointsSum.add(fact.getPoints());
break;
default:
throw new AdempiereException("fact has unsupported state " + fact.getState())
.appendParametersToMessage()
.setParameter("fact", fact);
}
return this;
}
public ImmutableList<CommissionFact> getFacts()
{
return ImmutableList.copyOf(facts);
}
public CommissionContract getContract()
{
return soTrx.isSales()
? config.getContractFor(payer.getBPartnerId())
: config.getContractFor(beneficiary.getBPartnerId());
}
public ProductId getCommissionProductId()
{
return config.getCommissionProductId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\sales\CommissionShare.java | 1 |
请完成以下Java代码 | public BigDecimal getInitialSchedQtyDelivered()
{
return initialSchedQtyDelivered;
}
public void setShipmentScheduleLineNetAmt(final BigDecimal lineNetAmt)
{
shipmentSchedule.setLineNetAmt(lineNetAmt);
}
@Nullable
public String getSalesOrderPORef()
{
return salesOrder.map(I_C_Order::getPOReference).orElse(null);
} | @Nullable
public InputDataSourceId getSalesOrderADInputDatasourceID()
{
if(!salesOrder.isPresent())
{
return null;
}
final I_C_Order orderRecord = salesOrder.get();
return InputDataSourceId.ofRepoIdOrNull(orderRecord.getAD_InputDataSource_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\OlAndSched.java | 1 |
请完成以下Java代码 | public class LoggingSessionFactory implements SessionFactory {
protected LoggingListener loggingListener;
protected ObjectMapper objectMapper;
@Override
public Class<?> getSessionType() {
return LoggingSession.class;
}
@Override
public Session openSession(CommandContext commandContext) {
return new LoggingSession(commandContext, loggingListener, objectMapper);
}
public LoggingListener getLoggingListener() { | return loggingListener;
}
public void setLoggingListener(LoggingListener loggingListener) {
this.loggingListener = loggingListener;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\logging\LoggingSessionFactory.java | 1 |
请完成以下Java代码 | public @Nullable String getName() {
return name;
}
public Config setName(String name) {
this.name = name;
return this;
}
public @Nullable String getId() {
if (!StringUtils.hasText(name) && StringUtils.hasText(routeId)) {
return routeId;
}
return name;
}
public Set<String> getStatusCodes() {
return statusCodes;
}
public Config setStatusCodes(Set<String> statusCodes) {
this.statusCodes = statusCodes;
return this;
}
public Config addStatusCode(String statusCode) {
this.statusCodes.add(statusCode);
return this;
}
public boolean isResumeWithoutError() {
return resumeWithoutError; | }
public void setResumeWithoutError(boolean resumeWithoutError) {
this.resumeWithoutError = resumeWithoutError;
}
}
public class CircuitBreakerStatusCodeException extends HttpStatusCodeException {
public CircuitBreakerStatusCodeException(HttpStatusCode statusCode) {
super(statusCode);
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SpringCloudCircuitBreakerFilterFactory.java | 1 |
请完成以下Java代码 | public class CompensationEventHandler implements EventHandler {
public String getEventHandlerType() {
return CompensateEventSubscriptionEntity.EVENT_TYPE;
}
public void handleEvent(EventSubscriptionEntity eventSubscription, Object payload, CommandContext commandContext) {
String configuration = eventSubscription.getConfiguration();
if (configuration == null) {
throw new ActivitiException(
"Compensating execution not set for compensate event subscription with id " + eventSubscription.getId()
);
}
ExecutionEntity compensatingExecution = commandContext.getExecutionEntityManager().findById(configuration);
String processDefinitionId = compensatingExecution.getProcessDefinitionId();
Process process = ProcessDefinitionUtil.getProcess(processDefinitionId);
if (process == null) {
throw new ActivitiException(
"Cannot start process instance. Process model (id = " + processDefinitionId + ") could not be found"
);
}
FlowElement flowElement = process.getFlowElement(eventSubscription.getActivityId(), true);
if (flowElement instanceof SubProcess && !((SubProcess) flowElement).isForCompensation()) {
// descend into scope:
compensatingExecution.setScope(true);
List<CompensateEventSubscriptionEntity> eventsForThisScope = commandContext
.getEventSubscriptionEntityManager()
.findCompensateEventSubscriptionsByExecutionId(compensatingExecution.getId());
ScopeUtil.throwCompensationEvent(eventsForThisScope, compensatingExecution, false);
} else {
try {
if (commandContext.getProcessEngineConfiguration().getEventDispatcher().isEnabled()) {
commandContext | .getProcessEngineConfiguration()
.getEventDispatcher()
.dispatchEvent(
ActivitiEventBuilder.createActivityEvent(
ActivitiEventType.ACTIVITY_COMPENSATE,
compensatingExecution,
flowElement
)
);
}
compensatingExecution.setCurrentFlowElement(flowElement);
Context.getAgenda().planContinueProcessInCompensation(compensatingExecution);
} catch (Exception e) {
throw new ActivitiException("Error while handling compensation event " + eventSubscription, e);
}
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\event\CompensationEventHandler.java | 1 |
请完成以下Java代码 | public void setLuId(@Nullable final HuPackingInstructionsId luId)
{
orderLine.setM_LU_HU_PI_ID(HuPackingInstructionsId.toRepoId(luId));
}
@Override
public HuPackingInstructionsId getLuId()
{
return HuPackingInstructionsId.ofRepoIdOrNull(orderLine.getM_LU_HU_PI_ID());
}
@Override
public boolean isInDispute()
{
// order line has no IsInDispute flag
return values.isInDispute();
} | @Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
@Override
public String toString()
{
return String
.format("OrderLineHUPackingAware [orderLine=%s, getM_Product_ID()=%s, getM_Product()=%s, getQty()=%s, getM_HU_PI_Item_Product()=%s, getM_AttributeSetInstance_ID()=%s, getC_UOM()=%s, getQtyPacks()=%s, getC_BPartner()=%s, getM_HU_PI_Item_Product_ID()=%s, qtyLU()=%s, luId()=%s, isInDispute()=%s]",
orderLine, getM_Product_ID(), getM_Product_ID(), getQty(), getM_HU_PI_Item_Product_ID(), getM_AttributeSetInstance_ID(), getC_UOM_ID(), getQtyTU(), getC_BPartner_ID(),
getM_HU_PI_Item_Product_ID(), getQtyLU(), getLuId(), isInDispute());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OrderLineHUPackingAware.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean supports(Class<?> clazz) {
return true;
}
});
ProxyExchangeArgumentResolver resolver = new ProxyExchangeArgumentResolver(template);
resolver.setHeaders(properties.convertHeaders());
resolver.setAutoForwardedHeaders(properties.getAutoForward());
Set<String> excludedHeaderNames = new HashSet<>();
if (!CollectionUtils.isEmpty(properties.getSensitive())) {
excludedHeaderNames.addAll(properties.getSensitive());
}
if (!CollectionUtils.isEmpty(properties.getSkipped())) {
excludedHeaderNames.addAll(properties.getSkipped());
}
resolver.setExcluded(excludedHeaderNames);
return resolver;
}
@Override
public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
argumentResolvers.add(context.getBean(ProxyExchangeArgumentResolver.class));
} | private static final class NoOpResponseErrorHandler extends DefaultResponseErrorHandler {
@Override
public void handleError(URI url, HttpMethod method, ClientHttpResponse response) throws IOException {
}
@Override
protected void handleError(ClientHttpResponse response, HttpStatusCode statusCode, @Nullable URI url,
@Nullable HttpMethod method) throws IOException {
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-proxyexchange-webmvc\src\main\java\org\springframework\cloud\gateway\mvc\config\ProxyResponseAutoConfiguration.java | 2 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Displayed.
@param IsDisplayed
Determines, if this field is displayed
*/
public void setIsDisplayed (boolean IsDisplayed)
{
set_Value (COLUMNNAME_IsDisplayed, Boolean.valueOf(IsDisplayed));
}
/** Get Displayed.
@return Determines, if this field is displayed
*/
public boolean isDisplayed ()
{
Object oo = get_Value(COLUMNNAME_IsDisplayed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Multi Row Only.
@param IsMultiRowOnly
This applies to Multi-Row view only
*/
public void setIsMultiRowOnly (boolean IsMultiRowOnly)
{
set_Value (COLUMNNAME_IsMultiRowOnly, Boolean.valueOf(IsMultiRowOnly));
}
/** Get Multi Row Only.
@return This applies to Multi-Row view only
*/
public boolean isMultiRowOnly ()
{
Object oo = get_Value(COLUMNNAME_IsMultiRowOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Read Only.
@param IsReadOnly
Field is read only
*/
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Read Only.
@return Field is read only
*/
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false; | }
/** Set Single Row Layout.
@param IsSingleRow
Default for toggle between Single- and Multi-Row (Grid) Layout
*/
public void setIsSingleRow (boolean IsSingleRow)
{
set_Value (COLUMNNAME_IsSingleRow, Boolean.valueOf(IsSingleRow));
}
/** Get Single Row Layout.
@return Default for toggle between Single- and Multi-Row (Grid) Layout
*/
public boolean isSingleRow ()
{
Object oo = get_Value(COLUMNNAME_IsSingleRow);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Tab.java | 1 |
请完成以下Java代码 | protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_CM_ChatTypeUpdate[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_User getAD_User() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getAD_User_ID(), get_TrxName()); }
/** Set User/Contact.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get User/Contact.
@return User within the system - Internal or Business Partner Contact
*/
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_CM_ChatType getCM_ChatType() throws RuntimeException
{
return (I_CM_ChatType)MTable.get(getCtx(), I_CM_ChatType.Table_Name)
.getPO(getCM_ChatType_ID(), get_TrxName()); }
/** Set Chat Type.
@param CM_ChatType_ID
Type of discussion / chat
*/ | public void setCM_ChatType_ID (int CM_ChatType_ID)
{
if (CM_ChatType_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, Integer.valueOf(CM_ChatType_ID));
}
/** Get Chat Type.
@return Type of discussion / chat
*/
public int getCM_ChatType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatType_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Self-Service.
@param IsSelfService
This is a Self-Service entry or this entry can be changed via Self-Service
*/
public void setIsSelfService (boolean IsSelfService)
{
set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService));
}
/** Get Self-Service.
@return This is a Self-Service entry or this entry can be changed via Self-Service
*/
public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
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_CM_ChatTypeUpdate.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebSecurityConfig {
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.authorizeHttpRequests(auth -> auth
.requestMatchers("/css/**", "/js/**", "/loggedout")
.permitAll()
.anyRequest()
.authenticated())
.httpBasic(Customizer.withDefaults())
.logout(AbstractHttpConfigurer::disable)
.csrf(AbstractHttpConfigurer::disable);
return http.build();
}
@Bean
public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) { | UserDetails jim = User.withUsername("jim")
.password(passwordEncoder.encode("jim"))
.roles("USER", "ACTUATOR")
.build();
UserDetails pam = User.withUsername("pam")
.password(passwordEncoder.encode("pam"))
.roles("USER")
.build();
UserDetails michael = User.withUsername("michael")
.password(passwordEncoder.encode("michael"))
.roles("MANAGER")
.build();
return new InMemoryUserDetailsManager(jim, pam, michael);
}
} | repos\tutorials-master\spring-security-modules\spring-security-core-2\src\main\java\com\baeldung\app\config\WebSecurityConfig.java | 2 |
请完成以下Java代码 | final class Utility
{
private static final int SECOND = 1000;
private static final int MINUTE = 60 * SECOND;
private static final int HOUR = 60 * MINUTE;
private static final int DAY = 24 * HOUR;
static String humanTime(long ms)
{
StringBuffer text = new StringBuffer("");
if (ms > DAY)
{
text.append(ms / DAY).append(" d ");
ms %= DAY;
}
if (ms > HOUR)
{
text.append(ms / HOUR).append(" h ");
ms %= HOUR;
}
if (ms > MINUTE)
{
text.append(ms / MINUTE).append(" m ");
ms %= MINUTE;
}
if (ms > SECOND)
{
long s = ms / SECOND;
if (s < 10)
{
text.append('0');
}
text.append(s).append(" s ");
// ms %= SECOND;
}
// text.append(ms + " ms");
return text.toString();
}
/**
* @param c
*/
public static void closeQuietly(Closeable c)
{
try
{
if (c != null) c.close();
}
catch (IOException ignored)
{
}
}
/**
* @param raf
*/
public static void closeQuietly(RandomAccessFile raf)
{
try
{
if (raf != null) raf.close();
}
catch (IOException ignored)
{
}
}
public static void closeQuietly(InputStream is)
{
try
{
if (is != null) is.close();
}
catch (IOException ignored)
{
}
} | public static void closeQuietly(Reader r)
{
try
{
if (r != null) r.close();
}
catch (IOException ignored)
{
}
}
public static void closeQuietly(OutputStream os)
{
try
{
if (os != null) os.close();
}
catch (IOException ignored)
{
}
}
public static void closeQuietly(Writer w)
{
try
{
if (w != null) w.close();
}
catch (IOException ignored)
{
}
}
/**
* 数组分割
*
* @param from 源
* @param to 目标
* @param <T> 类型
* @return 目标
*/
public static <T> T[] shrink(T[] from, T[] to)
{
assert to.length <= from.length;
System.arraycopy(from, 0, to, 0, to.length);
return to;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Utility.java | 1 |
请完成以下Java代码 | public class ActivitiMessageEventImpl extends ActivitiActivityEventImpl implements ActivitiMessageEvent {
protected String messageName;
protected String correlationKey;
protected Object messageData;
protected String businessKey;
public ActivitiMessageEventImpl(ActivitiEventType type) {
super(type);
}
public void setMessageName(String messageName) {
this.messageName = messageName;
}
public String getMessageName() {
return messageName;
}
public void setMessageData(Object messageData) {
this.messageData = messageData;
}
public Object getMessageData() { | return messageData;
}
public String getMessageCorrelationKey() {
return correlationKey;
}
public void setMessageCorrelationKey(String correlationKey) {
this.correlationKey = correlationKey;
}
public String getMessageBusinessKey() {
return businessKey;
}
public void setMessageBusinessKey(String businessKey) {
this.businessKey = businessKey;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\delegate\event\impl\ActivitiMessageEventImpl.java | 1 |
请完成以下Java代码 | public static String cleanString(String value) {
if (!StringUtils.hasText(value)) {
return "";
}
value = value.toLowerCase();
value = value.replaceAll("<", "& lt;").replaceAll(">", "& gt;");
value = value.replaceAll("\\(", "& #40;").replaceAll("\\)", "& #41;");
value = value.replaceAll("'", "& #39;");
value = value.replaceAll("onload", "0nl0ad");
value = value.replaceAll("xml", "xm1");
value = value.replaceAll("window", "wind0w");
value = value.replaceAll("click", "cl1ck");
value = value.replaceAll("var", "v0r");
value = value.replaceAll("let", "1et");
value = value.replaceAll("function", "functi0n");
value = value.replaceAll("return", "retu1n");
value = value.replaceAll("$", "");
value = value.replaceAll("document", "d0cument");
value = value.replaceAll("const", "c0nst");
value = value.replaceAll("eval\\((.*)\\)", ""); | value = value.replaceAll("[\\\"\\\'][\\s]*javascript:(.*)[\\\"\\\']", "\"\"");
value = value.replaceAll("script", "scr1pt");
value = value.replaceAll("insert", "1nsert");
value = value.replaceAll("drop", "dr0p");
value = value.replaceAll("create", "cre0ate");
value = value.replaceAll("update", "upd0ate");
value = value.replaceAll("alter", "a1ter");
value = value.replaceAll("from", "fr0m");
value = value.replaceAll("where", "wh1re");
value = value.replaceAll("database", "data1base");
value = value.replaceAll("table", "tab1e");
value = value.replaceAll("tb", "tb0");
return value;
}
} | repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\java\com\site\springboot\core\util\AntiXssUtils.java | 1 |
请完成以下Java代码 | public OrderLineBuilder addQty(@NonNull final Quantity qtyToAdd)
{
assertNotBuilt();
return qty(Quantity.addNullables(this.qty, qtyToAdd));
}
public OrderLineBuilder qty(@NonNull final BigDecimal qty)
{
if (productId == null)
{
throw new AdempiereException("Setting BigDecimal Qty not allowed if the product was not already set");
}
final I_C_UOM uom = productBL.getStockUOM(productId);
return qty(Quantity.of(qty, uom));
}
@Nullable
private UomId getUomId()
{
return qty != null ? qty.getUomId() : null;
}
public OrderLineBuilder priceUomId(@Nullable final UomId priceUomId)
{
assertNotBuilt();
this.priceUomId = priceUomId;
return this;
}
public OrderLineBuilder externalId(@Nullable final ExternalId externalId)
{
assertNotBuilt();
this.externalId = externalId;
return this;
}
public OrderLineBuilder manualPrice(@Nullable final BigDecimal manualPrice)
{
assertNotBuilt();
this.manualPrice = manualPrice;
return this;
}
public OrderLineBuilder manualPrice(@Nullable final Money manualPrice)
{
return manualPrice(manualPrice != null ? manualPrice.toBigDecimal() : null);
}
public OrderLineBuilder manualDiscount(final BigDecimal manualDiscount)
{
assertNotBuilt();
this.manualDiscount = manualDiscount;
return this;
}
public OrderLineBuilder setDimension(final Dimension dimension)
{
assertNotBuilt();
this.dimension = dimension; | return this;
}
public boolean isProductAndUomMatching(@Nullable final ProductId productId, @Nullable final UomId uomId)
{
return ProductId.equals(getProductId(), productId)
&& UomId.equals(getUomId(), uomId);
}
public OrderLineBuilder description(@Nullable final String description)
{
this.description = description;
return this;
}
public OrderLineBuilder hideWhenPrinting(final boolean hideWhenPrinting)
{
this.hideWhenPrinting = hideWhenPrinting;
return this;
}
public OrderLineBuilder details(@NonNull final Collection<OrderLineDetailCreateRequest> details)
{
assertNotBuilt();
detailCreateRequests.addAll(details);
return this;
}
public OrderLineBuilder detail(@NonNull final OrderLineDetailCreateRequest detail)
{
assertNotBuilt();
detailCreateRequests.add(detail);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLineBuilder.java | 1 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_TaxPostal[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_C_Tax getC_Tax() throws RuntimeException
{
return (I_C_Tax)MTable.get(getCtx(), I_C_Tax.Table_Name)
.getPO(getC_Tax_ID(), get_TrxName()); }
/** Set Tax.
@param C_Tax_ID
Tax identifier
*/
public void setC_Tax_ID (int C_Tax_ID)
{
if (C_Tax_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Tax_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Tax_ID, Integer.valueOf(C_Tax_ID));
}
/** Get Tax.
@return Tax identifier
*/
public int getC_Tax_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Tax_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Tax ZIP.
@param C_TaxPostal_ID
Tax Postal/ZIP
*/
public void setC_TaxPostal_ID (int C_TaxPostal_ID)
{
if (C_TaxPostal_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_TaxPostal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_TaxPostal_ID, Integer.valueOf(C_TaxPostal_ID));
}
/** Get Tax ZIP.
@return Tax Postal/ZIP
*/
public int getC_TaxPostal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxPostal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set ZIP.
@param Postal | Postal code
*/
public void setPostal (String Postal)
{
set_Value (COLUMNNAME_Postal, Postal);
}
/** Get ZIP.
@return Postal code
*/
public String getPostal ()
{
return (String)get_Value(COLUMNNAME_Postal);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getPostal());
}
/** Set ZIP To.
@param Postal_To
Postal code to
*/
public void setPostal_To (String Postal_To)
{
set_Value (COLUMNNAME_Postal_To, Postal_To);
}
/** Get ZIP To.
@return Postal code to
*/
public String getPostal_To ()
{
return (String)get_Value(COLUMNNAME_Postal_To);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxPostal.java | 1 |
请完成以下Java代码 | public SecurityInfo getByIdentity(String pskIdentity) {
SecurityInfo securityInfo = securityStore.getByIdentity(pskIdentity);
if (securityInfo == null) {
try {
securityInfo = fetchAndPutSecurityInfo(pskIdentity);
} catch (LwM2MAuthException e) {
log.trace("Registration failed: No pre-shared key found for [identity: {}]", pskIdentity);
return null;
}
}
return securityInfo;
}
@Override
public SecurityInfo getByOscoreIdentity(OscoreIdentity oscoreIdentity) {
return null;
}
public SecurityInfo fetchAndPutSecurityInfo(String credentialsId) {
TbLwM2MSecurityInfo securityInfo = validator.getEndpointSecurityInfoByCredentialsId(credentialsId, CLIENT);
doPut(securityInfo);
return securityInfo != null ? securityInfo.getSecurityInfo() : null;
}
private void doPut(TbLwM2MSecurityInfo securityInfo) {
if (securityInfo != null) {
try {
securityStore.put(securityInfo);
} catch (NonUniqueSecurityInfoException e) {
log.trace("Failed to add security info: {}", securityInfo, e); | }
}
}
@Override
public void putX509(TbLwM2MSecurityInfo securityInfo) throws NonUniqueSecurityInfoException {
securityStore.put(securityInfo);
}
@Override
public void registerX509(String endpoint, String registrationId) {
endpointRegistrations.computeIfAbsent(endpoint, ep -> new HashSet<>()).add(registrationId);
}
@Override
public void remove(String endpoint, String registrationId) {
Set<String> epRegistrationIds = endpointRegistrations.get(endpoint);
boolean shouldRemove;
if (epRegistrationIds == null) {
shouldRemove = true;
} else {
epRegistrationIds.remove(registrationId);
shouldRemove = epRegistrationIds.isEmpty();
}
if (shouldRemove) {
securityStore.remove(endpoint);
}
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbLwM2mSecurityStore.java | 1 |
请完成以下Java代码 | private static ImmutableSet<FlatrateDataEntryDetailKey> extractExistingDetailKeys(final FlatrateDataEntry entry)
{
return entry
.getDetails()
.stream()
.map(detail -> new FlatrateDataEntryDetailKey(
detail.getBPartnerDepartment().getId(),
createAttributesKey(detail.getAsiId()))
)
.collect(ImmutableSet.toImmutableSet());
}
private static AttributesKey createAttributesKey(@NonNull final AttributeSetInstanceId asiId)
{
return AttributesKeys
.createAttributesKeyFromASIAllAttributes(asiId)
.orElse(AttributesKey.NONE);
}
private List<BPartnerDepartment> retrieveBPartnerDepartments(@NonNull final BPartnerId bPartnerId)
{
final List<BPartnerDepartment> departments = bPartnerDepartmentRepo.getByBPartnerId(bPartnerId);
if (departments.isEmpty()) | {
return ImmutableList.of(BPartnerDepartment.none(bPartnerId));
}
return departments;
}
@Value
static class FlatrateDataEntryDetailKey
{
@NonNull
BPartnerDepartmentId bPartnerDepartmentId;
@NonNull
AttributesKey attributesKey;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\dataEntry\FlatrateDataEntryService.java | 1 |
请完成以下Java代码 | public String getTheme() {
return theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public String getUsersAccess() { | return usersAccess;
}
public void setUsersAccess(String usersAccess) {
this.usersAccess = usersAccess;
}
public String getGroupsAccess() {
return groupsAccess;
}
public void setGroupsAccess(String groupsAccess) {
this.groupsAccess = groupsAccess;
}
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\deployer\BaseAppModel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HelloWorldController {
@RequestMapping("/hello")
public Map<String, Object> showHelloWorld(){
Map<String, Object> map = new HashMap<>();
map.put("msg", "HelloWorld");
return map;
}
@Autowired
private FileUploadService fileUploadService;
/**
* upload
*
* @param files
* @return
*/
@PostMapping("/upload")
public ResponseEntity<String> upload(@RequestParam("files") MultipartFile[] files) {
fileUploadService.upload(files);
return ResponseEntity.ok("File Upload Success");
} | /**
* files
*
* @return
*/
@GetMapping("/files")
public ResponseEntity<List<FileInfo>> list() {
return ResponseEntity.ok(fileUploadService.list());
}
/**
* get file by name
*
* @param fileName
* @return
*/
@GetMapping("/files/{fileName:.+}")
public ResponseEntity<Resource> getFile(@PathVariable("fileName") String fileName) {
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + fileName + "\"").body(fileUploadService.getFile(fileName));
}
} | repos\springboot-demo-master\file\src\main\java\com\et\controller\HelloWorldController.java | 2 |
请完成以下Java代码 | public static void apply(GridFieldVO vo)
{
for (MUserDefWin uw : get(vo.getCtx(), vo.getAdWindowId()))
{
MUserDefTab ut = uw.getTab(vo.AD_Tab_ID);
if (ut == null)
{
continue;
}
MUserDefField uf = ut.getField(vo.getAD_Field_ID());
if (uf != null)
{
uf.apply(vo);
}
}
}
@SuppressWarnings("unused")
public MUserDefWin(Properties ctx, int AD_UserDef_Win_ID, String trxName)
{
super(ctx, AD_UserDef_Win_ID, trxName);
}
@SuppressWarnings("unused")
public MUserDefWin(Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
}
/**
* @return tab customizations for this window
*/
private MUserDefTab[] getTabs()
{
if (m_tabs != null)
{
return m_tabs;
}
final String whereClause = MUserDefTab.COLUMNNAME_AD_UserDef_Win_ID+"=?";
final List<MUserDefTab> list = new Query(getCtx(), MUserDefTab.Table_Name, whereClause, get_TrxName())
.setParameters(get_ID())
.setOnlyActiveRecords(true)
.setOrderBy(MUserDefTab.COLUMNNAME_AD_Tab_ID)
.list(MUserDefTab.class);
//
m_tabs = list.toArray(new MUserDefTab[0]); | return m_tabs;
}
private MUserDefTab[] m_tabs = null;
/**
* @return tab customization of given AD_Tab_ID or null if not found
*/
public MUserDefTab getTab(int AD_Tab_ID)
{
if (AD_Tab_ID <= 0)
{
return null;
}
for (MUserDefTab tab : getTabs())
{
if (AD_Tab_ID == tab.getAD_Tab_ID())
{
return tab;
}
}
return null;
}
@Override
public String toString()
{
return getClass().getName()+"[ID="+get_ID()
+", AD_Org_ID="+getAD_Org_ID()
+", AD_Role_ID="+getAD_Role_ID()
+", AD_User_ID="+getAD_User_ID()
+", AD_Window_ID="+getAD_Window_ID()
+", Name="+getName()
+"]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\MUserDefWin.java | 1 |
请完成以下Java代码 | public boolean isCalculationTypePercent()
{
return CALCULATIONTYPE_PercentageOp1OfOp2.equals(getCalculationType());
}
/**
* Column Type Calculation
* @return true if calculation
*/
public boolean isColumnTypeCalculation()
{
return COLUMNTYPE_Calculation.equals(getColumnType());
}
/**
* Column Type Relative Period
* @return true if relative period
*/
public boolean isColumnTypeRelativePeriod()
{
return COLUMNTYPE_RelativePeriod.equals(getColumnType());
}
/**
* Column Type Segment Value
* @return true if segment value
*/
public boolean isColumnTypeSegmentValue()
{
return COLUMNTYPE_SegmentValue.equals(getColumnType());
}
/**
* Get Relative Period As Int
* @return relative period
*/
public int getRelativePeriodAsInt ()
{
BigDecimal bd = getRelativePeriod();
if (bd == null)
return 0;
return bd.intValue();
} // getRelativePeriodAsInt
/**
* Get Relative Period
* @return relative period
*/
@Override
public BigDecimal getRelativePeriod()
{
if (getColumnType().equals(COLUMNTYPE_RelativePeriod)
|| getColumnType().equals(COLUMNTYPE_SegmentValue))
return super.getRelativePeriod();
return null;
} // getRelativePeriod
/**
* Get Element Type
*/
@Override
public String getElementType()
{
if (getColumnType().equals(COLUMNTYPE_SegmentValue))
{
return super.getElementType();
}
else
{
return null;
}
} // getElementType
/**
* Get Calculation Type
*/
@Override
public String getCalculationType()
{
if (getColumnType().equals(COLUMNTYPE_Calculation))
return super.getCalculationType(); | return null;
} // getCalculationType
/**
* Before Save
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave(boolean newRecord)
{
// Validate Type
String ct = getColumnType();
if (ct.equals(COLUMNTYPE_RelativePeriod))
{
setElementType(null);
setCalculationType(null);
}
else if (ct.equals(COLUMNTYPE_Calculation))
{
setElementType(null);
setRelativePeriod(null);
}
else if (ct.equals(COLUMNTYPE_SegmentValue))
{
setCalculationType(null);
}
return true;
} // beforeSave
/**************************************************************************
/**
* Copy
* @param ctx context
* @param AD_Client_ID parent
* @param AD_Org_ID parent
* @param PA_ReportColumnSet_ID parent
* @param source copy source
* @param trxName transaction
* @return Report Column
*/
public static MReportColumn copy (Properties ctx, int AD_Client_ID, int AD_Org_ID,
int PA_ReportColumnSet_ID, MReportColumn source, String trxName)
{
MReportColumn retValue = new MReportColumn (ctx, 0, trxName);
MReportColumn.copyValues(source, retValue, AD_Client_ID, AD_Org_ID);
//
retValue.setPA_ReportColumnSet_ID(PA_ReportColumnSet_ID); // parent
retValue.setOper_1_ID(0);
retValue.setOper_2_ID(0);
return retValue;
} // copy
} // MReportColumn | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\report\MReportColumn.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class PortMapperConfigurer<H extends HttpSecurityBuilder<H>>
extends AbstractHttpConfigurer<PortMapperConfigurer<H>, H> {
private PortMapper portMapper;
private Map<String, String> httpsPortMappings = new HashMap<>();
/**
* Creates a new instance
*/
public PortMapperConfigurer() {
}
/**
* Allows specifying the {@link PortMapper} instance.
* @param portMapper
* @return the {@link PortMapperConfigurer} for further customizations
*/
public PortMapperConfigurer<H> portMapper(PortMapper portMapper) {
this.portMapper = portMapper;
return this;
}
/**
* Adds a port mapping
* @param httpPort the HTTP port that maps to a specific HTTPS port.
* @return {@link HttpPortMapping} to define the HTTPS port
*/
public HttpPortMapping http(int httpPort) {
return new HttpPortMapping(httpPort);
}
@Override
public void init(H http) {
http.setSharedObject(PortMapper.class, getPortMapper());
}
/**
* Gets the {@link PortMapper} to use. If {@link #portMapper(PortMapper)} was not
* invoked, builds a {@link PortMapperImpl} using the port mappings specified with
* {@link #http(int)}.
* @return the {@link PortMapper} to use
*/
private PortMapper getPortMapper() {
if (this.portMapper == null) { | PortMapperImpl portMapper = new PortMapperImpl();
portMapper.setPortMappings(this.httpsPortMappings);
this.portMapper = portMapper;
}
return this.portMapper;
}
/**
* Allows specifying the HTTPS port for a given HTTP port when redirecting between
* HTTP and HTTPS.
*
* @author Rob Winch
* @since 3.2
*/
public final class HttpPortMapping {
private final int httpPort;
/**
* Creates a new instance
* @param httpPort
* @see PortMapperConfigurer#http(int)
*/
private HttpPortMapping(int httpPort) {
this.httpPort = httpPort;
}
/**
* Maps the given HTTP port to the provided HTTPS port and vice versa.
* @param httpsPort the HTTPS port to map to
* @return the {@link PortMapperConfigurer} for further customization
*/
public PortMapperConfigurer<H> mapsTo(int httpsPort) {
PortMapperConfigurer.this.httpsPortMappings.put(String.valueOf(this.httpPort), String.valueOf(httpsPort));
return PortMapperConfigurer.this;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\PortMapperConfigurer.java | 2 |
请完成以下Java代码 | public TodoResponseDto findById(
@PathVariable("id") final Long id
) {
// Action
return service.findById(id) //
.map(mapper::map) // map to dto
.orElseThrow(NotFoundException::new);
}
@PostMapping(consumes = DEFAULT_MEDIA_TYPE)
public ResponseEntity<TodoResponseDto> create(final @Valid @RequestBody TodoRequestDto item) {
// Action
final var todo = mapper.map(item, null);
final var newTodo = service.create(todo);
final var result = mapper.map(newTodo);
// Response
final URI locationHeader = linkTo(methodOn(TodosController.class).findById(result.getId())).toUri(); // HATEOAS
return ResponseEntity.created(locationHeader).body(result);
} | @PutMapping(value = "{id}", consumes = DEFAULT_MEDIA_TYPE)
@ResponseStatus(NO_CONTENT)
public void update(
@PathVariable("id") final Long id,
@Valid @RequestBody final TodoRequestDto item
) {
service.update(mapper.map(item, id));
}
@DeleteMapping("/{id}")
@ResponseStatus(NO_CONTENT)
public void delete(
@PathVariable("id") final Long id
) {
service.delete(id);
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-3\src\main\java\com\baeldung\sample\boundary\TodosController.java | 1 |
请完成以下Java代码 | public Criteria andValueIn(List<String> values) {
addCriterion("value in", values, "value");
return (Criteria) this;
}
public Criteria andValueNotIn(List<String> values) {
addCriterion("value not in", values, "value");
return (Criteria) this;
}
public Criteria andValueBetween(String value1, String value2) {
addCriterion("value between", value1, value2, "value");
return (Criteria) this;
}
public Criteria andValueNotBetween(String value1, String value2) {
addCriterion("value not between", value1, value2, "value");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() { | return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
}
protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductAttributeValueExample.java | 1 |
请完成以下Java代码 | static @Nullable ServletWebServerApplicationContext getWebServerApplicationContextIfPossible(
ApplicationContext context) {
try {
return (ServletWebServerApplicationContext) context;
}
catch (NoClassDefFoundError | ClassCastException ex) {
return null;
}
}
@Override
public @Nullable LocalTestWebServer getLocalTestWebServer() {
if (this.context == null) {
return null;
}
return LocalTestWebServer.of((isSslEnabled(this.context)) ? Scheme.HTTPS : Scheme.HTTP, () -> {
int port = this.context.getEnvironment().getProperty("local.server.port", Integer.class, 8080);
String path = this.context.getEnvironment().getProperty("server.servlet.context-path", "");
return new BaseUriDetails(port, path); | });
}
private boolean isSslEnabled(ServletWebServerApplicationContext context) {
try {
AbstractConfigurableWebServerFactory webServerFactory = context
.getBean(AbstractConfigurableWebServerFactory.class);
return webServerFactory.getSsl() != null && webServerFactory.getSsl().isEnabled();
}
catch (NoSuchBeanDefinitionException ex) {
return false;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\context\ServletWebServerApplicationContextLocalTestWebServerProvider.java | 1 |
请完成以下Spring Boot application配置 | app.datasource.ds1.url=jdbc:mysql://localhost:3306/booksdb?createDatabaseIfNotExist=true
app.datasource.ds1.username=root
app.datasource.ds1.password=root
app.datasource.ds1.connection-timeout=50000
app.datasource.ds1.idle-timeout=300000
app.datasource.ds1.max-lifetime=900000
app.datasource.ds1.maximum-pool-size=5
app.datasource.ds1.minimum-idle=5
app.datasource.ds1.pool-name=BooksPoolConnection
app.flyway.ds1.location=classpath:db/migration/booksdb
app.datasource.ds2.url=jdbc:mysql://localhost:3306/authorsdb?createDatabaseIfNotExist=true
app.datasource.ds2.username=root
app.datasource.ds2.password=root
app.datasource.ds2.connection-timeout=50000
app.datasource.ds2.idle-timeout=300000
app.datasource.ds2.max-lifetime=900000
app.dat | asource.ds2.maximum-pool-size=6
app.datasource.ds2.minimum-idle=6
app.datasource.ds2.pool-name=AuthorsConnectionPool
app.flyway.ds2.location=classpath:db/migration/authorsdb
spring.flyway.enabled=false
spring.jpa.show-sql=true
logging.level.com.zaxxer.hikari.HikariConfig=DEBUG
logging.level.com.zaxxer.hikari=TRACE | repos\Hibernate-SpringBoot-master\HibernateSpringBootFlywayMySQLTwoDatabases\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public void setAD_Language(final UserId adUserId, final String adLanguage)
{
final org.compiere.model.I_AD_User user = userDAO.getByIdInTrx(adUserId, I_AD_User.class);
user.setAD_Language(adLanguage);
InterfaceWrapperHelper.save(user);
}
@Interceptor(I_AD_User.class)
@AllArgsConstructor
private static class AD_User_UserSessionUpdater
{
private final UserSessionRepository userSessionRepo;
/**
* If system user and it's the user's of current session, then load the current session.
*/
@ModelChange(timings = ModelValidator.TYPE_AFTER_CHANGE, afterCommit = true)
public void onUserChanged(final org.compiere.model.I_AD_User user) | {
if (!user.isSystemUser())
{
return;
}
final UserId userId = UserId.ofRepoId(user.getAD_User_ID());
final UserSession userSession = UserSession.getCurrentIfMatchingOrNull(userId);
if (userSession == null)
{
return;
}
userSessionRepo.loadFromAD_User(userSession, user);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserSessionRepository.java | 1 |
请完成以下Java代码 | public void setCompletionCondition(String completionCondition) {
this.completionCondition = completionCondition;
}
public String getElementVariable() {
return elementVariable;
}
public void setElementVariable(String elementVariable) {
this.elementVariable = elementVariable;
}
public String getElementIndexVariable() {
return elementIndexVariable;
}
public void setElementIndexVariable(String elementIndexVariable) {
this.elementIndexVariable = elementIndexVariable;
}
public boolean isSequential() {
return sequential;
}
public void setSequential(boolean sequential) {
this.sequential = sequential;
}
public boolean isNoWaitStatesAsyncLeave() {
return noWaitStatesAsyncLeave;
}
public void setNoWaitStatesAsyncLeave(boolean noWaitStatesAsyncLeave) {
this.noWaitStatesAsyncLeave = noWaitStatesAsyncLeave;
}
public VariableAggregationDefinitions getAggregations() {
return aggregations;
}
public void setAggregations(VariableAggregationDefinitions aggregations) {
this.aggregations = aggregations;
}
public void addAggregation(VariableAggregationDefinition aggregation) {
if (this.aggregations == null) {
this.aggregations = new VariableAggregationDefinitions();
}
this.aggregations.getAggregations().add(aggregation);
} | @Override
public MultiInstanceLoopCharacteristics clone() {
MultiInstanceLoopCharacteristics clone = new MultiInstanceLoopCharacteristics();
clone.setValues(this);
return clone;
}
public void setValues(MultiInstanceLoopCharacteristics otherLoopCharacteristics) {
super.setValues(otherLoopCharacteristics);
setInputDataItem(otherLoopCharacteristics.getInputDataItem());
setCollectionString(otherLoopCharacteristics.getCollectionString());
if (otherLoopCharacteristics.getHandler() != null) {
setHandler(otherLoopCharacteristics.getHandler().clone());
}
setLoopCardinality(otherLoopCharacteristics.getLoopCardinality());
setCompletionCondition(otherLoopCharacteristics.getCompletionCondition());
setElementVariable(otherLoopCharacteristics.getElementVariable());
setElementIndexVariable(otherLoopCharacteristics.getElementIndexVariable());
setSequential(otherLoopCharacteristics.isSequential());
setNoWaitStatesAsyncLeave(otherLoopCharacteristics.isNoWaitStatesAsyncLeave());
if (otherLoopCharacteristics.getAggregations() != null) {
setAggregations(otherLoopCharacteristics.getAggregations().clone());
}
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\MultiInstanceLoopCharacteristics.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void addParts(final IPackingItem packingItem)
{
getDelegate().addParts(packingItem);
}
public final IPackingItem addPartsAndReturn(final IPackingItem packingItem)
{
return getDelegate().addPartsAndReturn(packingItem);
}
@Override
public void addParts(final PackingItemParts toAdd)
{
getDelegate().addParts(toAdd);
}
@Override
public Set<WarehouseId> getWarehouseIds()
{
return getDelegate().getWarehouseIds();
}
@Override
public Set<ShipmentScheduleId> getShipmentScheduleIds()
{
return getDelegate().getShipmentScheduleIds();
}
@Override
public IPackingItem subtractToPackingItem(
final Quantity subtrahent,
final Predicate<PackingItemPart> acceptPartPredicate)
{
return getDelegate().subtractToPackingItem(subtrahent, acceptPartPredicate);
}
@Override | public PackingItemParts subtract(final Quantity subtrahent)
{
return getDelegate().subtract(subtrahent);
}
@Override
public PackingItemParts getParts()
{
return getDelegate().getParts();
}
@Override
public ProductId getProductId()
{
return getDelegate().getProductId();
}
@Override
public Quantity getQtySum()
{
return getDelegate().getQtySum();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\ForwardingPackingItem.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public static DataScopeModel getDataScopeByMapper(String mapperId, String roleId) {
DataScopeModel dataScope = CacheUtil.get(SYS_CACHE, SCOPE_CACHE_CLASS, mapperId + StringPool.COLON + roleId, DataScopeModel.class);
if (dataScope == null || !dataScope.getSearched()) {
dataScope = getDataScopeClient().getDataScopeByMapper(mapperId, roleId);
CacheUtil.put(SYS_CACHE, SCOPE_CACHE_CLASS, mapperId + StringPool.COLON + roleId, dataScope);
}
return StringUtil.isNotBlank(dataScope.getResourceCode()) ? dataScope : null;
}
/**
* 获取数据权限
*
* @param code 数据权限资源编号
* @return DataScopeModel
*/
public static DataScopeModel getDataScopeByCode(String code) {
DataScopeModel dataScope = CacheUtil.get(SYS_CACHE, SCOPE_CACHE_CODE, code, DataScopeModel.class);
if (dataScope == null || !dataScope.getSearched()) {
dataScope = getDataScopeClient().getDataScopeByCode(code);
CacheUtil.put(SYS_CACHE, SCOPE_CACHE_CODE, code, dataScope);
} | return StringUtil.isNotBlank(dataScope.getResourceCode()) ? dataScope : null;
}
/**
* 获取部门子级
*
* @param deptId 部门id
* @return deptIds
*/
public static List<Long> getDeptAncestors(Long deptId) {
List ancestors = CacheUtil.get(SYS_CACHE, DEPT_CACHE_ANCESTORS, deptId, List.class);
if (CollectionUtil.isEmpty(ancestors)) {
ancestors = getDataScopeClient().getDeptAncestors(deptId);
CacheUtil.put(SYS_CACHE, DEPT_CACHE_ANCESTORS, deptId, ancestors);
}
return ancestors;
}
} | repos\SpringBlade-master\blade-service-api\blade-scope-api\src\main\java\org\springblade\system\cache\DataScopeCache.java | 2 |
请完成以下Java代码 | public EMail sendEMail(I_AD_User from, String toEmail, String subject, final BoilerPlateContext attributes)
{
final Mailbox mailbox = mailService.findMailbox(MailboxQuery.builder()
.clientId(getClientId())
.orgId(getOrgId())
.adProcessId(getProcessInfo().getAdProcessId())
.fromUserId(UserId.ofRepoId(from.getAD_User_ID()))
.build());
return mailService.sendEMail(EMailRequest.builder()
.mailbox(mailbox)
.toList(toEMailAddresses(toEmail))
.subject(text.getSubject())
.message(text.getTextSnippetParsed(attributes))
.html(true)
.build());
}
}); | }
private void notifyLetter(MADBoilerPlate text, MRGroupProspect prospect)
{
throw new UnsupportedOperationException();
}
private List<MRGroupProspect> getProspects(int R_Group_ID)
{
final String whereClause = MRGroupProspect.COLUMNNAME_R_Group_ID + "=?";
return new Query(getCtx(), MRGroupProspect.Table_Name, whereClause, get_TrxName())
.setParameters(R_Group_ID)
.list(MRGroupProspect.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\letters\report\AD_BoilderPlate_SendToGroup.java | 1 |
请完成以下Java代码 | public List<Object> getValuesOrNull()
{
return values;
}
private void buildSql()
{
if (sqlBuilt)
{
return;
}
if (values == null || values.isEmpty())
{
sqlWhereClause = defaultReturnWhenEmpty ? SQL_TRUE : SQL_FALSE;
sqlParams = ImmutableList.of();
}
else if (values.size() == 1)
{
final Object value = values.get(0);
if (value == null)
{
sqlWhereClause = columnName + " IS NULL";
sqlParams = ImmutableList.of();
}
else if (embedSqlParams)
{
sqlWhereClause = columnName + "=" + DB.TO_SQL(value);
sqlParams = ImmutableList.of();
}
else
{
sqlWhereClause = columnName + "=?";
sqlParams = ImmutableList.of(value);
}
}
else
{
final List<Object> sqlParamsBuilt = new ArrayList<>(values.size());
final StringBuilder sqlWhereClauseBuilt = new StringBuilder();
boolean hasNullValues = false;
boolean hasNonNullValues = false;
for (final Object value : values)
{
//
// Null Value - just set the flag, we need to add the where clause separately
if (value == null)
{
hasNullValues = true;
continue;
}
//
// Non Null Value
if (hasNonNullValues)
{ | sqlWhereClauseBuilt.append(",");
}
else
{
// First time we are adding a non-NULL value => we are adding "ColumnName IN (" first
sqlWhereClauseBuilt.append(columnName).append(" IN (");
}
if (embedSqlParams)
{
sqlWhereClauseBuilt.append(DB.TO_SQL(value));
}
else
{
sqlWhereClauseBuilt.append("?");
sqlParamsBuilt.add(value);
}
hasNonNullValues = true;
}
// Closing the bracket from "ColumnName IN (".
if (hasNonNullValues)
{
sqlWhereClauseBuilt.append(")");
}
// We have NULL and non-NULL values => we need to join the expressions with an OR
if (hasNonNullValues && hasNullValues)
{
sqlWhereClauseBuilt.append(" OR ");
}
// Add the IS NULL expression
if (hasNullValues)
{
sqlWhereClauseBuilt.append(columnName).append(" IS NULL");
}
// If we have both NULL and non-NULL values, we need to enclose the expression in brackets because of the "OR"
if (hasNonNullValues && hasNullValues)
{
sqlWhereClauseBuilt.insert(0, '(').append(')');
}
this.sqlWhereClause = sqlWhereClauseBuilt.toString();
this.sqlParams = sqlParamsBuilt;
}
sqlBuilt = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InArrayQueryFilter.java | 1 |
请完成以下Java代码 | public Date getLastAvailableTime() {
return lastAvailableTime;
}
@Override
public Date getLastUnavailableTime() {
return lastUnavailableTime;
}
@Override
public Date getLastEnabledTime() {
return lastEnabledTime;
}
@Override
public Date getLastDisabledTime() {
return lastDisabledTime;
}
@Override
public Date getLastStartedTime() {
return lastStartedTime;
}
@Override
public Date getLastSuspendedTime() {
return lastSuspendedTime;
}
@Override
public Date getCompletedTime() {
return completedTime;
}
@Override
public Date getOccurredTime() {
return occurredTime;
}
@Override
public Date getTerminatedTime() {
return terminatedTime;
}
@Override
public Date getExitTime() {
return exitTime;
}
@Override
public Date getEndedTime() {
return endedTime;
}
@Override
public String getStartUserId() {
return startUserId;
}
@Override
public String getAssignee() {
return assignee;
}
@Override
public String getCompletedBy() {
return completedBy;
}
@Override
public String getReferenceId() {
return referenceId;
}
@Override
public String getReferenceType() {
return referenceType;
}
@Override | public boolean isCompletable() {
return completable;
}
@Override
public String getEntryCriterionId() {
return entryCriterionId;
}
@Override
public String getExitCriterionId() {
return exitCriterionId;
}
@Override
public String getFormKey() {
return formKey;
}
@Override
public String getExtraValue() {
return extraValue;
}
@Override
public boolean hasVariable(String variableName) {
return variables.containsKey(variableName);
}
@Override
public Object getVariable(String variableName) {
return variables.get(variableName);
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public Set<String> getVariableNames() {
return variables.keySet();
}
@Override
public Map<String, Object> getPlanItemInstanceLocalVariables() {
return localVariables;
}
@Override
public PlanItem getPlanItem() {
return planItem;
}
@Override
public String toString() {
return new StringJoiner(", ", getClass().getSimpleName() + "[", "]")
.add("id='" + id + "'")
.add("planItemDefinitionId='" + planItemDefinitionId + "'")
.add("elementId='" + elementId + "'")
.add("caseInstanceId='" + caseInstanceId + "'")
.add("caseDefinitionId='" + caseDefinitionId + "'")
.add("tenantId='" + tenantId + "'")
.toString();
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\delegate\ReadOnlyDelegatePlanItemInstanceImpl.java | 1 |
请完成以下Java代码 | public <T> void beforeConcurrentHandling(NativeWebRequest request, Callable<T> task) {
if (this.securityContext == null) {
setSecurityContext(this.securityContextHolderStrategy.getContext());
}
}
@Override
public <T> void preProcess(NativeWebRequest request, Callable<T> task) {
if (this.securityContext != null) {
this.securityContextHolderStrategy.setContext(this.securityContext);
}
}
@Override
public <T> void postProcess(NativeWebRequest request, Callable<T> task, @Nullable Object concurrentResult) {
this.securityContextHolderStrategy.clearContext();
}
/** | * Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
private void setSecurityContext(SecurityContext securityContext) {
this.securityContext = securityContext;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\context\request\async\SecurityContextCallableProcessingInterceptor.java | 1 |
请完成以下Java代码 | public void setIsArchived (final boolean IsArchived)
{
set_Value (COLUMNNAME_IsArchived, IsArchived);
}
@Override
public boolean isArchived()
{
return get_ValueAsBoolean(COLUMNNAME_IsArchived);
}
@Override
public void setIsInitialCare (final boolean IsInitialCare)
{
set_Value (COLUMNNAME_IsInitialCare, IsInitialCare);
}
@Override
public boolean isInitialCare()
{
return get_ValueAsBoolean(COLUMNNAME_IsInitialCare);
}
@Override
public void setIsSeriesOrder (final boolean IsSeriesOrder)
{
set_Value (COLUMNNAME_IsSeriesOrder, IsSeriesOrder);
}
@Override
public boolean isSeriesOrder()
{
return get_ValueAsBoolean(COLUMNNAME_IsSeriesOrder);
}
@Override
public void setNextDelivery (final @Nullable java.sql.Timestamp NextDelivery)
{
set_Value (COLUMNNAME_NextDelivery, NextDelivery); | }
@Override
public java.sql.Timestamp getNextDelivery()
{
return get_ValueAsTimestamp(COLUMNNAME_NextDelivery);
}
@Override
public void setRootId (final @Nullable String RootId)
{
set_Value (COLUMNNAME_RootId, RootId);
}
@Override
public String getRootId()
{
return get_ValueAsString(COLUMNNAME_RootId);
}
@Override
public void setStartDate (final @Nullable java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
@Override
public java.sql.Timestamp getStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StartDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_Order.java | 1 |
请完成以下Java代码 | private void startProcessInstances(List<EventSubscriptionEntity> startSignalEventSubscriptions, Map<String, ProcessDefinitionEntity> processDefinitions) {
for (EventSubscriptionEntity signalStartEventSubscription : startSignalEventSubscriptions) {
ProcessDefinitionEntity processDefinition = processDefinitions.get(signalStartEventSubscription.getId());
if (processDefinition != null) {
ActivityImpl signalStartEvent = processDefinition.findActivity(signalStartEventSubscription.getActivityId());
PvmProcessInstance processInstance = processDefinition.createProcessInstanceForInitial(signalStartEvent);
processInstance.start(builder.getVariables());
}
}
}
protected List<EventSubscriptionEntity> filterIntermediateSubscriptions(List<EventSubscriptionEntity> subscriptions) {
List<EventSubscriptionEntity> result = new ArrayList<EventSubscriptionEntity>();
for (EventSubscriptionEntity subscription : subscriptions) {
if (subscription.getExecutionId() != null) {
result.add(subscription); | }
}
return result;
}
protected List<EventSubscriptionEntity> filterStartSubscriptions(List<EventSubscriptionEntity> subscriptions) {
List<EventSubscriptionEntity> result = new ArrayList<EventSubscriptionEntity>();
for (EventSubscriptionEntity subscription : subscriptions) {
if (subscription.getExecutionId() == null) {
result.add(subscription);
}
}
return result;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\SignalEventReceivedCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MigrationBatchConfiguration extends BatchConfiguration {
protected MigrationPlan migrationPlan;
protected boolean isSkipCustomListeners;
protected boolean isSkipIoMappings;
public MigrationBatchConfiguration(List<String> ids,
MigrationPlan migrationPlan,
boolean isSkipCustomListeners,
boolean isSkipIoMappings,
String batchId) {
this(ids, null, migrationPlan, isSkipCustomListeners, isSkipIoMappings, batchId);
}
public MigrationBatchConfiguration(List<String> ids,
DeploymentMappings mappings,
MigrationPlan migrationPlan,
boolean isSkipCustomListeners,
boolean isSkipIoMappings,
String batchId) {
super(ids, mappings);
this.migrationPlan = migrationPlan;
this.isSkipCustomListeners = isSkipCustomListeners;
this.isSkipIoMappings = isSkipIoMappings;
this.batchId = batchId;
}
public MigrationBatchConfiguration(List<String> ids,
DeploymentMappings mappings,
MigrationPlan migrationPlan,
boolean isSkipCustomListeners,
boolean isSkipIoMappings) {
this(ids, mappings, migrationPlan, isSkipCustomListeners, isSkipIoMappings, null);
} | public MigrationPlan getMigrationPlan() {
return migrationPlan;
}
public void setMigrationPlan(MigrationPlan migrationPlan) {
this.migrationPlan = migrationPlan;
}
public boolean isSkipCustomListeners() {
return isSkipCustomListeners;
}
public void setSkipCustomListeners(boolean isSkipCustomListeners) {
this.isSkipCustomListeners = isSkipCustomListeners;
}
public boolean isSkipIoMappings() {
return isSkipIoMappings;
}
public void setSkipIoMappings(boolean isSkipIoMappings) {
this.isSkipIoMappings = isSkipIoMappings;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\batch\MigrationBatchConfiguration.java | 2 |
请完成以下Spring Boot application配置 | server:
port: 8888
spring:
application:
name: demo-config-server
profiles:
active: git # 使用的 Spring Cloud Config Server 的存储器方案
# Spring Cloud Config 相关配置项
cloud:
config:
server:
# Spring Cloud Config Server 的 Git 存储器的配置项,对应 MultipleJGitEnvironmentProperties 类
git:
uri: https://github.com/YunaiV/demo-config-server.git # Git 仓库地址
search-paths: / # 读取文件的根地址
default-label: master # 使用的默认分支,默认为 master
# username: ${CODING_USERNAME} # 账号
# password: ${CODING_PASSWORD} # 密码
# Spring Clou | d Nacos Discovery 相关配置项
nacos:
# Nacos 作为注册中心的配置项,对应 NacosDiscoveryProperties 配置类
discovery:
server-addr: 127.0.0.1:8848 # Nacos 服务器地址
service: ${spring.application.name} # 注册到 Nacos 的服务名。默认值为 ${spring.application.name}。 | repos\SpringBoot-Labs-master\labx-12-spring-cloud-config\labx-12-sc-config-server-git-nacos\src\main\resources\application.yml | 2 |
请完成以下Java代码 | public class Lexicon
{
public BinTrie<Integer> wordId;
public List<String> idWord;
public Lexicon()
{
wordId = new BinTrie<Integer>();
idWord = new LinkedList<String>();
}
public Lexicon(BinTrie<Integer> wordIdTrie)
{
wordId = wordIdTrie;
}
public int addWord(String word)
{
assert word != null;
char[] charArray = word.toCharArray();
Integer id = wordId.get(charArray);
if (id == null)
{
id = wordId.size();
wordId.put(charArray, id);
idWord.add(word);
assert idWord.size() == wordId.size();
}
return id;
}
public Integer getId(String word)
{
return wordId.get(word);
}
public String getWord(int id)
{
assert 0 <= id;
assert id <= idWord.size();
return idWord.get(id); | }
public int size()
{
return idWord.size();
}
public String[] getWordIdArray()
{
String[] wordIdArray = new String[idWord.size()];
if (idWord.isEmpty()) return wordIdArray;
int p = -1;
Iterator<String> iterator = idWord.iterator();
while (iterator.hasNext())
{
wordIdArray[++p] = iterator.next();
}
return wordIdArray;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\Lexicon.java | 1 |
请完成以下Java代码 | public void setC_DataImport_ID (final int C_DataImport_ID)
{
if (C_DataImport_ID < 1)
set_Value (COLUMNNAME_C_DataImport_ID, null);
else
set_Value (COLUMNNAME_C_DataImport_ID, C_DataImport_ID);
}
@Override
public int getC_DataImport_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DataImport_ID);
}
@Override
public org.compiere.model.I_C_Location getC_Location()
{
return get_ValueAsPO(COLUMNNAME_C_Location_ID, org.compiere.model.I_C_Location.class);
}
@Override
public void setC_Location(final org.compiere.model.I_C_Location C_Location)
{
set_ValueFromPO(COLUMNNAME_C_Location_ID, org.compiere.model.I_C_Location.class, C_Location);
}
@Override
public void setC_Location_ID (final int C_Location_ID)
{
if (C_Location_ID < 1)
set_Value (COLUMNNAME_C_Location_ID, null);
else
set_Value (COLUMNNAME_C_Location_ID, C_Location_ID);
}
@Override
public int getC_Location_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Location_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setESR_PostBank (final boolean ESR_PostBank)
{
set_Value (COLUMNNAME_ESR_PostBank, ESR_PostBank);
}
@Override
public boolean isESR_PostBank()
{
return get_ValueAsBoolean(COLUMNNAME_ESR_PostBank);
}
@Override
public void setIsCashBank (final boolean IsCashBank)
{
set_Value (COLUMNNAME_IsCashBank, IsCashBank);
}
@Override
public boolean isCashBank()
{
return get_ValueAsBoolean(COLUMNNAME_IsCashBank);
}
@Override
public void setIsImportAsSingleSummaryLine (final boolean IsImportAsSingleSummaryLine)
{
set_Value (COLUMNNAME_IsImportAsSingleSummaryLine, IsImportAsSingleSummaryLine);
}
@Override
public boolean isImportAsSingleSummaryLine()
{
return get_ValueAsBoolean(COLUMNNAME_IsImportAsSingleSummaryLine);
}
@Override | public void setIsOwnBank (final boolean IsOwnBank)
{
set_Value (COLUMNNAME_IsOwnBank, IsOwnBank);
}
@Override
public boolean isOwnBank()
{
return get_ValueAsBoolean(COLUMNNAME_IsOwnBank);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setRoutingNo (final java.lang.String RoutingNo)
{
set_Value (COLUMNNAME_RoutingNo, RoutingNo);
}
@Override
public java.lang.String getRoutingNo()
{
return get_ValueAsString(COLUMNNAME_RoutingNo);
}
@Override
public void setSwiftCode (final @Nullable java.lang.String SwiftCode)
{
set_Value (COLUMNNAME_SwiftCode, SwiftCode);
}
@Override
public java.lang.String getSwiftCode()
{
return get_ValueAsString(COLUMNNAME_SwiftCode);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Bank.java | 1 |
请完成以下Java代码 | protected HistoricCaseInstanceEntityManager getHistoricCaseInstanceEntityManager() {
return cmmnEngineConfiguration.getHistoricCaseInstanceEntityManager();
}
protected HistoricMilestoneInstanceEntityManager getHistoricMilestoneInstanceEntityManager() {
return cmmnEngineConfiguration.getHistoricMilestoneInstanceEntityManager();
}
protected HistoricPlanItemInstanceEntityManager getHistoricPlanItemInstanceEntityManager() {
return cmmnEngineConfiguration.getHistoricPlanItemInstanceEntityManager();
}
protected VariableInstanceEntityManager getVariableInstanceEntityManager() {
return cmmnEngineConfiguration.getVariableServiceConfiguration().getVariableInstanceEntityManager();
}
protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() {
return cmmnEngineConfiguration.getVariableServiceConfiguration().getHistoricVariableInstanceEntityManager();
}
protected IdentityLinkEntityManager getIdentityLinkEntityManager() {
return cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkEntityManager();
}
protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getHistoricIdentityLinkEntityManager();
}
protected EntityLinkEntityManager getEntityLinkEntityManager() {
return cmmnEngineConfiguration.getEntityLinkServiceConfiguration().getEntityLinkEntityManager(); | }
protected HistoricEntityLinkEntityManager getHistoricEntityLinkEntityManager() {
return cmmnEngineConfiguration.getEntityLinkServiceConfiguration().getHistoricEntityLinkEntityManager();
}
protected TaskEntityManager getTaskEntityManager() {
return cmmnEngineConfiguration.getTaskServiceConfiguration().getTaskEntityManager();
}
protected HistoricTaskLogEntryEntityManager getHistoricTaskLogEntryEntityManager() {
return cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskLogEntryEntityManager();
}
protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() {
return cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskInstanceEntityManager();
}
protected CmmnEngineConfiguration getCmmnEngineConfiguration() {
return cmmnEngineConfiguration;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\AbstractCmmnManager.java | 1 |
请完成以下Spring Boot application配置 | spring:
boot:
admin:
ui:
cache:
no-cache: true
template-location: file:../../spring-boot-admin-server-ui/target/dist/
resource-locations: file:../../spring-boot-admin-server-ui/target/dist/
cache-t | emplates: false
extension-resource-locations: file:../spring-boot-admin-sample-custom-ui/target/dist/ | repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-servlet\src\main\resources\application-dev.yml | 2 |
请完成以下Java代码 | public void setQtyIssued (java.math.BigDecimal QtyIssued)
{
set_Value (COLUMNNAME_QtyIssued, QtyIssued);
}
/** Get Ausgelagerte Menge.
@return Ausgelagerte Menge */
@Override
public java.math.BigDecimal getQtyIssued ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyIssued);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Empfangene Menge.
@param QtyReceived Empfangene Menge */
@Override
public void setQtyReceived (java.math.BigDecimal QtyReceived) | {
set_Value (COLUMNNAME_QtyReceived, QtyReceived);
}
/** Get Empfangene Menge.
@return Empfangene Menge */
@Override
public java.math.BigDecimal getQtyReceived ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyReceived);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java-gen\de\metas\materialtracking\ch\lagerkonf\model\X_M_Material_Tracking_Report_Line.java | 1 |
请完成以下Java代码 | public class JsonHUAttributeConverters
{
@NonNull
public static Object toDisplayValue(@Nullable final Object value, @NonNull final String adLanguage)
{
if (value == null)
{
return "";
}
else if (value instanceof java.sql.Timestamp)
{
final LocalDateTime dateTime = ((Timestamp)value).toLocalDateTime();
return toDisplayValue_fromLocalDateTime(dateTime, adLanguage);
}
else if (value instanceof LocalDateTime)
{
return toDisplayValue_fromLocalDateTime((LocalDateTime)value, adLanguage);
}
else if (value instanceof LocalDate)
{
return toDisplayValue_fromLocalDate((LocalDate)value, adLanguage);
}
else if (value instanceof BigDecimal)
{
return TranslatableStrings.number((BigDecimal)value, DisplayType.Number).translate(adLanguage);
}
else
{
return CoalesceUtil.coalesceNotNull(JsonHUAttribute.convertValueToJson(value), "");
} | }
private static String toDisplayValue_fromLocalDateTime(@NonNull final LocalDateTime value, @NonNull final String adLanguage)
{
final LocalDate date = value.toLocalDate();
if (value.equals(date.atStartOfDay()))
{
return toDisplayValue_fromLocalDate(date, adLanguage);
}
else
{
return TranslatableStrings.dateAndTime(value).translate(adLanguage);
}
}
private static String toDisplayValue_fromLocalDate(@NonNull final LocalDate value, @NonNull final String adLanguage)
{
return TranslatableStrings.date(value).translate(adLanguage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.mobileui\src\main\java\de\metas\handlingunits\rest_api\JsonHUAttributeConverters.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static List toList() {
NotifyStatusEnum[] ary = NotifyStatusEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("desc", ary[i].getDesc());
list.add(map);
}
return list;
}
public static NotifyStatusEnum getEnum(String name) {
NotifyStatusEnum[] arry = NotifyStatusEnum.values();
for (int i = 0; i < arry.length; i++) {
if (arry[i].name().equalsIgnoreCase(name)) {
return arry[i];
}
}
return null;
}
/** | * 取枚举的json字符串
*
* @return
*/
public static String getJsonStr() {
NotifyStatusEnum[] enums = NotifyStatusEnum.values();
StringBuffer jsonStr = new StringBuffer("[");
for (NotifyStatusEnum senum : enums) {
if (!"[".equals(jsonStr.toString())) {
jsonStr.append(",");
}
jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}");
}
jsonStr.append("]");
return jsonStr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\enums\NotifyStatusEnum.java | 2 |
请完成以下Java代码 | protected void configureExternallyManagedTransactions() {
if (processEngineConfiguration instanceof SpringProcessEngineConfiguration) { // remark:
// any
// config
// can
// be
// injected,
// so
// we
// cannot
// have
// SpringConfiguration
// as
// member
SpringProcessEngineConfiguration engineConfiguration = (SpringProcessEngineConfiguration) processEngineConfiguration;
if (engineConfiguration.getTransactionManager() != null) {
processEngineConfiguration.setTransactionsExternallyManaged(true);
}
}
}
@Override | public Class<ProcessEngine> getObjectType() {
return ProcessEngine.class;
}
@Override
public boolean isSingleton() {
return true;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
} | repos\flowable-engine-main\modules\flowable5-spring\src\main\java\org\activiti\spring\ProcessEngineFactoryBean.java | 1 |
请完成以下Java代码 | public ProcessDialogBuilder setFromGridTab(GridTab gridTab)
{
final int windowNo = gridTab.getWindowNo();
final int tabNo = gridTab.getTabNo();
setWindowAndTabNo(windowNo, tabNo);
setAdWindowId(gridTab.getAdWindowId());
setIsSOTrx(Env.isSOTrx(gridTab.getCtx(), windowNo));
setTableAndRecord(gridTab.getAD_Table_ID(), gridTab.getRecord_ID());
setWhereClause(gridTab.getTableModel().getSelectWhereClauseFinal());
skipResultsPanel();
return this;
}
public ProcessDialogBuilder setProcessExecutionListener(final IProcessExecutionListener processExecutionListener)
{
this.processExecutionListener = processExecutionListener;
return this;
} | IProcessExecutionListener getProcessExecutionListener()
{
return processExecutionListener;
}
public ProcessDialogBuilder setPrintPreview(final boolean printPreview)
{
this._printPreview = printPreview;
return this;
}
boolean isPrintPreview()
{
if (_printPreview != null)
{
return _printPreview;
}
return Ini.isPropertyBool(Ini.P_PRINTPREVIEW);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessDialogBuilder.java | 1 |
请完成以下Java代码 | public static BigDecimal multiply(Object a, Object b) {
BigDecimal bdA = toBigDecimal(a);
BigDecimal bdB = toBigDecimal(b);
return bdA.multiply(bdB).setScale(2, RoundingMode.HALF_UP);
}
/**
* 除法
* @param a 被除数
* @param b 除数
* @return 两数的商,保留两位小数
*/
public static BigDecimal divide(Object a, Object b) {
BigDecimal bdA = toBigDecimal(a);
BigDecimal bdB = toBigDecimal(b);
return bdA.divide(bdB, 2, RoundingMode.HALF_UP);
}
/**
* 除法
* @param a 被除数
* @param b 除数
* @param scale 保留小数位数
* @return 两数的商,保留两位小数
*/
public static BigDecimal divide(Object a, Object b, int scale) {
BigDecimal bdA = toBigDecimal(a);
BigDecimal bdB = toBigDecimal(b);
return bdA.divide(bdB, scale, RoundingMode.HALF_UP);
}
/**
* 分转元
* @param obj 分的金额
* @return 转换后的元,保留两位小数
*/
public static BigDecimal centsToYuan(Object obj) {
BigDecimal cents = toBigDecimal(obj);
return cents.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
}
/**
* 元转分
* @param obj 元的金额
* @return 转换后的分
*/ | public static Long yuanToCents(Object obj) {
BigDecimal yuan = toBigDecimal(obj);
return yuan.multiply(BigDecimal.valueOf(100)).setScale(0, RoundingMode.HALF_UP).longValue();
}
public static void main(String[] args) {
BigDecimal num1 = new BigDecimal("10.123");
BigDecimal num2 = new BigDecimal("2.456");
System.out.println("加法结果: " + add(num1, num2));
System.out.println("减法结果: " + subtract(num1, num2));
System.out.println("乘法结果: " + multiply(num1, num2));
System.out.println("除法结果: " + divide(num1, num2));
Long cents = 12345L;
System.out.println("分转元结果: " + centsToYuan(cents));
BigDecimal yuan = new BigDecimal("123.45");
System.out.println("元转分结果: " + yuanToCents(yuan));
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\BigDecimalUtils.java | 1 |
请完成以下Java代码 | public <T> List<T> retrieveModelsByIds(final DocumentIdsSelection rowIds, final Class<T> modelClass)
{
throw new UnsupportedOperationException();
}
@Override
public Stream<? extends IViewRow> streamByIds(final DocumentIdsSelection rowIds)
{
return rows.streamByIds(rowIds);
}
@Override
public void notifyRecordsChanged(
@NonNull final TableRecordReferenceSet recordRefs,
final boolean watchedByFrontend)
{
// TODO Auto-generated method stub
}
@Override
public List<RelatedProcessDescriptor> getAdditionalRelatedProcessDescriptors()
{ | return additionalRelatedProcessDescriptors;
}
/**
* @return the {@code M_ShipmentSchedule_ID} of the packageable line that is currently selected within the {@link PackageableView}.
*/
@NonNull
public ShipmentScheduleId getCurrentShipmentScheduleId()
{
return currentShipmentScheduleId;
}
@Override
public void invalidateAll()
{
rows.invalidateAll();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickingSlotView.java | 1 |
请完成以下Java代码 | public TaskListener createDelegateExpressionTaskListener(FlowableListener listener) {
return new DelegateExpressionTaskListener(expressionManager.createExpression(listener.getImplementation()), listener.getFieldExtensions());
}
@Override
public TaskListener createScriptTypeTaskListener(FlowableListener listener) {
ScriptInfo scriptInfo = listener.getScriptInfo();
if (scriptInfo == null) {
throw new FlowableIllegalStateException("Cannot create 'script' task listener. Missing ScriptInfo.");
}
ScriptTypeTaskListener scriptListener = new ScriptTypeTaskListener(createExpression(listener.getScriptInfo().getLanguage()),
createExpression(listener.getScriptInfo().getScript()));
Optional.ofNullable(listener.getScriptInfo().getResultVariable())
.ifPresent(resultVar -> scriptListener.setResultVariable(createExpression(resultVar)));
return scriptListener;
}
protected Expression createExpression(Object value) {
return value instanceof String ? expressionManager.createExpression((String) value) : new FixedValue(value);
}
@Override
public PlanItemInstanceLifecycleListener createClassDelegateLifeCycleListener(FlowableListener listener) {
return classDelegateFactory.create(listener.getImplementation(), listener.getFieldExtensions());
}
@Override
public PlanItemInstanceLifecycleListener createExpressionLifeCycleListener(FlowableListener listener) {
return new ExpressionPlanItemLifecycleListener(listener.getSourceState(), listener.getTargetState(),
expressionManager.createExpression(listener.getImplementation()));
}
@Override | public PlanItemInstanceLifecycleListener createDelegateExpressionLifeCycleListener(FlowableListener listener) {
return new DelegateExpressionPlanItemLifecycleListener(listener.getSourceState(), listener.getTargetState(),
expressionManager.createExpression(listener.getImplementation()), listener.getFieldExtensions());
}
@Override
public CaseInstanceLifecycleListener createClassDelegateCaseLifeCycleListener(FlowableListener listener) {
return classDelegateFactory.create(listener.getImplementation(), listener.getFieldExtensions());
}
@Override
public CaseInstanceLifecycleListener createExpressionCaseLifeCycleListener(FlowableListener listener) {
return new ExpressionCaseLifecycleListener(listener.getSourceState(), listener.getTargetState(), expressionManager.createExpression(listener.getImplementation()));
}
@Override
public CaseInstanceLifecycleListener createDelegateExpressionCaseLifeCycleListener(FlowableListener listener) {
return new DelegateExpressionCaseLifecycleListener(listener.getSourceState(), listener.getTargetState(),
expressionManager.createExpression(listener.getImplementation()), listener.getFieldExtensions());
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\listener\DefaultCmmnListenerFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static List<AuthenticationProvider> createDefaultAuthenticationProviders(HttpSecurity httpSecurity) {
List<AuthenticationProvider> authenticationProviders = new ArrayList<>();
OAuth2AuthorizationService authorizationService = OAuth2ConfigurerUtils.getAuthorizationService(httpSecurity);
OAuth2TokenGenerator<? extends OAuth2Token> tokenGenerator = OAuth2ConfigurerUtils
.getTokenGenerator(httpSecurity);
OAuth2AuthorizationCodeAuthenticationProvider authorizationCodeAuthenticationProvider = new OAuth2AuthorizationCodeAuthenticationProvider(
authorizationService, tokenGenerator);
SessionRegistry sessionRegistry = httpSecurity.getSharedObject(SessionRegistry.class);
if (sessionRegistry != null) {
authorizationCodeAuthenticationProvider.setSessionRegistry(sessionRegistry);
}
authenticationProviders.add(authorizationCodeAuthenticationProvider);
OAuth2RefreshTokenAuthenticationProvider refreshTokenAuthenticationProvider = new OAuth2RefreshTokenAuthenticationProvider(
authorizationService, tokenGenerator); | authenticationProviders.add(refreshTokenAuthenticationProvider);
OAuth2ClientCredentialsAuthenticationProvider clientCredentialsAuthenticationProvider = new OAuth2ClientCredentialsAuthenticationProvider(
authorizationService, tokenGenerator);
authenticationProviders.add(clientCredentialsAuthenticationProvider);
OAuth2DeviceCodeAuthenticationProvider deviceCodeAuthenticationProvider = new OAuth2DeviceCodeAuthenticationProvider(
authorizationService, tokenGenerator);
authenticationProviders.add(deviceCodeAuthenticationProvider);
OAuth2TokenExchangeAuthenticationProvider tokenExchangeAuthenticationProvider = new OAuth2TokenExchangeAuthenticationProvider(
authorizationService, tokenGenerator);
authenticationProviders.add(tokenExchangeAuthenticationProvider);
return authenticationProviders;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OAuth2TokenEndpointConfigurer.java | 2 |
请完成以下Java代码 | public void onPP_Order_Node_ID(final I_PP_Cost_Collector cc)
{
final PPOrderId orderId = PPOrderId.ofRepoIdOrNull(cc.getPP_Order_ID());
if (orderId == null)
{
return;
}
final PPOrderRoutingActivityId orderRoutingActivityId = PPOrderRoutingActivityId.ofRepoIdOrNull(orderId, cc.getPP_Order_Node_ID());
if (orderRoutingActivityId == null)
{
return;
}
final PPOrderRoutingActivity orderActivity = orderRoutingRepository.getOrderRoutingActivity(orderRoutingActivityId);
cc.setS_Resource_ID(orderActivity.getResourceId().getRepoId());
cc.setIsSubcontracting(orderActivity.isSubcontracting());
final Quantity qtyToDeliver = orderActivity.getQtyToDeliver();
costCollectorBL.setQuantities(cc, PPCostCollectorQuantities.ofMovementQty(qtyToDeliver));
updateDurationReal(cc); // shall be automatically triggered
}
@CalloutMethod(columnNames = I_PP_Cost_Collector.COLUMNNAME_MovementQty)
public void onMovementQty(final I_PP_Cost_Collector cc)
{
updateDurationReal(cc);
}
/**
* Calculates and sets DurationReal based on selected PP_Order_Node
*/
private void updateDurationReal(final I_PP_Cost_Collector cc)
{
final WorkingTime durationReal = computeWorkingTime(cc);
if (durationReal == null)
{
return;
}
cc.setDurationReal(durationReal.toBigDecimalUsingActivityTimeUnit());
} | @Nullable
private WorkingTime computeWorkingTime(final I_PP_Cost_Collector cc)
{
final PPOrderId orderId = PPOrderId.ofRepoIdOrNull(cc.getPP_Order_ID());
if (orderId == null)
{
return null;
}
final PPOrderRoutingActivityId activityId = PPOrderRoutingActivityId.ofRepoIdOrNull(orderId, cc.getPP_Order_Node_ID());
if (activityId == null)
{
return null;
}
final PPOrderRoutingActivity activity = orderRoutingRepository.getOrderRoutingActivity(activityId);
return WorkingTime.builder()
.durationPerOneUnit(activity.getDurationPerOneUnit())
.unitsPerCycle(activity.getUnitsPerCycle())
.qty(costCollectorBL.getMovementQty(cc))
.activityTimeUnit(activity.getDurationUnit())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\callout\PP_Cost_Collector.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static class SqlWithParams
{
@NonNull
String sql;
@NonNull
ImmutableList<Object> sqlParams;
@VisibleForTesting
static SqlWithParams createEmpty()
{
return new SqlWithParams("", ImmutableList.of());
}
@VisibleForTesting
SqlWithParams add(@NonNull final SqlWithParams sqlWithParams)
{
StringBuilder completeSQL = new StringBuilder(sql);
ImmutableList.Builder<Object> completeParams = ImmutableList.builder().addAll(sqlParams);
final boolean firstSQL = completeSQL.length() == 0;
if (!firstSQL) | {
completeSQL.append(" UNION\n");
}
completeSQL.append(sqlWithParams.getSql());
completeSQL.append("\n");
completeParams.addAll(sqlWithParams.getSqlParams());
return new SqlWithParams(completeSQL.toString(), completeParams.build());
}
@VisibleForTesting
SqlWithParams withFinalOrderByClause(@NonNull final String orderBy)
{
final StringBuilder completeSQL = new StringBuilder(sql).append(orderBy);
return new SqlWithParams(completeSQL.toString(), sqlParams);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\RecordChangeLogEntryLoader.java | 2 |
请完成以下Java代码 | public void init() {
this.toTbCore = tbQueueProvider.createTbCoreMsgProducer();
this.toRuleEngine = tbQueueProvider.createRuleEngineMsgProducer();
this.toUsageStats = tbQueueProvider.createToUsageStatsServiceMsgProducer();
this.toTbCoreNotifications = tbQueueProvider.createTbCoreNotificationsMsgProducer();
this.toHousekeeper = tbQueueProvider.createHousekeeperMsgProducer();
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToTransportMsg>> getTransportNotificationsMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToRuleEngineMsg>> getRuleEngineMsgProducer() {
return toRuleEngine;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToCoreMsg>> getTbCoreMsgProducer() {
return toTbCore;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToRuleEngineNotificationMsg>> getRuleEngineNotificationsMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToCoreNotificationMsg>> getTbCoreNotificationsMsgProducer() {
return toTbCoreNotifications;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeMsg>> getTbEdgeMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeNotificationMsg>> getTbEdgeNotificationsMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
} | @Override
public TbQueueProducer<TbProtoQueueMsg<ToEdgeEventNotificationMsg>> getTbEdgeEventsMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToVersionControlServiceMsg>> getTbVersionControlMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToUsageStatsServiceMsg>> getTbUsageStatsMsgProducer() {
return toUsageStats;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<ToHousekeeperServiceMsg>> getHousekeeperMsgProducer() {
return toHousekeeper;
}
@Override
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldMsg>> getCalculatedFieldsMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
@Override
public TbQueueProducer<TbProtoQueueMsg<TransportProtos.ToCalculatedFieldNotificationMsg>> getCalculatedFieldsNotificationsMsgProducer() {
throw new RuntimeException("Not Implemented! Should not be used by Transport!");
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\provider\TbTransportQueueProducerProvider.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class BookstoreService {
private final AuthorRepository authorRepository;
public BookstoreService(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
public void fetchWithDuplicates() {
System.out.println("\nFetching authors with duplicates ...");
List<Author> authors = authorRepository.fetchWithDuplicates();
authors.forEach(a -> {
System.out.println("Id: " + a.getId() + ": Name: " + a.getName() + " Books: " + a.getBooks());
});
}
public void fetchWithoutHint() {
System.out.println("\nFetching authors without HINT_PASS_DISTINCT_THROUGH hint ...");
List<Author> authors = authorRepository.fetchWithoutHint(); | authors.forEach(a -> {
System.out.println("Id: " + a.getId() + ": Name: " + a.getName() + " Books: " + a.getBooks());
});
}
public void fetchWithHint() {
System.out.println("\nFetching authors with HINT_PASS_DISTINCT_THROUGH hint ...");
List<Author> authors = authorRepository.fetchWithHint();
authors.forEach(a -> {
System.out.println("Id: " + a.getId() + ": Name: " + a.getName() + " Books: " + a.getBooks());
});
}
} | repos\Hibernate-SpringBoot-master\HibernateSpringBootHintPassDistinctThrough\src\main\java\com\bookstore\service\BookstoreService.java | 2 |
请完成以下Java代码 | private static void infoOfLiveProcesses() {
Stream<ProcessHandle> liveProcesses = ProcessHandle.allProcesses();
liveProcesses.filter(ProcessHandle::isAlive)
.forEach(ph -> {
log.info("PID: " + ph.pid());
log.info("Instance: " + ph.info().startInstant());
log.info("User: " + ph.info().user());
});
}
private static void infoOfChildProcess() throws IOException {
int childProcessCount = 5;
for (int i = 0; i < childProcessCount; i++) {
String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
processBuilder.inheritIO().start();
}
Stream<ProcessHandle> children = ProcessHandle.current()
.children();
children.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
Stream<ProcessHandle> descendants = ProcessHandle.current()
.descendants();
descendants.filter(ProcessHandle::isAlive)
.forEach(ph -> log.info("PID: {}, Cmd: {}", ph.pid(), ph.info()
.command()));
}
private static void infoOfExitCallback() throws IOException, InterruptedException, ExecutionException { | String javaCmd = ProcessUtils.getJavaCmd()
.getAbsolutePath();
ProcessBuilder processBuilder
= new ProcessBuilder(javaCmd, "-version");
Process process = processBuilder.inheritIO()
.start();
ProcessHandle processHandle = process.toHandle();
log.info("PID: {} has started", processHandle.pid());
CompletableFuture<ProcessHandle> onProcessExit = processHandle.onExit();
onProcessExit.get();
log.info("Alive: " + processHandle.isAlive());
onProcessExit.thenAccept(ph -> {
log.info("PID: {} has stopped", ph.pid());
});
}
} | repos\tutorials-master\core-java-modules\core-java-os-2\src\main\java\com\baeldung\java9\process\ProcessAPIEnhancements.java | 1 |
请完成以下Java代码 | public boolean isInt()
{
return false;
}
@Override
public int toInt()
{
if (isComposedKey())
{
throw new AdempiereException("Composed keys cannot be converted to int: " + this);
}
else
{
throw new AdempiereException("String document IDs cannot be converted to int: " + this);
}
}
@Override
public boolean isNew()
{
return false;
} | @Override
public boolean isComposedKey()
{
return idStr.contains(COMPOSED_KEY_SEPARATOR);
}
@Override
public List<Object> toComposedKeyParts()
{
final ImmutableList.Builder<Object> composedKeyParts = ImmutableList.builder();
COMPOSED_KEY_SPLITTER.split(idStr).forEach(composedKeyParts::add);
return composedKeyParts.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentId.java | 1 |
请完成以下Java代码 | public abstract class BroadcastingGuessGame implements NotificationBroadcaster, GuessGameMBean {
private final NotificationBroadcasterSupport broadcaster =
new NotificationBroadcasterSupport();
private long notificationSequence = 0;
private final MBeanNotificationInfo[] notificationInfo;
protected BroadcastingGuessGame() {
this.notificationInfo = new MBeanNotificationInfo[]{
new MBeanNotificationInfo(new String[]{"game"}, Notification.class.getName(), "Game notification")
};
}
protected void notifyAboutWinner(Player winner) {
String message = "Winner is " + winner.getName() + " with score " + winner.getScore();
Notification notification = new Notification("game.winner", this, notificationSequence++, message); | broadcaster.sendNotification(notification);
}
public void addNotificationListener(NotificationListener listener, NotificationFilter filter, Object handback) {
broadcaster.addNotificationListener(listener, filter, handback);
}
public void removeNotificationListener(NotificationListener listener) throws ListenerNotFoundException {
broadcaster.removeNotificationListener(listener);
}
public MBeanNotificationInfo[] getNotificationInfo() {
return notificationInfo;
}
} | repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\jmxterm\BroadcastingGuessGame.java | 1 |
请完成以下Java代码 | public static void downloadFile(HttpServletRequest request, HttpServletResponse response, File file, boolean deleteOnExit) {
response.setCharacterEncoding(request.getCharacterEncoding());
response.setContentType("application/octet-stream");
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
IOUtils.copy(fis, response.getOutputStream());
response.flushBuffer();
} catch (Exception e) {
log.error(e.getMessage(), e);
} finally {
if (fis != null) {
try {
fis.close();
if (deleteOnExit) {
file.deleteOnExit();
}
} catch (IOException e) {
log.error(e.getMessage(), e);
}
}
}
}
/**
* 验证并过滤非法的文件名
* @param fileName 文件名
* @return 文件名
*/
public static String verifyFilename(String fileName) {
// 过滤掉特殊字符
fileName = fileName.replaceAll("[\\\\/:*?\"<>|~\\s]", "");
// 去掉文件名开头和结尾的空格和点
fileName = fileName.trim().replaceAll("^[. ]+|[. ]+$", "");
// 不允许文件名超过255(在Mac和Linux中)或260(在Windows中)个字符
int maxFileNameLength = 255;
if (System.getProperty("os.name").startsWith("Windows")) { | maxFileNameLength = 260;
}
if (fileName.length() > maxFileNameLength) {
fileName = fileName.substring(0, maxFileNameLength);
}
// 过滤掉控制字符
fileName = fileName.replaceAll("[\\p{Cntrl}]", "");
// 过滤掉 ".." 路径
fileName = fileName.replaceAll("\\.{2,}", "");
// 去掉文件名开头的 ".."
fileName = fileName.replaceAll("^\\.+/", "");
// 保留文件名中最后一个 "." 字符,过滤掉其他 "."
fileName = fileName.replaceAll("^(.*)(\\.[^.]*)$", "$1").replaceAll("\\.", "") +
fileName.replaceAll("^(.*)(\\.[^.]*)$", "$2");
return fileName;
}
public static String getMd5(File file) {
return getMd5(getByte(file));
}
} | repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\utils\FileUtil.java | 1 |
请完成以下Java代码 | public IncidentQuery orderByConfiguration() {
orderBy(IncidentQueryProperty.CONFIGURATION);
return this;
}
public IncidentQuery orderByTenantId() {
return orderBy(IncidentQueryProperty.TENANT_ID);
}
@Override
public IncidentQuery orderByIncidentMessage() {
return orderBy(IncidentQueryProperty.INCIDENT_MESSAGE);
}
//results ////////////////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk(); | return commandContext
.getIncidentManager()
.findIncidentCountByQueryCriteria(this);
}
@Override
public List<Incident> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext
.getIncidentManager()
.findIncidentByQueryCriteria(this, page);
}
public String[] getProcessDefinitionKeys() {
return processDefinitionKeys;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\IncidentQueryImpl.java | 1 |
请完成以下Java代码 | public String getDeploymentId() {
return deploymentId;
}
@Override
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
@Override
public String getEditorSourceValueId() {
return editorSourceValueId;
}
@Override
public void setEditorSourceValueId(String editorSourceValueId) {
this.editorSourceValueId = editorSourceValueId;
}
@Override
public String getEditorSourceExtraValueId() {
return editorSourceExtraValueId;
}
@Override
public void setEditorSourceExtraValueId(String editorSourceExtraValueId) {
this.editorSourceExtraValueId = editorSourceExtraValueId;
}
@Override
public String getTenantId() {
return tenantId;
} | @Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public boolean hasEditorSource() {
return this.editorSourceValueId != null;
}
@Override
public boolean hasEditorSourceExtra() {
return this.editorSourceExtraValueId != null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ModelEntityImpl.java | 1 |
请完成以下Java代码 | public IStorageQuery addAttributes(@NonNull final IAttributeSet attributeSet)
{
for (final I_M_Attribute attribute : attributeSet.getAttributes())
{
// Skip attributes which were newly generated just to have an complete attribute set,
// because it makes no sense to filter by those and because it could be that we will get no result.
// Case: ASIAttributeStorge is generating new AIs for those attributes which are defined in M_HU_PI_Attribute but which were missing in given ASI.
// If we would filter by those too, it's a big chance that we would get no result.
if (attributeSet.isNew(attribute))
{
continue;
}
final Object value = attributeSet.getValue(attribute);
final String attributeValueType = attributeSet.getAttributeValueType(attribute);
addAttribute(attribute, attributeValueType, value);
}
return this;
}
private Set<AttributeId> getAvailableAttributeIds()
{
if (_availableAttributeIds == null)
{
final IHUStorageBL huStorageBL = Services.get(IHUStorageBL.class);
_availableAttributeIds = ImmutableSet.copyOf(huStorageBL.getAvailableAttributeIds());
}
return _availableAttributeIds;
} | @Override
public IStorageQuery setExcludeAfterPickingLocator(final boolean excludeAfterPickingLocator)
{
huQueryBuilder.setExcludeAfterPickingLocator(excludeAfterPickingLocator);
return this;
}
@Override
public IStorageQuery setExcludeReservedToOtherThan(@NonNull final OrderLineId orderLineId)
{
huQueryBuilder.setExcludeReservedToOtherThan(HUReservationDocRef.ofSalesOrderLineId(orderLineId));
return this;
}
@Override
public IStorageQuery setExcludeReserved()
{
huQueryBuilder.setExcludeReserved();
return this;
}
@Override
public IStorageQuery setOnlyActiveHUs(final boolean onlyActiveHUs)
{
huQueryBuilder.setOnlyActiveHUs(onlyActiveHUs);
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\storage\spi\hu\impl\HUStorageQuery.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static void assertValid(
final PricingConditionsId pricingConditionsId,
final PricingConditionsBreak forcePricingConditionsBreak,
final PricingConditionsBreakQuery pricingConditionsBreakQuery)
{
if (forcePricingConditionsBreak == null && pricingConditionsBreakQuery == null)
{
// TODO support PricingConditions that are not backed by discount schema breaks
throw new AdempiereException("forcePricingConditionsBreak or pricingConditionsBreakQuery shall be specified");
}
else if (forcePricingConditionsBreak != null && pricingConditionsBreakQuery != null)
{
throw new AdempiereException("Only forcePricingConditionsBreak or pricingConditionsBreakQuery shall be specified but not both");
}
if (forcePricingConditionsBreak != null && pricingConditionsId != null)
{
PricingConditionsBreakId.assertMatching(pricingConditionsId, forcePricingConditionsBreak.getId());
}
}
private static final PricingConditionsId extractPricingConditionsIdOrNull(
@Nullable final PricingConditionsId pricingConditionsId,
@Nullable final PricingConditionsBreak forcePricingConditionsBreak)
{
// note that in case both are given, we already asserted that they match
if (pricingConditionsId != null)
{ | return pricingConditionsId;
}
else if (forcePricingConditionsBreak != null)
{
final PricingConditionsBreakId pricingConditionsBreakId = forcePricingConditionsBreak.getId();
if (pricingConditionsBreakId != null)
{
return pricingConditionsBreakId.getPricingConditionsId();
}
else
{
return null; // pricing conditions ID not available but OK
}
}
else
{
throw new AdempiereException("Cannot extract " + PricingConditionsId.class);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\conditions\service\CalculatePricingConditionsRequest.java | 2 |
请完成以下Java代码 | public boolean isWithoutTenantId() {
return withoutTenantId;
}
public String getName() {
return name;
}
public String getNameLike() {
return nameLike;
}
public void setName(String name) {
this.name = name;
}
public void setNameLike(String nameLike) {
this.nameLike = nameLike;
}
public String getExecutionId() {
return executionId;
}
public String getDeploymentId() {
return deploymentId;
}
public List<String> getDeploymentIds() {
return deploymentIds;
}
public boolean isIncludeProcessVariables() {
return includeProcessVariables;
}
public boolean iswithException() {
return withJobException;
}
public String getNameLikeIgnoreCase() {
return nameLikeIgnoreCase;
}
public List<ProcessInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
/**
* Methods needed for ibatis because of re-use of query-xml for executions. ExecutionQuery contains a parentId property.
*/
public String getParentId() {
return null;
}
public boolean isOnlyChildExecutions() {
return onlyChildExecutions;
}
public boolean isOnlyProcessInstanceExecutions() {
return onlyProcessInstanceExecutions;
} | public boolean isOnlySubProcessExecutions() {
return onlySubProcessExecutions;
}
public Date getStartedBefore() {
return startedBefore;
}
public void setStartedBefore(Date startedBefore) {
this.startedBefore = startedBefore;
}
public Date getStartedAfter() {
return startedAfter;
}
public void setStartedAfter(Date startedAfter) {
this.startedAfter = startedAfter;
}
public String getStartedBy() {
return startedBy;
}
public void setStartedBy(String startedBy) {
this.startedBy = startedBy;
}
public List<String> getInvolvedGroups() {
return involvedGroups;
}
public ProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) {
if (involvedGroups == null || involvedGroups.isEmpty()) {
throw new ActivitiIllegalArgumentException("Involved groups list is null or empty.");
}
if (inOrStatement) {
this.currentOrQueryObject.involvedGroups = involvedGroups;
} else {
this.involvedGroups = involvedGroups;
}
return this;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceQueryImpl.java | 1 |
请完成以下Java代码 | public void setIMP_RequestHandler_ID (int IMP_RequestHandler_ID)
{
if (IMP_RequestHandler_ID < 1)
set_ValueNoCheck (COLUMNNAME_IMP_RequestHandler_ID, null);
else
set_ValueNoCheck (COLUMNNAME_IMP_RequestHandler_ID, Integer.valueOf(IMP_RequestHandler_ID));
}
/** Get Request handler.
@return Request handler */
@Override
public int getIMP_RequestHandler_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IMP_RequestHandler_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.adempiere.process.rpl.requesthandler.model.I_IMP_RequestHandlerType getIMP_RequestHandlerType() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_IMP_RequestHandlerType_ID, org.adempiere.process.rpl.requesthandler.model.I_IMP_RequestHandlerType.class);
}
@Override
public void setIMP_RequestHandlerType(org.adempiere.process.rpl.requesthandler.model.I_IMP_RequestHandlerType IMP_RequestHandlerType)
{
set_ValueFromPO(COLUMNNAME_IMP_RequestHandlerType_ID, org.adempiere.process.rpl.requesthandler.model.I_IMP_RequestHandlerType.class, IMP_RequestHandlerType);
}
/** Set Request handler type.
@param IMP_RequestHandlerType_ID Request handler type */
@Override
public void setIMP_RequestHandlerType_ID (int IMP_RequestHandlerType_ID)
{
if (IMP_RequestHandlerType_ID < 1)
set_Value (COLUMNNAME_IMP_RequestHandlerType_ID, null);
else
set_Value (COLUMNNAME_IMP_RequestHandlerType_ID, Integer.valueOf(IMP_RequestHandlerType_ID));
}
/** Get Request handler type.
@return Request handler type */
@Override
public int getIMP_RequestHandlerType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IMP_RequestHandlerType_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 Suchschlüssel.
@param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\process\rpl\requesthandler\model\X_IMP_RequestHandler.java | 1 |
请完成以下Java代码 | public class M_HU_DestroyEmptyHUs extends JavaProcess
{
// services
private final transient IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
// Parameters
private static final String PARAM_M_Warehouse_ID = "M_Warehouse_ID";
private int p_M_Warehouse_ID;
// Status
private int countDestroyed = 0;
private int countNotDestroyed = 0;
@Override
protected void prepare()
{
for (final ProcessInfoParameter para : getParametersAsArray())
{
if (PARAM_M_Warehouse_ID.equals(para.getParameterName()))
{
p_M_Warehouse_ID = para.getParameterAsInt();
}
}
}
@Override
protected String doIt() throws Exception
{
final Iterator<I_M_HU> emptyHUs = retrieveEmptyHUs();
while (emptyHUs.hasNext())
{
final I_M_HU emptyHU = emptyHUs.next();
destroyEmptyHU(emptyHU);
}
return countDestroyed + "@Destroyed@, " + countNotDestroyed + " @NotDestroyed@: " ;
}
private void destroyEmptyHU(final I_M_HU emptyHU)
{
try
{
final boolean destroyed = handlingUnitsBL.destroyIfEmptyStorage(emptyHU);
if (destroyed)
{
countDestroyed++;
}
else
{ | countNotDestroyed++;
}
}
catch (Exception e)
{
addLog("Failed destroying " + handlingUnitsBL.getDisplayName(emptyHU) + ": " + e.getLocalizedMessage());
countNotDestroyed++;
}
}
private Iterator<I_M_HU> retrieveEmptyHUs()
{
// Services
final IHandlingUnitsDAO handlingUnitsDAO = Services.get(IHandlingUnitsDAO.class);
if (p_M_Warehouse_ID <= 0)
{
throw new FillMandatoryException(PARAM_M_Warehouse_ID);
}
final IHUQueryBuilder huQueryBuilder = handlingUnitsDAO.createHUQueryBuilder()
.setContext(getCtx(), ITrx.TRXNAME_None)
.addOnlyInWarehouseId(WarehouseId.ofRepoId(p_M_Warehouse_ID))
// we don't want to deal with e.g. Shipped HUs
.addHUStatusToInclude(X_M_HU.HUSTATUS_Active)
.addHUStatusToInclude(X_M_HU.HUSTATUS_Planning)
.setEmptyStorageOnly()
.setOnlyTopLevelHUs();
return huQueryBuilder
.createQuery()
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, true)
.iterate(I_M_HU.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\process\M_HU_DestroyEmptyHUs.java | 1 |
请完成以下Java代码 | public class Types
{
public enum RequestType
{
INVOICE("invoice"),
REMINDER("reminder");
@Getter
private final String value;
private RequestType(String value)
{
this.value = value;
}
}
public enum Language
{
DE("de", "de_CH"),
IT("it", "it_CH"),
FR("fr", "fr_CH");
public static Language ofXmlValue(@NonNull final String xmlValue)
{
return Check.assumeNotNull(
LANGUAGES.get(xmlValue),
"There needs to be a language for the given xmlValue={}", xmlValue);
}
@Getter
private final String xmlValue;
@Getter
private final String metasfreshValue;
private static final Map<String, Language> LANGUAGES = ImmutableMap.of(
DE.getXmlValue(), DE,
IT.getXmlValue(), IT,
FR.getXmlValue(), FR);
private Language(String xmlValue, String metasfreshValue)
{
this.xmlValue = xmlValue;
this.metasfreshValue = metasfreshValue;
}
}
public enum Mode
{ | PRODUCTION("production"),
TEST("test");
private static final Map<String, Mode> MODES = ImmutableMap.of(
PRODUCTION.getXmlValue(), PRODUCTION,
TEST.getXmlValue(), TEST);
public static Mode ofXmlValue(@NonNull final String xmlValue)
{
return Check.assumeNotNull(
MODES.get(xmlValue),
"There needs to be a mode for the given xmlValue={}", xmlValue);
}
@Getter
private final String xmlValue;
private Mode(String xmlValue)
{
this.xmlValue = xmlValue;
}
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\Types.java | 1 |
请完成以下Java代码 | protected final void createAllocation(final I_M_HU luHU,
final I_M_HU tuHU,
final I_M_HU vhu,
@NonNull final StockQtyAndUOMQty qtyToAllocate,
final boolean deleteOldTUAllocations)
{
// In case TU is null, consider using VHU as HU (i.e. the case of an VHU on LU, or free VHU)
// NOTE: we do this shit because in some BLs TU is assumed to be there not null
// and also, before VHU level allocation the TU field was filled with VHU.
final I_M_HU tuHUActual = coalesce(tuHU, vhu);
Check.assumeNotNull(tuHUActual, "At least one of tuHU or vhu needs to be not null; qtyToAllocate={}", qtyToAllocate);
final IContextAware contextProvider = getContextProvider();
final I_M_ReceiptSchedule receiptSchedule = getDocumentLineModel();
if (deleteOldTUAllocations)
{
deleteAllocationsOfTU(receiptSchedule, tuHUActual);
}
final HUReceiptScheduleAllocBuilder builder = new HUReceiptScheduleAllocBuilder();
builder.setContext(contextProvider)
.setM_ReceiptSchedule(receiptSchedule)
.setM_InOutLine(null)
.setQtyToAllocate(qtyToAllocate.toZero())
.setQtyWithIssues(qtyToAllocate.toZero()) // to be sure...
; | builder.setHU_QtyAllocated(qtyToAllocate)
.setM_LU_HU(luHU)
.setM_TU_HU(tuHUActual)
.setVHU(vhu);
// Create RSA and save it
builder.buildAndSave();
}
/**
* Remove existing receipt schedule allocations for the given TU.
*/
private final void deleteAllocationsOfTU(final I_M_ReceiptSchedule receiptSchedule, final I_M_HU tuHU)
{
final String trxName = getTrxName();
final List<I_M_HU> tradingUnitsToUnassign = Collections.singletonList(tuHU);
huReceiptScheduleDAO.deleteTradingUnitAllocations(receiptSchedule, tradingUnitsToUnassign, trxName);
}
@Override
protected void deleteAllocations(final Collection<I_M_HU> husToUnassign)
{
final I_M_ReceiptSchedule receiptSchedule = getDocumentLineModel();
final String trxName = getTrxName();
huReceiptScheduleDAO.deleteHandlingUnitAllocations(receiptSchedule, husToUnassign, trxName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleHUAllocations.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public java.lang.Throwable getError(final WebRequest webRequest)
{
Throwable exception = (Throwable)webRequest.getAttribute(REQUEST_ATTR_EXCEPTION, RequestAttributes.SCOPE_REQUEST);
if (exception == null)
{
exception = (Throwable)webRequest.getAttribute(RequestDispatcher.ERROR_EXCEPTION, RequestAttributes.SCOPE_REQUEST);
}
if (exception != null)
{
exception = AdempiereException.extractCause(exception);
}
return exception;
}
@Nullable
private Throwable getRootError(final WebRequest webRequest)
{
final Throwable error = getError(webRequest);
return error != null ? unboxRootError(error) : null;
}
public Throwable unboxRootError(@NonNull final java.lang.Throwable error)
{
Throwable rootError = error;
while (rootError instanceof ServletException)
{
final Throwable cause = AdempiereException.extractCause(rootError);
if (cause == rootError)
{
return rootError;
} | else
{
rootError = cause;
}
}
return rootError;
}
@SuppressWarnings("unchecked")
private static <T> T getAttribute(final RequestAttributes requestAttributes, final String name)
{
return (T)requestAttributes.getAttribute(name, RequestAttributes.SCOPE_REQUEST);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\config\WebuiExceptionHandler.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getQtyEnteredInBPartnerUOM() {
return qtyEnteredInBPartnerUOM;
}
/**
* Sets the value of the qtyEnteredInBPartnerUOM property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setQtyEnteredInBPartnerUOM(BigDecimal value) {
this.qtyEnteredInBPartnerUOM = value;
}
/**
* Gets the value of the bPartnerQtyItemCapacity property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getBPartnerQtyItemCapacity() {
return bPartnerQtyItemCapacity;
}
/**
* Sets the value of the bPartnerQtyItemCapacity property.
*
* @param value
* allowed object is | * {@link BigDecimal }
*
*/
public void setBPartnerQtyItemCapacity(BigDecimal value) {
this.bPartnerQtyItemCapacity = value;
}
/**
* Gets the value of the upctu property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUPCTU() {
return upctu;
}
/**
* Sets the value of the upctu property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUPCTU(String value) {
this.upctu = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDIExpDesadvLineType.java | 2 |
请完成以下Java代码 | public class HUNotAssignableException extends HUException
{
/**
*
*/
private static final long serialVersionUID = -438979286865114772L;
/**
*
* @param message reason why is not assignable
* @param documentLineModel document line on which HU was tried to be assigned
* @param hu HU that wanted to be assigned
*/
public HUNotAssignableException(final String message, final Object documentLineModel, final I_M_HU hu)
{
super(buildMsg(message, documentLineModel, hu));
}
private static final String buildMsg(final String message, final Object documentLineModel, final I_M_HU hu)
{
final StringBuilder sb = new StringBuilder();
if (!Check.isEmpty(message, true))
{
sb.append(message.trim());
} | //
// Document Line Info
if (documentLineModel != null)
{
if (sb.length() > 0)
{
sb.append("\n");
}
sb.append("@Line@: ").append(documentLineModel);
}
//
// HU Info
if (hu != null)
{
if (sb.length() > 0)
{
sb.append("\n");
}
sb.append("@M_HU_ID@: ").append(hu.getValue()).append(" (ID=").append(hu.getM_HU_ID()).append(")");
}
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\exceptions\HUNotAssignableException.java | 1 |
请完成以下Java代码 | public static class KPIDataSetBuilder
{
private String name;
@Getter
@Nullable private String unit;
private final Map<KPIDataSetValuesAggregationKey, KPIDataSetValuesMap.KPIDataSetValuesMapBuilder> valuesByKey = new LinkedHashMap<>();
public KPIDataSet build()
{
return new KPIDataSet(this);
}
public KPIDataSetBuilder name(final String name)
{
this.name = name;
return this;
}
public KPIDataSetBuilder unit(@Nullable final String unit)
{
this.unit = unit;
return this;
}
public KPIDataSetValuesMap.KPIDataSetValuesMapBuilder dataSetValue(final KPIDataSetValuesAggregationKey dataSetValueKey)
{ | return valuesByKey.computeIfAbsent(dataSetValueKey, KPIDataSetValuesMap::builder);
}
public void putValue(@NonNull final KPIDataSetValuesAggregationKey dataSetValueKey, @NonNull final String fieldName, @NonNull final KPIDataValue value)
{
dataSetValue(dataSetValueKey).put(fieldName, value);
}
public void putValueIfAbsent(@NonNull final KPIDataSetValuesAggregationKey dataSetValueKey, @NonNull final String fieldName, @NonNull final KPIDataValue value)
{
dataSetValue(dataSetValueKey).putIfAbsent(fieldName, value);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\KPIDataSet.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.