instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请在Spring Boot框架中完成以下Java代码
|
public SecurityFilterChain filterChain(HttpSecurity http, SAMLProcessingFilter samlProcessingFilter) throws Exception {
http
.csrf()
.disable();
http
.httpBasic()
.authenticationEntryPoint(samlEntryPoint);
http
.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class)
.addFilterAfter(samlProcessingFilter, BasicAuthenticationFilter.class)
.addFilterBefore(samlProcessingFilter, CsrfFilter.class);
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated();
|
http
.logout()
.addLogoutHandler((request, response, authentication) -> {
try {
response.sendRedirect("/saml/logout");
} catch (IOException e) {
e.printStackTrace();
}
});
http.authenticationProvider(samlAuthenticationProvider);
return http.build();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-saml\src\main\java\com\baeldung\saml\config\WebSecurityConfig.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public SAMLProcessingFilter samlWebSSOProcessingFilter(AuthenticationManager authenticationManager) {
SAMLProcessingFilter samlWebSSOProcessingFilter = new SAMLProcessingFilter();
samlWebSSOProcessingFilter.setAuthenticationManager(authenticationManager);
samlWebSSOProcessingFilter.setAuthenticationSuccessHandler(samlAuthSuccessHandler);
samlWebSSOProcessingFilter.setAuthenticationFailureHandler(samlAuthFailureHandler);
return samlWebSSOProcessingFilter;
}
@Bean
public FilterChainProxy samlFilter(SAMLProcessingFilter samlProcessingFilter) throws Exception {
List<SecurityFilterChain> chains = new ArrayList<>();
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SSO/**"),
samlProcessingFilter));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/discovery/**"),
samlDiscovery()));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/login/**"),
samlEntryPoint));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/logout/**"),
samlLogoutFilter));
chains.add(new DefaultSecurityFilterChain(new AntPathRequestMatcher("/saml/SingleLogout/**"),
samlLogoutProcessingFilter));
return new FilterChainProxy(chains);
}
@Bean
public MetadataGeneratorFilter metadataGeneratorFilter() {
return new MetadataGeneratorFilter(metadataGenerator());
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http, SAMLProcessingFilter samlProcessingFilter) throws Exception {
http
.csrf()
.disable();
http
.httpBasic()
.authenticationEntryPoint(samlEntryPoint);
|
http
.addFilterBefore(metadataGeneratorFilter(), ChannelProcessingFilter.class)
.addFilterAfter(samlProcessingFilter, BasicAuthenticationFilter.class)
.addFilterBefore(samlProcessingFilter, CsrfFilter.class);
http
.authorizeRequests()
.antMatchers("/").permitAll()
.anyRequest().authenticated();
http
.logout()
.addLogoutHandler((request, response, authentication) -> {
try {
response.sendRedirect("/saml/logout");
} catch (IOException e) {
e.printStackTrace();
}
});
http.authenticationProvider(samlAuthenticationProvider);
return http.build();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-saml\src\main\java\com\baeldung\saml\config\WebSecurityConfig.java
| 2
|
请完成以下Java代码
|
private static long invalidateNoFail(@Nullable final CacheInterface cacheInstance)
{
try (final IAutoCloseable ignored = CacheMDC.putCache(cacheInstance))
{
if (cacheInstance == null)
{
return 0;
}
return cacheInstance.reset();
}
catch (final Exception ex)
{
// log but don't fail
logger.warn("Error while resetting {}. Ignored.", cacheInstance, ex);
return 0;
}
}
|
private static long invalidateNoFail(final CacheInterface cacheInstance, final TableRecordReference recordRef)
{
try (final IAutoCloseable ignored = CacheMDC.putCache(cacheInstance))
{
return cacheInstance.resetForRecordId(recordRef);
}
catch (final Exception ex)
{
// log but don't fail
logger.warn("Error while resetting {} for {}. Ignored.", cacheInstance, recordRef, ex);
return 0;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\CacheMgt.java
| 1
|
请完成以下Java代码
|
public boolean isExitCriterion() {
return isExitCriterion;
}
public void setExitCriterion(boolean isExitCriterion) {
this.isExitCriterion = isExitCriterion;
}
public String getExitType() {
return exitType;
}
public void setExitType(String exitType) {
this.exitType = exitType;
}
public String getExitEventType() {
return exitEventType;
}
public void setExitEventType(String exitEventType) {
this.exitEventType = exitEventType;
}
@Override
public void addIncomingAssociation(Association association) {
this.incomingAssociations.add(association);
}
@Override
public List<Association> getIncomingAssociations() {
return incomingAssociations;
}
@Override
public void setIncomingAssociations(List<Association> incomingAssociations) {
this.incomingAssociations = incomingAssociations;
}
@Override
public void addOutgoingAssociation(Association association) {
this.outgoingAssociations.add(association);
}
|
@Override
public List<Association> getOutgoingAssociations() {
return outgoingAssociations;
}
@Override
public void setOutgoingAssociations(List<Association> outgoingAssociations) {
this.outgoingAssociations = outgoingAssociations;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
if (isEntryCriterion) {
stringBuilder.append("Entry criterion");
} else {
stringBuilder.append("Exit criterion");
}
stringBuilder.append(" with id '").append(id).append("'");
return stringBuilder.toString();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\Criterion.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CountryController {
@Autowired
private CountryService countryService;
@RequestMapping
public ModelAndView getAll(Country country) {
ModelAndView result = new ModelAndView("index");
List<Country> countryList = countryService.getAllByWeekend(country);
result.addObject("pageInfo", new PageInfo<Country>(countryList));
result.addObject("queryParam", country);
result.addObject("page", country.getPage());
result.addObject("rows", country.getRows());
return result;
}
@RequestMapping(value = "/add")
public ModelAndView add() {
ModelAndView result = new ModelAndView("view");
result.addObject("country", new Country());
return result;
}
@RequestMapping(value = "/view/{id}")
public ModelAndView view(@PathVariable Integer id) {
ModelAndView result = new ModelAndView("view");
Country country = countryService.getById(id);
|
result.addObject("country", country);
return result;
}
@RequestMapping(value = "/delete/{id}")
public ModelAndView delete(@PathVariable Integer id, RedirectAttributes ra) {
ModelAndView result = new ModelAndView("redirect:/countries");
countryService.deleteById(id);
ra.addFlashAttribute("msg", "删除成功!");
return result;
}
@RequestMapping(value = "/save", method = RequestMethod.POST)
public ModelAndView save(Country country) {
ModelAndView result = new ModelAndView("view");
String msg = country.getId() == null ? "新增成功!" : "更新成功!";
countryService.save(country);
result.addObject("country", country);
result.addObject("msg", msg);
return result;
}
}
|
repos\MyBatis-Spring-Boot-master\src\main\java\tk\mybatis\springboot\controller\CountryController.java
| 2
|
请完成以下Java代码
|
private static String getFailureMessage(Throwable th) {
String failureMessage;
if (th != null) {
if (!StringUtils.isEmpty(th.getMessage())) {
failureMessage = th.getMessage();
} else {
failureMessage = th.getClass().getSimpleName();
}
} else {
failureMessage = null;
}
return failureMessage;
}
private void persistDebugOutput(TbMsg msg, String relationType) {
persistDebugOutput(msg, Set.of(relationType));
}
|
private void persistDebugOutput(TbMsg msg, Set<String> relationTypes) {
persistDebugOutput(msg, relationTypes, null, null);
}
private void persistDebugOutput(TbMsg msg, Set<String> relationTypes, Throwable error, String failureMessage) {
RuleNode ruleNode = nodeCtx.getSelf();
if (DebugModeUtil.isDebugAllAvailable(ruleNode)) {
relationTypes.forEach(relationType -> mainCtx.persistDebugOutput(getTenantId(), ruleNode.getId(), msg, relationType, error, failureMessage));
} else if (DebugModeUtil.isDebugFailuresAvailable(ruleNode, relationTypes)) {
mainCtx.persistDebugOutput(getTenantId(), ruleNode.getId(), msg, TbNodeConnectionType.FAILURE, error, failureMessage);
}
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\actors\ruleChain\DefaultTbContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getJmx() {
return this.jmx;
}
public void setJmx(String jmx) {
this.jmx = jmx;
}
public String getLocator() {
return this.locator;
}
public void setLocator(String locator) {
this.locator = locator;
}
|
public String getServer() {
return this.server;
}
public void setServer(String server) {
this.server = server;
}
public String getWeb() {
return this.web;
}
public void setWeb(String web) {
this.web = web;
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SslProperties.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Iterator<FTSJoinColumn> iterator()
{
return joinColumns.iterator();
}
public String buildJoinCondition(
@NonNull final String targetTableNameOrAlias,
@Nullable final String selectionTableNameOrAlias)
{
Check.assumeNotEmpty(targetTableNameOrAlias, "targetTableNameOrAlias not empty");
final String selectionTableNameOrAliasWithDot = StringUtils.trimBlankToOptional(selectionTableNameOrAlias)
.map(alias -> alias + ".")
.orElse("");
final StringBuilder sql = new StringBuilder();
for (final FTSJoinColumn joinColumn : joinColumns)
{
if (sql.length() > 0)
{
sql.append(" AND ");
}
if (joinColumn.isNullable())
{
|
sql.append("(")
.append(selectionTableNameOrAliasWithDot).append(joinColumn.getSelectionTableColumnName()).append(" IS NULL")
.append(" OR ")
.append(targetTableNameOrAlias).append(".").append(joinColumn.getTargetTableColumnName())
.append(" IS NOT DISTINCT FROM ")
.append(selectionTableNameOrAliasWithDot).append(joinColumn.getSelectionTableColumnName())
.append(")");
}
else
{
sql.append(targetTableNameOrAlias).append(".").append(joinColumn.getTargetTableColumnName())
.append("=")
.append(selectionTableNameOrAliasWithDot).append(joinColumn.getSelectionTableColumnName());
}
}
return sql.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSJoinColumnList.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static final class StaticResourceRequestMatcher
extends ApplicationContextRequestMatcher<DispatcherServletPath> {
private final Set<StaticResourceLocation> locations;
private volatile @Nullable RequestMatcher delegate;
private StaticResourceRequestMatcher(Set<StaticResourceLocation> locations) {
super(DispatcherServletPath.class);
this.locations = locations;
}
/**
* Return a new {@link StaticResourceRequestMatcher} based on this one but
* excluding the specified locations.
* @param first the first location to exclude
* @param rest additional locations to exclude
* @return a new {@link StaticResourceRequestMatcher}
*/
public StaticResourceRequestMatcher excluding(StaticResourceLocation first, StaticResourceLocation... rest) {
return excluding(EnumSet.of(first, rest));
}
/**
* Return a new {@link StaticResourceRequestMatcher} based on this one but
* excluding the specified locations.
* @param locations the locations to exclude
* @return a new {@link StaticResourceRequestMatcher}
*/
public StaticResourceRequestMatcher excluding(Set<StaticResourceLocation> locations) {
Assert.notNull(locations, "'locations' must not be null");
Set<StaticResourceLocation> subset = new LinkedHashSet<>(this.locations);
subset.removeAll(locations);
return new StaticResourceRequestMatcher(subset);
}
@Override
protected void initialized(Supplier<DispatcherServletPath> dispatcherServletPath) {
this.delegate = new OrRequestMatcher(getDelegateMatchers(dispatcherServletPath.get()).toList());
}
|
private Stream<RequestMatcher> getDelegateMatchers(DispatcherServletPath dispatcherServletPath) {
return getPatterns(dispatcherServletPath).map(PathPatternRequestMatcher.withDefaults()::matcher);
}
private Stream<String> getPatterns(DispatcherServletPath dispatcherServletPath) {
return this.locations.stream()
.flatMap(StaticResourceLocation::getPatterns)
.map(dispatcherServletPath::getRelativePath);
}
@Override
protected boolean ignoreApplicationContext(WebApplicationContext applicationContext) {
return hasServerNamespace(applicationContext, "management");
}
@Override
protected boolean matches(HttpServletRequest request, Supplier<DispatcherServletPath> context) {
RequestMatcher delegate = this.delegate;
Assert.state(delegate != null, "'delegate' must not be null");
return delegate.matches(request);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-security\src\main\java\org\springframework\boot\security\autoconfigure\web\servlet\StaticResourceRequest.java
| 2
|
请完成以下Java代码
|
private Set<ConfigAttribute> getUnsupportedAttributes(Collection<ConfigAttribute> attrDefs) {
Set<ConfigAttribute> unsupportedAttributes = new HashSet<>();
for (ConfigAttribute attr : attrDefs) {
if (!this.channelDecisionManager.supports(attr)) {
unsupportedAttributes.add(attr);
}
}
return unsupportedAttributes;
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
FilterInvocation filterInvocation = new FilterInvocation(request, response, chain);
Collection<ConfigAttribute> attributes = this.securityMetadataSource.getAttributes(filterInvocation);
if (attributes != null) {
this.logger.debug(LogMessage.format("Request: %s; ConfigAttributes: %s", filterInvocation, attributes));
this.channelDecisionManager.decide(filterInvocation, attributes);
@Nullable HttpServletResponse channelResponse = filterInvocation.getResponse();
Assert.notNull(channelResponse, "HttpServletResponse is required");
if (channelResponse.isCommitted()) {
return;
}
}
chain.doFilter(request, response);
|
}
protected @Nullable ChannelDecisionManager getChannelDecisionManager() {
return this.channelDecisionManager;
}
protected FilterInvocationSecurityMetadataSource getSecurityMetadataSource() {
return this.securityMetadataSource;
}
public void setChannelDecisionManager(ChannelDecisionManager channelDecisionManager) {
this.channelDecisionManager = channelDecisionManager;
}
public void setSecurityMetadataSource(
FilterInvocationSecurityMetadataSource filterInvocationSecurityMetadataSource) {
this.securityMetadataSource = filterInvocationSecurityMetadataSource;
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\channel\ChannelProcessingFilter.java
| 1
|
请完成以下Java代码
|
public void assertAssignable(final I_M_HU hu, final Object model, final String trxName) throws HUNotAssignableException
{
final I_M_ReceiptSchedule receiptSchedule = getReceiptScheduleOrNull(model);
if (receiptSchedule == null)
{
// does not apply
return;
}
//
// Only HUs which have HUStatus=Planning are allowed to be assigned to an Receipt Schedule
final String huStatus = hu.getHUStatus();
if (!X_M_HU.HUSTATUS_Planning.equals(huStatus))
{
throw new HUNotAssignableException("@HUStatus@ <> Planning", model, hu);
}
}
/**
* Updates the given assigned {@code hu}'s {@code M_Locator_ID} from the I_M_ReceiptSchedule that is given {@code model}.
*
|
*/
@Override
public void onHUAssigned(final I_M_HU hu, final Object model, final String trxName)
{
final I_M_ReceiptSchedule receiptSchedule = getReceiptScheduleOrNull(model);
if (receiptSchedule == null)
{
// does not apply
return;
}
//
// Update HU's locator (if needed)
final WarehouseId warehouseId = Services.get(IReceiptScheduleBL.class).getWarehouseEffectiveId(receiptSchedule);
final LocatorId locatorId = Services.get(IWarehouseBL.class).getOrCreateDefaultLocatorId(warehouseId);
hu.setM_Locator_ID(locatorId.getRepoId());
InterfaceWrapperHelper.save(hu, trxName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\receiptschedule\impl\ReceiptScheduleHUAssignmentListener.java
| 1
|
请完成以下Java代码
|
private Object getBody(@NonNull final ContentCachingResponseWrapper responseWrapper)
{
if (responseWrapper.getContentSize() <= 0)
{
return null;
}
final MediaType contentType = getContentType(responseWrapper);
if (contentType == null)
{
return null;
}
else if (contentType.includes(MediaType.TEXT_PLAIN))
{
return new String(responseWrapper.getContentAsByteArray());
}
else if (contentType.includes(MediaType.APPLICATION_JSON))
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(responseWrapper.getContentAsByteArray(), Object.class);
}
catch (final IOException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
else
{
return responseWrapper.getContentAsByteArray();
}
}
@Nullable
private Object getBody(@Nullable final HttpHeaders httpHeaders, @Nullable final String bodyCandidate)
|
{
if (bodyCandidate == null)
{
return null;
}
final MediaType contentType = getContentType(httpHeaders);
if (contentType == null)
{
return null;
}
else if (contentType.includes(MediaType.TEXT_PLAIN))
{
return bodyCandidate;
}
else if (contentType.includes(MediaType.APPLICATION_JSON))
{
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(bodyCandidate, Object.class);
}
catch (final IOException e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
else
{
return bodyCandidate;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\audit\dto\ApiResponseMapper.java
| 1
|
请完成以下Java代码
|
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
if (processInstanceId != null){
referenceIdAndClass.put(processInstanceId, ExecutionEntity.class);
}
if (executionId != null){
referenceIdAndClass.put(executionId, ExecutionEntity.class);
}
if (caseInstanceId != null){
referenceIdAndClass.put(caseInstanceId, CaseExecutionEntity.class);
}
if (caseExecutionId != null){
referenceIdAndClass.put(caseExecutionId, CaseExecutionEntity.class);
|
}
if (getByteArrayValueId() != null){
referenceIdAndClass.put(getByteArrayValueId(), ByteArrayEntity.class);
}
return referenceIdAndClass;
}
/**
*
* @return <code>true</code> <code>processDefinitionId</code> is introduced in 7.13,
* the check is used to created missing history at {@link LegacyBehavior#createMissingHistoricVariables(org.camunda.bpm.engine.impl.pvm.runtime.PvmExecutionImpl) LegacyBehavior#createMissingHistoricVariables}
*/
public boolean wasCreatedBefore713() {
return this.getProcessDefinitionId() == null;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\VariableInstanceEntity.java
| 1
|
请完成以下Java代码
|
public String firstLabel()
{
return labelMap.keySet().iterator().next();
}
/**
*
* @param param 类似 “希望 v 7685 vn 616” 的字串
* @return
*/
public static Item create(String param)
{
if (param == null) return null;
String mark = "\\s"; // 分隔符,历史格式用空格,但是现在觉得用制表符比较好
if (param.indexOf('\t') > 0) mark = "\t";
String[] array = param.split(mark);
|
return create(array);
}
public static Item create(String param[])
{
if (param.length % 2 == 0) return null;
Item item = new Item(param[0]);
int natureCount = (param.length - 1) / 2;
for (int i = 0; i < natureCount; ++i)
{
item.labelMap.put(param[1 + 2 * i], Integer.parseInt(param[2 + 2 * i]));
}
return item;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\item\Item.java
| 1
|
请完成以下Java代码
|
public void setURL3 (final @Nullable java.lang.String URL3)
{
set_Value (COLUMNNAME_URL3, URL3);
}
@Override
public java.lang.String getURL3()
{
return get_ValueAsString(COLUMNNAME_URL3);
}
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setVATaxID (final @Nullable java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
|
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
@Override
public void setVendorCategory (final @Nullable java.lang.String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
@Override
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setPassword(@Nullable String password) {
this.password = password;
}
public @Nullable String getRetentionPolicy() {
return this.retentionPolicy;
}
public void setRetentionPolicy(@Nullable String retentionPolicy) {
this.retentionPolicy = retentionPolicy;
}
public @Nullable String getRetentionDuration() {
return this.retentionDuration;
}
public void setRetentionDuration(@Nullable String retentionDuration) {
this.retentionDuration = retentionDuration;
}
public @Nullable Integer getRetentionReplicationFactor() {
return this.retentionReplicationFactor;
}
public void setRetentionReplicationFactor(@Nullable Integer retentionReplicationFactor) {
this.retentionReplicationFactor = retentionReplicationFactor;
}
public @Nullable String getRetentionShardDuration() {
return this.retentionShardDuration;
}
public void setRetentionShardDuration(@Nullable String retentionShardDuration) {
this.retentionShardDuration = retentionShardDuration;
}
public String getUri() {
return this.uri;
}
public void setUri(String uri) {
this.uri = uri;
}
public boolean isCompressed() {
return this.compressed;
}
public void setCompressed(boolean compressed) {
this.compressed = compressed;
|
}
public boolean isAutoCreateDb() {
return this.autoCreateDb;
}
public void setAutoCreateDb(boolean autoCreateDb) {
this.autoCreateDb = autoCreateDb;
}
public @Nullable InfluxApiVersion getApiVersion() {
return this.apiVersion;
}
public void setApiVersion(@Nullable InfluxApiVersion apiVersion) {
this.apiVersion = apiVersion;
}
public @Nullable String getOrg() {
return this.org;
}
public void setOrg(@Nullable String org) {
this.org = org;
}
public @Nullable String getBucket() {
return this.bucket;
}
public void setBucket(@Nullable String bucket) {
this.bucket = bucket;
}
public @Nullable String getToken() {
return this.token;
}
public void setToken(@Nullable String token) {
this.token = token;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\influx\InfluxProperties.java
| 2
|
请完成以下Java代码
|
public class DeviceQRCodeJsonConverter
{
public static GlobalQRCodeType GLOBAL_QRCODE_TYPE = GlobalQRCodeType.ofString("SCALE");
public static String toGlobalQRCodeJsonString(final DeviceQRCode qrCode)
{
return toGlobalQRCode(qrCode).getAsString();
}
public static GlobalQRCode toGlobalQRCode(final DeviceQRCode qrCode)
{
return JsonConverterV1.toGlobalQRCode(qrCode);
}
public static DeviceQRCode fromGlobalQRCodeJsonString(final String qrCodeString)
{
return fromGlobalQRCode(GlobalQRCode.ofString(qrCodeString));
}
public static DeviceQRCode fromGlobalQRCode(@NonNull final GlobalQRCode globalQRCode)
{
if (!GlobalQRCodeType.equals(GLOBAL_QRCODE_TYPE, globalQRCode.getType()))
{
throw new AdempiereException("Invalid QR Code")
|
.setParameter("globalQRCode", globalQRCode); // avoid adding it to error message, it might be quite long
}
final GlobalQRCodeVersion version = globalQRCode.getVersion();
if (GlobalQRCodeVersion.equals(globalQRCode.getVersion(), JsonConverterV1.GLOBAL_QRCODE_VERSION))
{
return JsonConverterV1.fromGlobalQRCode(globalQRCode);
}
else
{
throw new AdempiereException("Invalid QR Code version: " + version);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\accessor\qrcode\DeviceQRCodeJsonConverter.java
| 1
|
请完成以下Java代码
|
public ParameterValueProvider getVersionTagValueProvider() {
return versionTagValueProvider;
}
public void setVersionTagValueProvider(ParameterValueProvider version) {
this.versionTagValueProvider = version;
}
public void setTenantIdProvider(ParameterValueProvider tenantIdProvider) {
this.tenantIdProvider = tenantIdProvider;
}
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getDefinitionTenantId(VariableScope variableScope, String defaultTenantId) {
if (tenantIdProvider != null) {
return (String) tenantIdProvider.getValue(variableScope);
} else {
|
return defaultTenantId;
}
}
public ParameterValueProvider getTenantIdProvider() {
return tenantIdProvider;
}
/**
* @return true if any of the references that specify the callable element are non-literal and need to be resolved with
* potential side effects to determine the process or case definition that is to be called.
*/
public boolean hasDynamicReferences() {
return (tenantIdProvider != null && tenantIdProvider.isDynamic())
|| definitionKeyValueProvider.isDynamic()
|| versionValueProvider.isDynamic()
|| versionTagValueProvider.isDynamic();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\core\model\BaseCallableElement.java
| 1
|
请完成以下Java代码
|
public class InstantAndOrgId implements Comparable<InstantAndOrgId>
{
@NonNull private final Instant instant;
@NonNull private final OrgId orgId;
private InstantAndOrgId(@NonNull final Instant instant, @NonNull final OrgId orgId)
{
this.instant = instant;
this.orgId = orgId;
}
public @NonNull static InstantAndOrgId ofInstant(@NonNull final Instant instant, @NonNull final OrgId orgId)
{
return new InstantAndOrgId(instant, orgId);
}
public @Nullable static InstantAndOrgId ofTimestampOrNull(@Nullable final java.sql.Timestamp timestamp, @NonNull final OrgId orgId)
{
if(timestamp == null)
{
return null;
}
return ofTimestamp(timestamp, orgId);
}
public @NonNull static InstantAndOrgId ofTimestamp(@NonNull final java.sql.Timestamp timestamp, @NonNull final OrgId orgId)
{
|
return new InstantAndOrgId(timestamp.toInstant(), orgId);
}
public @NonNull static InstantAndOrgId ofTimestamp(@NonNull final java.sql.Timestamp timestamp, final int orgRepoId)
{
return new InstantAndOrgId(timestamp.toInstant(), OrgId.ofRepoId(orgRepoId));
}
public @NonNull OrgId getOrgId() {return orgId;}
public Instant toInstant() {return instant;}
public @NonNull ZonedDateTime toZonedDateTime(@NonNull final ZoneId zoneId) {return instant.atZone(zoneId);}
public @NonNull ZonedDateTime toZonedDateTime(@NonNull final Function<OrgId, ZoneId> orgMapper) {return instant.atZone(orgMapper.apply(orgId));}
public @NonNull java.sql.Timestamp toTimestamp() {return java.sql.Timestamp.from(instant);}
public LocalDate toLocalDate(@NonNull final Function<OrgId, ZoneId> orgMapper) {return toZonedDateTime(orgMapper).toLocalDate();}
public LocalDateAndOrgId toLocalDateAndOrgId(@NonNull final Function<OrgId, ZoneId> orgMapper) {return LocalDateAndOrgId.ofLocalDate(toLocalDate(orgMapper), orgId);}
@Override
public int compareTo(@NonNull final InstantAndOrgId other) {return this.instant.compareTo(other.instant);}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\InstantAndOrgId.java
| 1
|
请完成以下Java代码
|
public int getAD_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Issue_ID);
}
@Override
public void setConfigSummary (final @Nullable java.lang.String ConfigSummary)
{
set_Value (COLUMNNAME_ConfigSummary, ConfigSummary);
}
@Override
public java.lang.String getConfigSummary()
{
return get_ValueAsString(COLUMNNAME_ConfigSummary);
}
@Override
public void setDhl_ShipmentOrder_Log_ID (final int Dhl_ShipmentOrder_Log_ID)
{
if (Dhl_ShipmentOrder_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_Dhl_ShipmentOrder_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Dhl_ShipmentOrder_Log_ID, Dhl_ShipmentOrder_Log_ID);
}
@Override
public int getDhl_ShipmentOrder_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_Dhl_ShipmentOrder_Log_ID);
}
@Override
public de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest getDHL_ShipmentOrderRequest()
{
return get_ValueAsPO(COLUMNNAME_DHL_ShipmentOrderRequest_ID, de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest.class);
}
@Override
public void setDHL_ShipmentOrderRequest(final de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest DHL_ShipmentOrderRequest)
{
set_ValueFromPO(COLUMNNAME_DHL_ShipmentOrderRequest_ID, de.metas.shipper.gateway.dhl.model.I_DHL_ShipmentOrderRequest.class, DHL_ShipmentOrderRequest);
}
@Override
public void setDHL_ShipmentOrderRequest_ID (final int DHL_ShipmentOrderRequest_ID)
{
if (DHL_ShipmentOrderRequest_ID < 1)
set_Value (COLUMNNAME_DHL_ShipmentOrderRequest_ID, null);
else
set_Value (COLUMNNAME_DHL_ShipmentOrderRequest_ID, DHL_ShipmentOrderRequest_ID);
}
@Override
public int getDHL_ShipmentOrderRequest_ID()
{
|
return get_ValueAsInt(COLUMNNAME_DHL_ShipmentOrderRequest_ID);
}
@Override
public void setDurationMillis (final int DurationMillis)
{
set_Value (COLUMNNAME_DurationMillis, DurationMillis);
}
@Override
public int getDurationMillis()
{
return get_ValueAsInt(COLUMNNAME_DurationMillis);
}
@Override
public void setIsError (final boolean IsError)
{
set_Value (COLUMNNAME_IsError, IsError);
}
@Override
public boolean isError()
{
return get_ValueAsBoolean(COLUMNNAME_IsError);
}
@Override
public void setRequestMessage (final @Nullable java.lang.String RequestMessage)
{
set_Value (COLUMNNAME_RequestMessage, RequestMessage);
}
@Override
public java.lang.String getRequestMessage()
{
return get_ValueAsString(COLUMNNAME_RequestMessage);
}
@Override
public void setResponseMessage (final @Nullable java.lang.String ResponseMessage)
{
set_Value (COLUMNNAME_ResponseMessage, ResponseMessage);
}
@Override
public java.lang.String getResponseMessage()
{
return get_ValueAsString(COLUMNNAME_ResponseMessage);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_Dhl_ShipmentOrder_Log.java
| 1
|
请完成以下Java代码
|
public Date getStartTime() {
return null;
}
@Override
public String getStartUserId() {
return null;
}
@Override
public String getCallbackId() {
return null;
}
@Override
public String getCallbackType() {
return null;
}
|
@Override
public String getReferenceId() {
return null;
}
@Override
public String getReferenceType() {
return null;
}
@Override
public String getPropagatedStageInstanceId() {
return null;
}
}
|
repos\flowable-engine-main\modules\flowable5-compatibility\src\main\java\org\flowable\compatibility\wrapper\Flowable5ProcessInstanceWrapper.java
| 1
|
请完成以下Java代码
|
private CompositeSqlLookupFilter build()
{
final IValidationRuleFactory validationRuleFactory = Services.get(IValidationRuleFactory.class);
final ArrayList<SqlLookupFilter> filters = new ArrayList<>();
for (LookupDescriptorProvider.LookupScope scope : adValRuleIdByScope.keySet())
{
final AdValRuleId adValRuleId = adValRuleIdByScope.get(scope);
if (adValRuleId != null)
{
final IValidationRule valRule = validationRuleFactory.create(lookupTableName.getAsString(), adValRuleId, ctxTableName, ctxColumnName);
for (final IValidationRule childValRule : CompositeValidationRule.unbox(valRule))
{
filters.add(SqlLookupFilter.of(childValRule, scope));
}
}
}
//
// Case: DocAction button => inject the DocActionValidationRule
// FIXME: hardcoded
if (displayType == DisplayType.Button && WindowConstants.FIELDNAME_DocAction.equals(ctxColumnName))
{
filters.add(SqlLookupFilter.of(DocActionValidationRule.instance, LookupDescriptorProvider.LookupScope.DocumentField));
}
//
// Additional validation rules registered
filters.addAll(this.filters);
return CompositeSqlLookupFilter.ofFilters(filters);
}
public void setAdValRuleId(@NonNull final LookupDescriptorProvider.LookupScope lookupScope, @Nullable final AdValRuleId adValRuleId)
{
if (adValRuleId != null)
{
adValRuleIdByScope.put(lookupScope, adValRuleId);
}
else
{
adValRuleIdByScope.remove(lookupScope);
}
}
public void setAdValRuleIds(@NonNull final Map<LookupDescriptorProvider.LookupScope, AdValRuleId> adValRuleIds)
{
adValRuleIdByScope.clear();
adValRuleIdByScope.putAll(adValRuleIds);
}
public void setLookupTableName(final TableName lookupTableName)
{
assertNotBuilt();
|
this.lookupTableName = lookupTableName;
}
public void setCtxTableName(final String ctxTableName)
{
assertNotBuilt();
this.ctxTableName = ctxTableName;
}
public void setCtxColumnName(final String ctxColumnName)
{
assertNotBuilt();
this.ctxColumnName = ctxColumnName;
}
public void setDisplayType(final int displayType)
{
assertNotBuilt();
this.displayType = displayType;
}
public void addFilter(@NonNull final Collection<IValidationRule> validationRules, @Nullable LookupDescriptorProvider.LookupScope scope)
{
for (final IValidationRule valRule : CompositeValidationRule.unbox(validationRules))
{
addFilter(SqlLookupFilter.of(valRule, scope));
}
}
public void addFilter(@Nullable final IValidationRule validationRule, @Nullable LookupDescriptorProvider.LookupScope scope)
{
for (final IValidationRule valRule : CompositeValidationRule.unbox(validationRule))
{
addFilter(SqlLookupFilter.of(valRule, scope));
}
}
private void addFilter(@NonNull final SqlLookupFilter filter)
{
assertNotBuilt();
filters.add(filter);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\CompositeSqlLookupFilterBuilder.java
| 1
|
请完成以下Java代码
|
public class X_PMM_Message extends org.compiere.model.PO implements I_PMM_Message, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 1982151971L;
/** Standard Constructor */
public X_PMM_Message (Properties ctx, int PMM_Message_ID, String trxName)
{
super (ctx, PMM_Message_ID, trxName);
/** if (PMM_Message_ID == 0)
{
setMsgText (null);
setPMM_Message_ID (0);
} */
}
/** Load Constructor */
public X_PMM_Message (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO (Properties ctx)
{
org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName());
return poi;
}
/** Set Message Text.
@param MsgText
Textual Informational, Menu or Error Message
*/
@Override
|
public void setMsgText (java.lang.String MsgText)
{
set_Value (COLUMNNAME_MsgText, MsgText);
}
/** Get Message Text.
@return Textual Informational, Menu or Error Message
*/
@Override
public java.lang.String getMsgText ()
{
return (java.lang.String)get_Value(COLUMNNAME_MsgText);
}
/** Set PMM_Message.
@param PMM_Message_ID PMM_Message */
@Override
public void setPMM_Message_ID (int PMM_Message_ID)
{
if (PMM_Message_ID < 1)
set_ValueNoCheck (COLUMNNAME_PMM_Message_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PMM_Message_ID, Integer.valueOf(PMM_Message_ID));
}
/** Get PMM_Message.
@return PMM_Message */
@Override
public int getPMM_Message_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PMM_Message_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_Message.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Foo implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@Column(nullable = false)
private String name;
@Version
private long version;
public Foo() {
super();
}
public Foo(final String name) {
super();
this.name = name;
}
// API
public long getId() {
return id;
}
public void setId(final long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
|
//
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final Foo other = (Foo) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=").append(name).append("]");
return builder.toString();
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\mime\Foo.java
| 2
|
请完成以下Java代码
|
public static ILoggable console(@Nullable final String prefix)
{
return ConsoleLoggable.withPrefix(prefix);
}
public static ILoggable logback(@NonNull final Logger logger, @NonNull final Level logLevel)
{
return new LogbackLoggable(logger, logLevel);
}
public static IAutoCloseable temporarySetLoggable(final ILoggable loggable)
{
return ThreadLocalLoggableHolder.instance.temporarySetLoggable(composeWithDebuggingLoggable(loggable));
}
public static void setDebuggingLoggable(@Nullable final ILoggable debuggingLoggable)
{
Loggables.debuggingLoggable = debuggingLoggable;
}
private static ILoggable composeWithDebuggingLoggable(@Nullable final ILoggable loggable)
{
return CompositeLoggable2.compose(loggable, debuggingLoggable);
}
/**
* @return The null loggable which can be used without NPE, but doesn't do anything
*/
@NonNull
public static ILoggable nop()
{
return NullLoggable.instance;
}
public static boolean isNull(@Nullable final ILoggable loggable)
{
return NullLoggable.isNull(loggable);
}
/**
|
* Create a new {@link ILoggable} instance that delegates {@link #addLog(String, Object...)} invocations to the thread-local instance and in addition logs to the given logger.
*/
public static ILoggable withLogger(@NonNull final Logger logger, @NonNull final Level level)
{
return new LoggableWithLogger(get(), logger, level);
}
@NonNull
public static ILoggable withFallbackToLogger(@NonNull final Logger logger, @NonNull final Level level)
{
final ILoggable threadLocalLoggable = get();
if (NullLoggable.isNull(threadLocalLoggable))
{
return new LoggableWithLogger(NullLoggable.instance, logger, level);
}
else
{
return threadLocalLoggable;
}
}
public static ILoggable withLogger(@NonNull final ILoggable loggable, @NonNull final Logger logger, @NonNull final Level level)
{
return new LoggableWithLogger(loggable, logger, level);
}
public static ILoggable withWarnLoggerToo(@NonNull final Logger logger)
{
return withLogger(logger, Level.WARN);
}
public static PlainStringLoggable newPlainStringLoggable()
{
return new PlainStringLoggable();
}
public static ILoggable addLog(final String msg, final Object... msgParameters)
{
return get().addLog(msg, msgParameters);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Loggables.java
| 1
|
请完成以下Java代码
|
public void setCardCtryCd(String value) {
this.cardCtryCd = value;
}
/**
* Gets the value of the cardBrnd property.
*
* @return
* possible object is
* {@link GenericIdentification1 }
*
*/
public GenericIdentification1 getCardBrnd() {
return cardBrnd;
}
/**
* Sets the value of the cardBrnd property.
*
* @param value
* allowed object is
* {@link GenericIdentification1 }
*
*/
public void setCardBrnd(GenericIdentification1 value) {
this.cardBrnd = value;
}
|
/**
* Gets the value of the addtlCardData property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlCardData() {
return addtlCardData;
}
/**
* Sets the value of the addtlCardData property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlCardData(String value) {
this.addtlCardData = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\PaymentCard4.java
| 1
|
请完成以下Java代码
|
class DeferredServletContainerInitializers
implements ServletContainerInitializer, TomcatEmbeddedContext.DeferredStartupExceptions {
private static final Log logger = LogFactory.getLog(DeferredServletContainerInitializers.class);
private final Iterable<ServletContextInitializer> initializers;
private volatile @Nullable Exception startUpException;
DeferredServletContainerInitializers(Iterable<ServletContextInitializer> initializers) {
this.initializers = initializers;
}
@Override
public void onStartup(Set<Class<?>> classes, ServletContext servletContext) throws ServletException {
try {
for (ServletContextInitializer initializer : this.initializers) {
initializer.onStartup(servletContext);
}
}
|
catch (Exception ex) {
this.startUpException = ex;
// Prevent Tomcat from logging and re-throwing when we know we can
// deal with it in the main thread, but log for information here.
if (logger.isErrorEnabled()) {
logger.error("Error starting Tomcat context. Exception: " + ex.getClass().getName() + ". Message: "
+ ex.getMessage());
}
}
}
@Override
public void rethrow() throws Exception {
if (this.startUpException != null) {
throw this.startUpException;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\servlet\DeferredServletContainerInitializers.java
| 1
|
请完成以下Java代码
|
private int determineAcct (int C_AcctSchema_ID, int M_Product_ID, int C_Charge_ID, BigDecimal lineAmt)
{
int invoiceAcct =0;
if (M_Product_ID == 0 && C_Charge_ID != 0)
{
if(lineAmt.signum() > 0){
String sqlb = "SELECT CH_Expense_Acct FROM C_Charge_Acct WHERE C_Charge_ID=? and C_AcctSchema_ID=?";
invoiceAcct = DB.getSQLValue(get_TrxName(),sqlb,C_Charge_ID,C_AcctSchema_ID);
}
else{
String sqlb = "SELECT CH_Revenue_Acct FROM C_Charge_Acct WHERE C_Charge_ID=? and C_AcctSchema_ID=?";
invoiceAcct = DB.getSQLValue(get_TrxName(),sqlb,C_Charge_ID,C_AcctSchema_ID);
}
}
else if(M_Product_ID != 0){
if(lineAmt.signum() > 0){
String sqlb = "SELECT P_Expense_Acct FROM M_Product_Acct WHERE M_Product_ID=? and C_AcctSchema_ID=?";
invoiceAcct = DB.getSQLValue(get_TrxName(),sqlb,M_Product_ID,C_AcctSchema_ID);
}
else{
String sqlb = "SELECT P_Revenue_Acct FROM M_Product_Acct WHERE M_Product_ID=? and C_AcctSchema_ID=?";
invoiceAcct = DB.getSQLValue(get_TrxName(),sqlb,M_Product_ID,C_AcctSchema_ID);
}
}
else{
if(lineAmt.signum() > 0){
String sqlb = "SELECT P_Expense_Acct "
+ "FROM M_Product_Category pc, M_Product_Category_Acct pca "
+ "WHERE pc.M_Product_Category_ID=pca.M_Product_Category_ID"
+ " AND pca.C_AcctSchema_ID=? "
+ "ORDER BY pc.IsDefault DESC, pc.Created";
invoiceAcct = DB.getSQLValue(get_TrxName(),sqlb,C_AcctSchema_ID);
}
else{
String sqlb = "SELECT P_Revenue_Acct "
+ "FROM M_Product_Category pc, M_Product_Category_Acct pca "
+ "WHERE pc.M_Product_Category_ID=pca.M_Product_Category_ID"
+ " AND pca.C_AcctSchema_ID=? "
+ "ORDER BY pc.IsDefault DESC, pc.Created";
invoiceAcct = DB.getSQLValue(get_TrxName(),sqlb,C_AcctSchema_ID);
|
}
}
return invoiceAcct;
}
/**
* Get tax posting accounts for invoice.
*
*
*/
private int determineTaxAcct (int C_AcctSchema_ID, int C_Tax_ID)
{
int invoiceAcct =0;
String sqlb = "SELECT T_Expense_Acct FROM C_Tax_Acct WHERE C_AcctSchema_ID=? and C_Tax_ID=?";
invoiceAcct = DB.getSQLValue(get_TrxName(),sqlb,C_AcctSchema_ID,C_Tax_ID);
return invoiceAcct;
}
} // InvoiceCreateInOut
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\FA\CreateInvoicedAsset.java
| 1
|
请完成以下Java代码
|
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getM_MovementConfirm_ID()));
}
/** Set Move Line Confirm.
@param M_MovementLineConfirm_ID
Inventory Move Line Confirmation
*/
public void setM_MovementLineConfirm_ID (int M_MovementLineConfirm_ID)
{
if (M_MovementLineConfirm_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_MovementLineConfirm_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_MovementLineConfirm_ID, Integer.valueOf(M_MovementLineConfirm_ID));
}
/** Get Move Line Confirm.
@return Inventory Move Line Confirmation
*/
public int getM_MovementLineConfirm_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementLineConfirm_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_MovementLine getM_MovementLine() throws RuntimeException
{
return (I_M_MovementLine)MTable.get(getCtx(), I_M_MovementLine.Table_Name)
.getPO(getM_MovementLine_ID(), get_TrxName()); }
/** Set Move Line.
@param M_MovementLine_ID
Inventory Move document Line
*/
public void setM_MovementLine_ID (int M_MovementLine_ID)
{
if (M_MovementLine_ID < 1)
set_Value (COLUMNNAME_M_MovementLine_ID, null);
else
set_Value (COLUMNNAME_M_MovementLine_ID, Integer.valueOf(M_MovementLine_ID));
}
/** Get Move Line.
@return Inventory Move document Line
*/
public int getM_MovementLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
|
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Scrapped Quantity.
@param ScrappedQty
The Quantity scrapped due to QA issues
*/
public void setScrappedQty (BigDecimal ScrappedQty)
{
set_Value (COLUMNNAME_ScrappedQty, ScrappedQty);
}
/** Get Scrapped Quantity.
@return The Quantity scrapped due to QA issues
*/
public BigDecimal getScrappedQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Target Quantity.
@param TargetQty
Target Movement Quantity
*/
public void setTargetQty (BigDecimal TargetQty)
{
set_Value (COLUMNNAME_TargetQty, TargetQty);
}
/** Get Target Quantity.
@return Target Movement Quantity
*/
public BigDecimal getTargetQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementLineConfirm.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Class<?> getObjectType() {
return MapReactiveUserDetailsService.class;
}
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.userDetails.setResourceLoader(resourceLoader);
}
/**
* Sets the location of a Resource that is a Properties file in the format defined in
* {@link UserDetailsResourceFactoryBean}.
* @param resourceLocation the location of the properties file that contains the users
* (i.e. "classpath:users.properties")
*/
public void setResourceLocation(String resourceLocation) {
this.userDetails.setResourceLocation(resourceLocation);
}
/**
* Sets a Resource that is a Properties file in the format defined in
* {@link UserDetailsResourceFactoryBean}.
* @param resource the Resource to use
*/
public void setResource(Resource resource) {
this.userDetails.setResource(resource);
}
/**
* Create a ReactiveUserDetailsServiceResourceFactoryBean with the location of a
* Resource that is a Properties file in the format defined in
* {@link UserDetailsResourceFactoryBean}.
* @param resourceLocation the location of the properties file that contains the users
* (i.e. "classpath:users.properties")
* @return the ReactiveUserDetailsServiceResourceFactoryBean
*/
public static ReactiveUserDetailsServiceResourceFactoryBean fromResourceLocation(String resourceLocation) {
ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean();
result.setResourceLocation(resourceLocation);
return result;
}
/**
* Create a ReactiveUserDetailsServiceResourceFactoryBean with a Resource that is a
* Properties file in the format defined in {@link UserDetailsResourceFactoryBean}.
* @param propertiesResource the Resource that is a properties file that contains the
* users
* @return the ReactiveUserDetailsServiceResourceFactoryBean
|
*/
public static ReactiveUserDetailsServiceResourceFactoryBean fromResource(Resource propertiesResource) {
ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean();
result.setResource(propertiesResource);
return result;
}
/**
* Create a ReactiveUserDetailsServiceResourceFactoryBean with a String that is in the
* format defined in {@link UserDetailsResourceFactoryBean}.
* @param users the users in the format defined in
* {@link UserDetailsResourceFactoryBean}
* @return the ReactiveUserDetailsServiceResourceFactoryBean
*/
public static ReactiveUserDetailsServiceResourceFactoryBean fromString(String users) {
ReactiveUserDetailsServiceResourceFactoryBean result = new ReactiveUserDetailsServiceResourceFactoryBean();
result.setResource(new InMemoryResource(users));
return result;
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\core\userdetails\ReactiveUserDetailsServiceResourceFactoryBean.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String ajaxPaymentList(HttpServletRequest request, @RequestBody JSONParam[] params) throws IllegalAccessException, InvocationTargetException {
// convertToMap定义于父类,将参数数组中的所有元素加入一个HashMap
HashMap<String, String> paramMap = convertToMap(params);
String sEcho = paramMap.get("sEcho");
int start = Integer.parseInt(paramMap.get("iDisplayStart"));
int length = Integer.parseInt(paramMap.get("iDisplayLength"));
String beginDate = paramMap.get("beginDate");
String endDate = paramMap.get("endDate");
if (StringUtil.isEmpty(beginDate) && !StringUtil.isEmpty(endDate)) {
beginDate = endDate;
}
if (StringUtil.isEmpty(endDate) && !StringUtil.isEmpty(beginDate)) {
endDate = beginDate;
}
String merchantRequestNo = paramMap.get("merchantRequestNo");
String status = paramMap.get("status");
RpUserInfo userInfo = (RpUserInfo) request.getSession().getAttribute(ConstantClass.USER);
// 页面当前页需要显示的记录数据
PageParam pageParam = new PageParam(start / length + 1, length);
Map<String, Object> settMap = new HashMap<String, Object>();
|
settMap.put("userNo", userInfo.getUserNo());
settMap.put("settStatus", status);
settMap.put("merchantRequestNo", merchantRequestNo);
settMap.put("beginDate", beginDate);
settMap.put("endDate", endDate);
PageBean pageBean = rpSettQueryService.querySettRecordListPage(pageParam, settMap);
Long count = Long.valueOf(pageBean.getTotalCount() + "");
String jsonString = JSON.toJSONString(pageBean.getRecordList());
String json = "{\"sEcho\":" + sEcho + ",\"iTotalRecords\":" + count.longValue() + ",\"iTotalDisplayRecords\":" + count.longValue() + ",\"aaData\":" + jsonString + "}";
return json;
}
}
|
repos\roncoo-pay-master\roncoo-pay-web-merchant\src\main\java\com\roncoo\pay\controller\sett\SettController.java
| 2
|
请完成以下Java代码
|
public static ScriptInfo parseScriptInfo(XMLStreamReader xtr) throws Exception {
boolean readyWithChildElements = false;
while (!readyWithChildElements && xtr.hasNext()) {
xtr.next();
if (xtr.isStartElement()) {
if (xtr.getLocalName().equals(CmmnXmlConstants.ELEMENT_SCRIPT)) {
return createScriptInfo(xtr);
}
} else if (xtr.isEndElement() && CmmnXmlConstants.ELEMENT_SCRIPT.equalsIgnoreCase(xtr.getLocalName())) {
readyWithChildElements = true;
}
}
return null;
}
protected static ScriptInfo createScriptInfo(XMLStreamReader xtr) throws Exception {
ScriptInfo script = new ScriptInfo();
|
CmmnXmlUtil.addXMLLocation(script, xtr);
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_SCRIPT_LANGUAGE))) {
script.setLanguage(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_SCRIPT_LANGUAGE));
}
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_SCRIPT_RESULTVARIABLE))) {
script.setResultVariable(xtr.getAttributeValue(null, CmmnXmlConstants.ATTRIBUTE_SCRIPT_RESULTVARIABLE));
}
String elementText = xtr.getElementText();
if (StringUtils.isNotEmpty(elementText)) {
script.setScript(elementText);
}
return script;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-converter\src\main\java\org\flowable\cmmn\converter\util\ListenerXmlConverterUtil.java
| 1
|
请完成以下Java代码
|
public int getM_ForecastLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ForecastLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_M_RequisitionLine getM_RequisitionLine() throws RuntimeException
{
return (I_M_RequisitionLine)MTable.get(getCtx(), I_M_RequisitionLine.Table_Name)
.getPO(getM_RequisitionLine_ID(), get_TrxName()); }
/** Set Requisition Line.
@param M_RequisitionLine_ID
Material Requisition Line
*/
public void setM_RequisitionLine_ID (int M_RequisitionLine_ID)
{
if (M_RequisitionLine_ID < 1)
set_Value (COLUMNNAME_M_RequisitionLine_ID, null);
|
else
set_Value (COLUMNNAME_M_RequisitionLine_ID, Integer.valueOf(M_RequisitionLine_ID));
}
/** Get Requisition Line.
@return Material Requisition Line
*/
public int getM_RequisitionLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_RequisitionLine_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_M_DemandDetail.java
| 1
|
请完成以下Java代码
|
public void setName(String name) {
this.name = name;
}
public NameAgeEntity getAge() {
return age;
}
public void setAge(NameAgeEntity age) {
this.age = age;
}
public NameCountriesEntity getCountries() {
return countries;
}
public void setCountries(NameCountriesEntity countries) {
this.countries = countries;
}
public NameGenderEntity getGender() {
return gender;
}
public void setGender(NameGenderEntity gender) {
this.gender = gender;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((age == null) ? 0 : age.hashCode());
result = prime * result + ((countries == null) ? 0 : countries.hashCode());
result = prime * result + ((gender == null) ? 0 : gender.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
NameAnalysisEntity other = (NameAnalysisEntity) obj;
|
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (age == null) {
if (other.age != null)
return false;
} else if (!age.equals(other.age))
return false;
if (countries == null) {
if (other.countries != null)
return false;
} else if (!countries.equals(other.countries))
return false;
if (gender == null) {
if (other.gender != null)
return false;
} else if (!gender.equals(other.gender))
return false;
return true;
}
@Override
public String toString() {
return "NameAnalysisEntity [name=" + name + ", age=" + age + ", countries=" + countries + ", gender=" + gender + "]";
}
}
|
repos\tutorials-master\spring-web-modules\spring-thymeleaf-attributes\accessing-session-attributes\src\main\java\com\baeldung\accesing_session_attributes\business\entities\NameAnalysisEntity.java
| 1
|
请完成以下Java代码
|
private FilterSql.RecordsToAlwaysIncludeSql toAlwaysIncludeSql(final @NonNull Set<HuId> alwaysIncludeHUIds)
{
return !alwaysIncludeHUIds.isEmpty()
? FilterSql.RecordsToAlwaysIncludeSql.ofColumnNameAndRecordIds(I_M_HU.COLUMNNAME_M_HU_ID, alwaysIncludeHUIds)
: null;
}
private IHUQueryBuilder newHUQuery()
{
return handlingUnitsDAO()
.createHUQueryBuilder()
.setContext(PlainContextAware.newOutOfTrx())
.setOnlyActiveHUs(false) // let other enforce this rule
.setOnlyTopLevelHUs(false); // let other enforce this rule
}
private SqlAndParams toSql(@NonNull final IHUQueryBuilder huQuery)
{
final ISqlQueryFilter sqlQueryFilter = ISqlQueryFilter.cast(huQuery.createQueryFilter());
return SqlAndParams.of(
sqlQueryFilter.getSql(),
sqlQueryFilter.getSqlParams(Env.getCtx()));
}
@Override
public FilterSql acceptAll() {return FilterSql.ALLOW_ALL;}
@Override
public FilterSql acceptAllBut(@NonNull final Set<HuId> alwaysIncludeHUIds, @NonNull final Set<HuId> excludeHUIds)
{
final SqlAndParams whereClause = !excludeHUIds.isEmpty()
? toSql(newHUQuery().addHUIdsToExclude(excludeHUIds))
: null;
|
return FilterSql.builder()
.whereClause(whereClause)
.alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds))
.build();
}
@Override
public FilterSql acceptNone() {return FilterSql.ALLOW_NONE;}
@Override
public FilterSql acceptOnly(@NonNull final HuIdsFilterList fixedHUIds, @NonNull final Set<HuId> alwaysIncludeHUIds)
{
final SqlAndParams whereClause = fixedHUIds.isNone()
? FilterSql.ALLOW_NONE.getWhereClause()
: toSql(newHUQuery().addOnlyHUIds(fixedHUIds.toSet()));
return FilterSql.builder()
.whereClause(whereClause)
.alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds))
.build();
}
@Override
public FilterSql huQuery(final @NonNull IHUQueryBuilder initialHUQueryCopy, final @NonNull Set<HuId> alwaysIncludeHUIds, final @NonNull Set<HuId> excludeHUIds)
{
initialHUQueryCopy.setContext(PlainContextAware.newOutOfTrx());
initialHUQueryCopy.addHUIdsToAlwaysInclude(alwaysIncludeHUIds);
initialHUQueryCopy.addHUIdsToExclude(excludeHUIds);
return FilterSql.builder()
.whereClause(toSql(initialHUQueryCopy))
.alwaysIncludeSql(toAlwaysIncludeSql(alwaysIncludeHUIds))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterDataToSqlCaseConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static IDeviceConfigPool of(@NonNull final Collection<IDeviceConfigPool> pools)
{
Check.assumeNotEmpty(pools, "pools is not empty");
if (pools.size() == 1)
{
return pools.iterator().next();
}
else
{
return new CompositeDeviceConfigPool(pools);
}
}
public static IDeviceConfigPool compose(
@NonNull final IDeviceConfigPool pool1,
@NonNull final IDeviceConfigPool pool2)
{
return new CompositeDeviceConfigPool(ImmutableList.of(pool1, pool2));
}
private final ImmutableList<IDeviceConfigPool> pools;
private CompositeDeviceConfigPool(@NonNull final Collection<IDeviceConfigPool> pools)
{
this.pools = ImmutableList.copyOf(pools);
}
@Override
public void addListener(@NonNull final IDeviceConfigPoolListener listener)
{
pools.forEach(pool -> pool.addListener(listener));
}
|
@Override
public Set<AttributeCode> getAllAttributeCodes()
{
return pools.stream()
.flatMap(pool -> pool.getAllAttributeCodes().stream())
.collect(ImmutableSet.toImmutableSet());
}
@Override
public List<DeviceConfig> getDeviceConfigsForAttributeCode(@NonNull final AttributeCode attributeCode)
{
return pools.stream()
.flatMap(pool -> pool.getDeviceConfigsForAttributeCode(attributeCode).stream())
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\config\CompositeDeviceConfigPool.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
static boolean isRecordIdColumnName(@Nullable final String columnName)
{
if (columnName == null)
{
// should not happen
return false;
}
// name must end with "Record_ID"
if (!columnName.endsWith(ITableRecordReference.COLUMNNAME_Record_ID))
{
return false;
}
// classical case
if (columnName.equals(ITableRecordReference.COLUMNNAME_Record_ID))
{
return true;
}
// Column name must end with "_Record_ID"
return columnName.endsWith("_" + ITableRecordReference.COLUMNNAME_Record_ID);
}
/**
* Get the primary key column for the given <code>tableName</code>.
* The difference to {@link InterfaceWrapperHelper#getKeyColumnName(String)} is that
* <li>this method shall return the "real" column name from {@link org.compiere.model.POInfo} and
* <li>that it shall throw an exception if there are more or less than one key column and finally
* <li>that the key column name might not be made up of <code>tablename + "_ID"</code>, but whatever is declared to be the key or single parent column in the application dictionary.
*
* @param tableName
* @return
|
* @throws org.adempiere.ad.table.exception.NoSingleKeyColumnException if the given table does not have exactly one key column.
*/
String getSingleKeyColumn(String tableName);
/**
* For the given <code>tableName</code> and <code>recordColumnName</code>, return the name of the column that contains the respective <code>AD_Table_ID</code>.
* Do not fail if this column can't be found.
*
* @param tableName
* @param recordColumnName
* @return
*/
Optional<String> getTableIdColumnName(String tableName, String recordColumnName);
boolean getDefaultAllowLoggingByColumnName(String columnName);
boolean getDefaultIsCalculatedByColumnName(String columnName);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\service\IColumnBL.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void bulkUpdateJobLockWithoutRevisionCheck(List<JobEntity> jobEntities, String lockOwner, Date lockExpirationTime) {
Map<String, Object> params = new HashMap<>(3);
params.put("lockOwner", lockOwner);
params.put("lockExpirationTime", lockExpirationTime);
bulkUpdateEntities("updateJobLocks", params, "jobs", jobEntities);
}
@Override
public void resetExpiredJob(String jobId) {
Map<String, Object> params = new HashMap<>(2);
params.put("id", jobId);
params.put("now", jobServiceConfiguration.getClock().getCurrentTime());
getDbSqlSession().directUpdate("resetExpiredJob", params);
}
|
@Override
public void deleteJobsByExecutionId(String executionId) {
DbSqlSession dbSqlSession = getDbSqlSession();
if (isEntityInserted(dbSqlSession, "execution", executionId)) {
deleteCachedEntities(dbSqlSession, jobsByExecutionIdMatcher, executionId);
} else {
bulkDelete("deleteJobsByExecutionId", jobsByExecutionIdMatcher, executionId);
}
}
@Override
protected IdGenerator getIdGenerator() {
return jobServiceConfiguration.getIdGenerator();
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\persistence\entity\data\impl\MybatisJobDataManager.java
| 2
|
请完成以下Java代码
|
public String getAttendType() {
return attendType;
}
public void setAttendType(String attendType) {
this.attendType = attendType;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", categoryId=").append(categoryId);
|
sb.append(", name=").append(name);
sb.append(", createTime=").append(createTime);
sb.append(", startTime=").append(startTime);
sb.append(", endTime=").append(endTime);
sb.append(", attendCount=").append(attendCount);
sb.append(", attentionCount=").append(attentionCount);
sb.append(", readCount=").append(readCount);
sb.append(", awardName=").append(awardName);
sb.append(", attendType=").append(attendType);
sb.append(", content=").append(content);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsTopic.java
| 1
|
请完成以下Java代码
|
public class MailTaskJsonConverter extends BaseBpmnJsonConverter {
public static void fillTypes(
Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap,
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {
fillJsonTypes(convertersToBpmnMap);
fillBpmnTypes(convertersToJsonMap);
}
public static void fillJsonTypes(Map<String, Class<? extends BaseBpmnJsonConverter>> convertersToBpmnMap) {
convertersToBpmnMap.put(STENCIL_TASK_MAIL, MailTaskJsonConverter.class);
}
public static void fillBpmnTypes(
Map<Class<? extends BaseElement>, Class<? extends BaseBpmnJsonConverter>> convertersToJsonMap
) {
// will be handled by ServiceTaskJsonConverter
}
protected String getStencilId(BaseElement baseElement) {
return STENCIL_TASK_MAIL;
}
protected void convertElementToJson(ObjectNode propertiesNode, BaseElement baseElement) {
// will be handled by ServiceTaskJsonConverter
}
protected FlowElement convertJsonToElement(
JsonNode elementNode,
JsonNode modelNode,
Map<String, JsonNode> shapeMap
|
) {
ServiceTask task = new ServiceTask();
task.setType(ServiceTask.MAIL_TASK);
addField(PROPERTY_MAILTASK_TO, elementNode, task);
addField(PROPERTY_MAILTASK_FROM, elementNode, task);
addField(PROPERTY_MAILTASK_SUBJECT, elementNode, task);
addField(PROPERTY_MAILTASK_CC, elementNode, task);
addField(PROPERTY_MAILTASK_BCC, elementNode, task);
addField(PROPERTY_MAILTASK_TEXT, elementNode, task);
addField(PROPERTY_MAILTASK_HTML, elementNode, task);
addField(PROPERTY_MAILTASK_CHARSET, elementNode, task);
return task;
}
}
|
repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\MailTaskJsonConverter.java
| 1
|
请完成以下Java代码
|
public int getNetDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NetDays);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Quantity.
@param Qty
Quantity
*/
|
public void setQty (int Qty)
{
set_Value (COLUMNNAME_Qty, Integer.valueOf(Qty));
}
/** Get Quantity.
@return Quantity
*/
public int getQty ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Qty);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Start Date.
@param StartDate
First effective day (inclusive)
*/
public void setStartDate (Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
/** Get Start Date.
@return First effective day (inclusive)
*/
public Timestamp getStartDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StartDate);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Year.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public AuthorizationManagerRequestMatcherRegistry rememberMe() {
return access(this.authorizationManagerFactory.rememberMe());
}
/**
* Specify that URLs are allowed by anonymous users.
* @return the {@link AuthorizationManagerRequestMatcherRegistry} for further
* customization
* @since 5.8
*/
public AuthorizationManagerRequestMatcherRegistry anonymous() {
return access(this.authorizationManagerFactory.anonymous());
}
/**
* Specify that a path variable in URL to be compared.
*
* <p>
* For example, <pre>
* requestMatchers("/user/{username}").hasVariable("username").equalTo(Authentication::getName)
* </pre>
* @param variable the variable in URL template to compare.
* @return {@link AuthorizedUrlVariable} for further customization.
* @since 6.3
*/
public AuthorizedUrlVariable hasVariable(String variable) {
return new AuthorizedUrlVariable(variable);
}
/**
* Allows specifying a custom {@link AuthorizationManager}.
* @param manager the {@link AuthorizationManager} to use
* @return the {@link AuthorizationManagerRequestMatcherRegistry} for further
* customizations
*/
public AuthorizationManagerRequestMatcherRegistry access(
AuthorizationManager<? super RequestAuthorizationContext> manager) {
Assert.notNull(manager, "manager cannot be null");
return (this.not)
? AuthorizeHttpRequestsConfigurer.this.addMapping(this.matchers, AuthorizationManagers.not(manager))
: AuthorizeHttpRequestsConfigurer.this.addMapping(this.matchers, manager);
}
/**
* An object that allows configuring {@link RequestMatcher}s with URI path
* variables
*
* @author Taehong Kim
|
* @since 6.3
*/
public final class AuthorizedUrlVariable {
private final String variable;
private AuthorizedUrlVariable(String variable) {
this.variable = variable;
}
/**
* Compares the value of a path variable in the URI with an `Authentication`
* attribute
* <p>
* For example, <pre>
* requestMatchers("/user/{username}").hasVariable("username").equalTo(Authentication::getName));
* </pre>
* @param function a function to get value from {@link Authentication}.
* @return the {@link AuthorizationManagerRequestMatcherRegistry} for further
* customization.
*/
public AuthorizationManagerRequestMatcherRegistry equalTo(Function<Authentication, String> function) {
return access((auth, requestContext) -> {
String value = requestContext.getVariables().get(this.variable);
return new AuthorizationDecision(function.apply(auth.get()).equals(value));
});
}
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\AuthorizeHttpRequestsConfigurer.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setMetadataFilename(String metadataFilename) {
Assert.hasText(metadataFilename, "metadataFilename cannot be empty");
Assert.isTrue(metadataFilename.contains("{registrationId}"),
"metadataFilename must contain a {registrationId} match variable");
Assert.isInstanceOf(Saml2MetadataResponseResolverAdapter.class, this.metadataResolver,
"a Saml2MetadataResponseResolver and file name cannot be both set on this filter. Please set the file name on the Saml2MetadataResponseResolver itself.");
((Saml2MetadataResponseResolverAdapter) this.metadataResolver).setMetadataFilename(metadataFilename);
}
private static final class Saml2MetadataResponseResolverAdapter implements Saml2MetadataResponseResolver {
private final RelyingPartyRegistrationResolver registrations;
private RequestMatcher requestMatcher = PathPatternRequestMatcher.withDefaults()
.matcher("/saml2/service-provider-metadata/{registrationId}");
private final Saml2MetadataResolver metadataResolver;
private String metadataFilename = DEFAULT_METADATA_FILE_NAME;
Saml2MetadataResponseResolverAdapter(RelyingPartyRegistrationResolver registrations,
Saml2MetadataResolver metadataResolver) {
this.registrations = registrations;
this.metadataResolver = metadataResolver;
}
@Override
public Saml2MetadataResponse resolve(HttpServletRequest request) {
RequestMatcher.MatchResult matcher = this.requestMatcher.matcher(request);
if (!matcher.isMatch()) {
return null;
}
String registrationId = matcher.getVariables().get("registrationId");
RelyingPartyRegistration relyingPartyRegistration = this.registrations.resolve(request, registrationId);
if (relyingPartyRegistration == null) {
throw new Saml2Exception("registration not found");
}
|
registrationId = relyingPartyRegistration.getRegistrationId();
String metadata = this.metadataResolver.resolve(relyingPartyRegistration);
String fileName = this.metadataFilename.replace("{registrationId}", registrationId);
return new Saml2MetadataResponse(metadata, fileName);
}
void setRequestMatcher(RequestMatcher requestMatcher) {
Assert.notNull(requestMatcher, "requestMatcher cannot be null");
this.requestMatcher = requestMatcher;
}
void setMetadataFilename(String metadataFilename) {
Assert.hasText(metadataFilename, "metadataFilename cannot be empty");
Assert.isTrue(metadataFilename.contains("{registrationId}"),
"metadataFilename must contain a {registrationId} match variable");
this.metadataFilename = metadataFilename;
}
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\Saml2MetadataFilter.java
| 2
|
请完成以下Java代码
|
private static AddressDisplaySequence getAddressDisplaySequence(final PickingJobField field)
{
final String pattern = StringUtils.trimBlankToNull(field.getPattern());
if (pattern == null)
{
return null;
}
return AddressDisplaySequence.ofNullable(pattern);
}
private Optional<String> getRuestplatz(@NonNull final Context pickingJob)
{
final BPartnerLocationId deliveryLocationId = pickingJob.getDeliveryLocationId();
if (deliveryLocationId == null)
{
return Optional.empty();
}
return ruestplatzCache.computeIfAbsent(deliveryLocationId, this::retrieveRuestplatz);
}
private Optional<String> retrieveRuestplatz(final BPartnerLocationId deliveryLocationId)
{
return extractRuestplatz(bpartnerService.getBPartnerLocationByIdEvenInactive(deliveryLocationId));
}
private static Optional<String> extractRuestplatz(@Nullable final I_C_BPartner_Location location)
{
return Optional.ofNullable(location)
.map(I_C_BPartner_Location::getSetup_Place_No)
.map(StringUtils::trimBlankToNull);
}
@Nullable
private String getHandoverAddress(@NonNull final Context pickingJob, @Nullable AddressDisplaySequence displaySequence)
{
final BPartnerLocationId bpLocationId = pickingJob.getHandoverLocationIdWithFallback();
return bpLocationId != null
? renderedAddressProvider.getAddress(bpLocationId, displaySequence)
: null;
}
@Nullable
private String getDeliveryAddress(@NonNull final Context context, @Nullable AddressDisplaySequence displaySequence)
{
final BPartnerLocationId bpLocationId = context.getDeliveryLocationId();
|
return bpLocationId != null
? renderedAddressProvider.getAddress(bpLocationId, displaySequence)
: null;
}
@Value
@Builder
private static class Context
{
@Nullable String salesOrderDocumentNo;
@Nullable String customerName;
@Nullable ZonedDateTime preparationDate;
@Nullable BPartnerLocationId deliveryLocationId;
@Nullable BPartnerLocationId handoverLocationId;
@Nullable ITranslatableString productName;
@Nullable Quantity qtyToDeliver;
@Nullable
public BPartnerLocationId getHandoverLocationIdWithFallback()
{
return handoverLocationId != null ? handoverLocationId : deliveryLocationId;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.picking.rest-api\src\main\java\de\metas\picking\workflow\DisplayValueProvider.java
| 1
|
请完成以下Java代码
|
public static final class Builder
{
private final Map<ArrayKey, DocTypeSequence> docTypeSequences = new HashMap<>();
private DocSequenceId defaultDocNoSequenceId = null;
private Builder()
{
}
public DocTypeSequenceMap build()
{
return new DocTypeSequenceMap(this);
}
public void addDocSequenceId(final ClientId adClientId, final OrgId adOrgId, final DocSequenceId docSequenceId)
{
final DocTypeSequence docTypeSequence = new DocTypeSequence(adClientId, adOrgId, docSequenceId);
final ArrayKey key = mkKey(docTypeSequence.getAdClientId(), docTypeSequence.getAdOrgId());
docTypeSequences.put(key, docTypeSequence);
}
public Builder defaultDocNoSequenceId(final DocSequenceId defaultDocNoSequenceId)
{
this.defaultDocNoSequenceId = defaultDocNoSequenceId;
return this;
}
}
@Value
|
private static final class DocTypeSequence
{
private final ClientId adClientId;
private final OrgId adOrgId;
private final DocSequenceId docSequenceId;
private DocTypeSequence(
@Nullable final ClientId adClientId,
@Nullable final OrgId adOrgId,
@NonNull final DocSequenceId docSequenceId)
{
this.adClientId = adClientId != null ? adClientId : ClientId.SYSTEM;
this.adOrgId = adOrgId != null ? adOrgId : OrgId.ANY;
this.docSequenceId = docSequenceId;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\DocTypeSequenceMap.java
| 1
|
请完成以下Java代码
|
private void setAdditionalContactFields(
@NonNull final JsonCustomerBuilder customerBuilder,
@NonNull final OrderAndLineId orderAndLineId)
{
final I_C_Order orderRecord = orderDAO.getById(orderAndLineId.getOrderId());
customerBuilder
.contactEmail(orderRecord.getEMail())
.contactName(orderRecord.getBPartnerName())
.contactPhone(orderRecord.getPhone());
logger.debug("Exporting effective contactEmail={}, contactName={}, contactPhone={} from the orderId={}",
orderRecord.getEMail(),
orderRecord.getBPartnerName(),
orderRecord.getPhone(),
orderAndLineId.getOrderId());
}
private void setAdditionalContactFields(
@NonNull final JsonCustomerBuilder customerBuilder,
@NonNull final BPartnerLocation bPartnerLocation)
{
customerBuilder
.contactEmail(bPartnerLocation.getEmail())
.contactName(bPartnerLocation.getBpartnerName())
.contactPhone(bPartnerLocation.getPhone());
logger.debug("Exporting effective contactEmail={}, contactName={}, contactPhone={} from the bPartnerLocationId={}",
bPartnerLocation.getEmail(),
bPartnerLocation.getBpartnerName(),
bPartnerLocation.getPhone(),
bPartnerLocation.getId());
}
|
private void setAdditionalContactFieldsForOxidOrder(
@NonNull final ShipmentSchedule shipmentSchedule,
@NonNull final BPartnerComposite composite,
@NonNull final JsonCustomerBuilder customerBuilder,
@Nullable final BPartnerContactId contactId)
{
if (contactId == null)
{
return;
}
final BPartnerContact contact = composite.extractContact(contactId)
.orElseThrow(() -> new ShipmentCandidateExportException("Unable to get the contact info from bPartnerComposite!")
.appendParametersToMessage()
.setParameter("composite.C_BPartner_ID", composite.getBpartner().getId())
.setParameter("AD_User_ID", contactId));
customerBuilder
.contactEmail(oxidAdaptor.getContactEmail(shipmentSchedule, composite))
.contactName(contact.getName())
.contactPhone(contact.getPhone());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\shipping\ShipmentCandidateAPIService.java
| 1
|
请完成以下Java代码
|
public final class DocumentDescriptor implements ETagAware
{
public static Builder builder()
{
return new Builder();
}
private final DocumentLayoutDescriptor layout;
private final DocumentEntityDescriptor entityDescriptor;
// ETag support
private static final Supplier<ETag> nextETagSupplier = ETagAware.newETagGenerator();
private final ETag eTag = nextETagSupplier.get();
private DocumentDescriptor(final Builder builder)
{
layout = Preconditions.checkNotNull(builder.layout, "layout not null");
entityDescriptor = Preconditions.checkNotNull(builder.entityDescriptor, "entityDescriptor not null");
}
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.add("entity", entityDescriptor)
.add("layout", layout)
.add("eTag", eTag)
.toString();
}
public DocumentLayoutDescriptor getLayout()
{
return layout;
}
public ViewLayout getViewLayout(final JSONViewDataType viewDataType)
{
switch (viewDataType)
{
case grid:
{
return layout.getGridViewLayout();
}
case list:
{
return layout.getSideListViewLayout();
}
|
default:
{
throw new IllegalArgumentException("Invalid viewDataType: " + viewDataType);
}
}
}
public DocumentEntityDescriptor getEntityDescriptor()
{
return entityDescriptor;
}
@Override
public ETag getETag()
{
return eTag;
}
//
public static final class Builder
{
private DocumentLayoutDescriptor layout;
private DocumentEntityDescriptor entityDescriptor;
private Builder()
{
}
public DocumentDescriptor build()
{
return new DocumentDescriptor(this);
}
public Builder setLayout(final DocumentLayoutDescriptor layout)
{
this.layout = layout;
return this;
}
public Builder setEntityDescriptor(final DocumentEntityDescriptor entityDescriptor)
{
this.entityDescriptor = entityDescriptor;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentDescriptor.java
| 1
|
请完成以下Java代码
|
public class Outer {
// Static Nested class
static class StaticNested {
public String message() {
return "This is a static Nested Class";
}
}
// Non-static Nested class
class Nested {
public String message() {
return "This is a non-static Nested Class";
}
}
// Local class
public String message() {
class Local {
private String message() {
return "This is a Local Class within a method";
}
}
Local local = new Local();
return local.message();
}
// Local class within if clause
public String message(String name) {
if (StringUtils.isEmpty(name)) {
class Local {
private String message() {
return "This is a Local Class within if clause";
}
}
Local local = new Local();
return local.message();
} else
return "Welcome to " + name;
}
// Anonymous Inner class extending a class
public String greet() {
Outer anonymous = new Outer() {
@Override
public String greet() {
return "Running Anonymous Class...";
}
};
return anonymous.greet();
}
// Anonymous inner class implementing an interface
public String greet(String name) {
HelloWorld helloWorld = new HelloWorld() {
@Override
public String greet(String name) {
return "Welcome to " + name;
}
};
return helloWorld.greet(name);
}
// Anonymous inner class implementing nested interface
public String greetSomeone(String name) {
HelloSomeone helloSomeOne = new HelloSomeone() {
@Override
public String greet(String name) {
return "Hello " + name;
}
};
return helloSomeOne.greet(name);
|
}
// Nested interface within a class
interface HelloOuter {
public String hello(String name);
}
// Enum within a class
enum Color {
RED, GREEN, BLUE;
}
}
interface HelloWorld {
public String greet(String name);
// Nested class within an interface
class InnerClass implements HelloWorld {
@Override
public String greet(String name) {
return "Inner class within an interface";
}
}
// Nested interface within an interfaces
interface HelloSomeone {
public String greet(String name);
}
// Enum within an interface
enum Directon {
NORTH, SOUTH, EAST, WEST;
}
}
enum Level {
LOW, MEDIUM, HIGH;
}
enum Foods {
DRINKS, EATS;
// Enum within Enum
enum DRINKS {
APPLE_JUICE, COLA;
}
enum EATS {
POTATO, RICE;
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-types-3\src\main\java\com\baeldung\classfile\Outer.java
| 1
|
请完成以下Java代码
|
public String getExporterVersion() {
return exporterVersion;
}
public void setExporterVersion(String exporterVersion) {
this.exporterVersion = exporterVersion;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Date getCreationDate() {
return creationDate;
}
public void setCreationDate(Date creationDate) {
this.creationDate = creationDate;
}
public List<Case> getCases() {
return cases;
}
public void setCases(List<Case> cases) {
this.cases = cases;
}
public List<Process> getProcesses() {
return processes;
}
public void setProcesses(List<Process> processes) {
this.processes = processes;
}
public List<Association> getAssociations() {
return associations;
}
public void setAssociations(List<Association> associations) {
this.associations = associations;
}
public List<TextAnnotation> getTextAnnotations() {
return textAnnotations;
}
public void setTextAnnotations(List<TextAnnotation> textAnnotations) {
this.textAnnotations = textAnnotations;
}
public void addNamespace(String prefix, String uri) {
namespaceMap.put(prefix, uri);
|
}
public boolean containsNamespacePrefix(String prefix) {
return namespaceMap.containsKey(prefix);
}
public String getNamespace(String prefix) {
return namespaceMap.get(prefix);
}
public Map<String, String> getNamespaces() {
return namespaceMap;
}
public Map<String, List<ExtensionAttribute>> getDefinitionsAttributes() {
return definitionsAttributes;
}
public String getDefinitionsAttributeValue(String namespace, String name) {
List<ExtensionAttribute> attributes = getDefinitionsAttributes().get(name);
if (attributes != null && !attributes.isEmpty()) {
for (ExtensionAttribute attribute : attributes) {
if (namespace.equals(attribute.getNamespace())) {
return attribute.getValue();
}
}
}
return null;
}
public void addDefinitionsAttribute(ExtensionAttribute attribute) {
if (attribute != null && StringUtils.isNotEmpty(attribute.getName())) {
List<ExtensionAttribute> attributeList = null;
if (!this.definitionsAttributes.containsKey(attribute.getName())) {
attributeList = new ArrayList<>();
this.definitionsAttributes.put(attribute.getName(), attributeList);
}
this.definitionsAttributes.get(attribute.getName()).add(attribute);
}
}
public void setDefinitionsAttributes(Map<String, List<ExtensionAttribute>> attributes) {
this.definitionsAttributes = attributes;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-model\src\main\java\org\flowable\cmmn\model\CmmnModel.java
| 1
|
请完成以下Java代码
|
private IQueryBuilder<I_C_Invoice_Candidate> createICQueryBuilder(final IQueryFilter<I_C_Invoice_Candidate> userSelectionFilter)
{
final IQueryBuilder<I_C_Invoice_Candidate> queryBuilder = Services.get(IQueryBL.class)
.createQueryBuilder(I_C_Invoice_Candidate.class, getCtx(), ITrx.TRXNAME_None)
.filter(userSelectionFilter)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient()
//
// NOTE: we are not filtering by IsToClear, Processed etc
// because we want to allow the enqueuer do do that
// because enqueuer will also log an message about why it was excluded (=> transparant for user)
// .addEqualsFilter(I_C_Invoice_Candidate.COLUMN_IsToClear, false)
// .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_Processed, false) not filtering by processed, because the IC might be invalid (08343)
// .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_IsError, false)
// .addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_IsInDispute, false)
//
;
//
// Consider only approved invoices (if we were asked to do so)
if (invoicingParams != null && invoicingParams.isOnlyApprovedForInvoicing())
{
queryBuilder.addEqualsFilter(I_C_Invoice_Candidate.COLUMNNAME_ApprovalForInvoicing, true);
|
}
return queryBuilder;
}
@Nullable
private ProcessCaptionMapper processCaptionMapper(final IQueryFilter<I_C_Invoice_Candidate> selectionFilter)
{
final IQuery<I_C_Invoice_Candidate> query = prepareNetAmountsToInvoiceForSelectionQuery(selectionFilter);
return processCaptionMapperHelper.getProcessCaptionMapperForNetAmountsFromQuery(query);
}
private IQuery<I_C_Invoice_Candidate> prepareNetAmountsToInvoiceForSelectionQuery(final IQueryFilter<I_C_Invoice_Candidate> selectionFilter)
{
return createICQueryBuilder(selectionFilter)
.addNotNull(I_C_Invoice_Candidate.COLUMNNAME_C_Currency_ID)
.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\process\C_Invoice_Candidate_EnqueueSelectionForInvoicing.java
| 1
|
请完成以下Java代码
|
public base setTarget (String target)
{
addAttribute ("target", target);
return this;
}
/**
* Sets the lang="" and xml:lang="" attributes
*
* @param lang
* the lang="" and xml:lang="" attributes
*/
public Element setLang (String lang)
{
addAttribute ("lang", lang);
addAttribute ("xml:lang", lang);
return this;
}
/**
* Adds an Element to the element.
*
* @param hashcode
* name of element for hash table
* @param element
* Adds an Element to the element.
*/
public base addElement (String hashcode, Element element)
{
addElementToRegistry (hashcode, element);
return (this);
}
/**
* Adds an Element to the element.
*
* @param hashcode
* name of element for hash table
* @param element
* Adds an Element to the element.
*/
public base addElement (String hashcode, String element)
{
addElementToRegistry (hashcode, element);
return (this);
}
/**
* Adds an Element to the element.
*
* @param element
* Adds an Element to the element.
|
*/
public base addElement (Element element)
{
addElementToRegistry (element);
return (this);
}
/**
* Adds an Element to the element.
*
* @param element
* Adds an Element to the element.
*/
public base addElement (String element)
{
addElementToRegistry (element);
return (this);
}
/**
* Removes an Element from the element.
*
* @param hashcode
* the name of the element to be removed.
*/
public base removeElement (String hashcode)
{
removeElementFromRegistry (hashcode);
return (this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\base.java
| 1
|
请完成以下Java代码
|
public Barcode getBarcode()
{
return m_barcode;
} // getBarcode
/**
* Is Barcode Valid
* @return true if valid
*/
public boolean isValid()
{
return m_valid;
} // isValid
/**
* Layout and Calculate Size
* Set p_width & p_height
* @return true if calculated
*/
protected boolean calculateSize ()
{
p_width = 0;
p_height = 0;
if (m_barcode == null)
return true;
p_width = m_barcode.getWidth();
p_height = m_barcode.getHeight();
if (p_width * p_height == 0)
return true; // don't bother scaling and prevent div by 0
m_scaleFactor = 1f;
if (p_maxWidth != 0 && p_width > p_maxWidth)
m_scaleFactor = p_maxWidth / p_width;
if (p_maxHeight != 0 && p_height > p_maxHeight && p_maxHeight/p_height < m_scaleFactor)
m_scaleFactor = p_maxHeight / p_height;
p_width = (float) m_scaleFactor * p_width;
p_height = (float) m_scaleFactor * p_height;
return true;
} // calculateSize
public float getScaleFactor() {
if (!p_sizeCalculated)
p_sizeCalculated = calculateSize();
return m_scaleFactor;
}
/**
* @author teo_sarca - [ 1673590 ] report table - barcode overflows over next fields
* @return can this element overflow over the next fields
*/
public boolean isAllowOverflow() { //
return m_allowOverflow;
}
/**
* Paint Element
* @param g2D graphics
* @param pageNo page no
* @param pageStart page start
* @param ctx context
* @param isView view
*/
public void paint (Graphics2D g2D, int pageNo, Point2D pageStart,
Properties ctx, boolean isView)
{
if (!m_valid || m_barcode == null)
return;
// Position
Point2D.Double location = getAbsoluteLocation(pageStart);
|
int x = (int)location.x;
if (MPrintFormatItem.FIELDALIGNMENTTYPE_TrailingRight.equals(p_FieldAlignmentType))
x += p_maxWidth - p_width;
else if (MPrintFormatItem.FIELDALIGNMENTTYPE_Center.equals(p_FieldAlignmentType))
x += (p_maxWidth - p_width) / 2;
int y = (int)location.y;
try {
int w = m_barcode.getWidth();
int h = m_barcode.getHeight();
// draw barcode to buffer
BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
Graphics2D temp = (Graphics2D) image.getGraphics();
m_barcode.draw(temp, 0, 0);
// scale barcode and paint
AffineTransform transform = new AffineTransform();
transform.translate(x,y);
transform.scale(m_scaleFactor, m_scaleFactor);
g2D.drawImage(image, transform, this);
} catch (OutputException e) {
}
} // paint
/**
* String Representation
* @return info
*/
public String toString ()
{
if (m_barcode == null)
return super.toString();
return super.toString() + " " + m_barcode.getData();
} // toString
} // BarcodeElement
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\BarcodeElement.java
| 1
|
请完成以下Java代码
|
public String getCamundaJobPriority() {
return camundaJobPriorityAttribute.getValue(this);
}
public void setCamundaJobPriority(String jobPriority) {
camundaJobPriorityAttribute.setValue(this, jobPriority);
}
@Override
public String getCamundaTaskPriority() {
return camundaTaskPriorityAttribute.getValue(this);
}
@Override
public void setCamundaTaskPriority(String taskPriority) {
camundaTaskPriorityAttribute.setValue(this, taskPriority);
}
@Override
public Integer getCamundaHistoryTimeToLive() {
String ttl = getCamundaHistoryTimeToLiveString();
if (ttl != null) {
return Integer.parseInt(ttl);
}
return null;
}
@Override
public void setCamundaHistoryTimeToLive(Integer historyTimeToLive) {
var value = historyTimeToLive == null ? null : String.valueOf(historyTimeToLive);
setCamundaHistoryTimeToLiveString(value);
}
@Override
public String getCamundaHistoryTimeToLiveString() {
return camundaHistoryTimeToLiveAttribute.getValue(this);
}
@Override
public void setCamundaHistoryTimeToLiveString(String historyTimeToLive) {
if (historyTimeToLive == null) {
|
camundaHistoryTimeToLiveAttribute.removeAttribute(this);
} else {
camundaHistoryTimeToLiveAttribute.setValue(this, historyTimeToLive);
}
}
@Override
public Boolean isCamundaStartableInTasklist() {
return camundaIsStartableInTasklistAttribute.getValue(this);
}
@Override
public void setCamundaIsStartableInTasklist(Boolean isStartableInTasklist) {
camundaIsStartableInTasklistAttribute.setValue(this, isStartableInTasklist);
}
@Override
public String getCamundaVersionTag() {
return camundaVersionTagAttribute.getValue(this);
}
@Override
public void setCamundaVersionTag(String versionTag) {
camundaVersionTagAttribute.setValue(this, versionTag);
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ProcessImpl.java
| 1
|
请完成以下Java代码
|
public void addCandidateStarterUser(String caseDefinitionId, String userId) {
commandExecutor.execute(new AddIdentityLinkForCaseDefinitionCmd(caseDefinitionId, userId, null, configuration));
}
@Override
public void addCandidateStarterGroup(String caseDefinitionId, String groupId) {
commandExecutor.execute(new AddIdentityLinkForCaseDefinitionCmd(caseDefinitionId, null, groupId, configuration));
}
@Override
public void deleteCandidateStarterGroup(String caseDefinitionId, String groupId) {
commandExecutor.execute(new DeleteIdentityLinkForCaseDefinitionCmd(caseDefinitionId, null, groupId));
}
@Override
public void deleteCandidateStarterUser(String caseDefinitionId, String userId) {
commandExecutor.execute(new DeleteIdentityLinkForCaseDefinitionCmd(caseDefinitionId, userId, null));
}
@Override
public List<IdentityLink> getIdentityLinksForCaseDefinition(String caseDefinitionId) {
return commandExecutor.execute(new GetIdentityLinksForCaseDefinitionCmd(caseDefinitionId));
}
@Override
public void setCaseDefinitionCategory(String caseDefinitionId, String category) {
commandExecutor.execute(new SetCaseDefinitionCategoryCmd(caseDefinitionId, category));
|
}
@Override
public void changeDeploymentParentDeploymentId(String deploymentId, String newParentDeploymentId) {
commandExecutor.execute(new SetDeploymentParentDeploymentIdCmd(deploymentId, newParentDeploymentId));
}
@Override
public List<DmnDecision> getDecisionsForCaseDefinition(String caseDefinitionId) {
return commandExecutor.execute(new GetDecisionsForCaseDefinitionCmd(caseDefinitionId));
}
@Override
public List<FormDefinition> getFormDefinitionsForCaseDefinition(String caseDefinitionId) {
return commandExecutor.execute(new GetFormDefinitionsForCaseDefinitionCmd(caseDefinitionId));
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\CmmnRepositoryServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getPassword() {
return user.getPassword();
}
@Override
@JSONField(serialize = false)
public String getUsername() {
return user.getUsername();
}
@JSONField(serialize = false)
@Override
public boolean isAccountNonExpired() {
return true;
}
@JSONField(serialize = false)
|
@Override
public boolean isAccountNonLocked() {
return true;
}
@JSONField(serialize = false)
@Override
public boolean isCredentialsNonExpired() {
return true;
}
@Override
@JSONField(serialize = false)
public boolean isEnabled() {
return user.getEnabled();
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\service\dto\JwtUserDto.java
| 2
|
请完成以下Java代码
|
public ValueType getParent() {
return null;
}
public boolean canConvertFromTypedValue(TypedValue typedValue) {
return false;
}
public TypedValue convertFromTypedValue(TypedValue typedValue) {
throw unsupportedConversion(typedValue.getType());
}
protected IllegalArgumentException unsupportedConversion(ValueType typeToConvertTo) {
return new IllegalArgumentException("The type " + getName() + " supports no conversion from type: " + typeToConvertTo.getName());
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
AbstractValueTypeImpl other = (AbstractValueTypeImpl) obj;
|
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
return true;
}
protected Boolean isTransient(Map<String, Object> valueInfo) {
if (valueInfo != null && valueInfo.containsKey(VALUE_INFO_TRANSIENT)) {
Object isTransient = valueInfo.get(VALUE_INFO_TRANSIENT);
if (isTransient instanceof Boolean) {
return (Boolean) isTransient;
} else {
throw new IllegalArgumentException("The property 'transient' should have a value of type 'boolean'.");
}
}
return false;
}
}
|
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\AbstractValueTypeImpl.java
| 1
|
请完成以下Java代码
|
public ExecutionResource getExecution(String executionId) {
return new ExecutionResourceImpl(getProcessEngine(), executionId, getObjectMapper());
}
@Override
public List<ExecutionDto> getExecutions(UriInfo uriInfo, Integer firstResult,
Integer maxResults) {
ExecutionQueryDto queryDto = new ExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryExecutions(queryDto, firstResult, maxResults);
}
@Override
public List<ExecutionDto> queryExecutions(
ExecutionQueryDto queryDto, Integer firstResult, Integer maxResults) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
ExecutionQuery query = queryDto.toQuery(engine);
List<Execution> matchingExecutions = QueryUtil.list(query, firstResult, maxResults);
List<ExecutionDto> executionResults = new ArrayList<ExecutionDto>();
for (Execution execution : matchingExecutions) {
ExecutionDto resultExecution = ExecutionDto.fromExecution(execution);
executionResults.add(resultExecution);
}
return executionResults;
}
@Override
public CountResultDto getExecutionsCount(UriInfo uriInfo) {
|
ExecutionQueryDto queryDto = new ExecutionQueryDto(getObjectMapper(), uriInfo.getQueryParameters());
return queryExecutionsCount(queryDto);
}
@Override
public CountResultDto queryExecutionsCount(ExecutionQueryDto queryDto) {
ProcessEngine engine = getProcessEngine();
queryDto.setObjectMapper(getObjectMapper());
ExecutionQuery query = queryDto.toQuery(engine);
long count = query.count();
CountResultDto result = new CountResultDto();
result.setCount(count);
return result;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\ExecutionRestServiceImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UniversalBankTransactionType {
@XmlElement(name = "BeneficiaryAccount")
protected List<AccountType> beneficiaryAccount;
@XmlElement(name = "PaymentReference")
protected String paymentReference;
@XmlAttribute(name = "ConsolidatorPayable", namespace = "http://erpel.at/schemas/1p0/documents")
protected Boolean consolidatorPayable;
/**
* The account of the beneficiary.Gets the value of the beneficiaryAccount property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the beneficiaryAccount property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getBeneficiaryAccount().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link AccountType }
*
*
*/
public List<AccountType> getBeneficiaryAccount() {
if (beneficiaryAccount == null) {
beneficiaryAccount = new ArrayList<AccountType>();
}
return this.beneficiaryAccount;
}
/**
* A payment reference which may be provided in order to allow for an automated processing of the payment.
*
* @return
* possible object is
* {@link String }
|
*
*/
public String getPaymentReference() {
return paymentReference;
}
/**
* Sets the value of the paymentReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPaymentReference(String value) {
this.paymentReference = value;
}
/**
* Indicates whether the payment is payable on a consolidator platform. In this case the attribute must be set to true.
*
* @return
* possible object is
* {@link Boolean }
*
*/
public Boolean isConsolidatorPayable() {
return consolidatorPayable;
}
/**
* Sets the value of the consolidatorPayable property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setConsolidatorPayable(Boolean value) {
this.consolidatorPayable = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\UniversalBankTransactionType.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public void setSwaggerOpen(Boolean swaggerOpen) {
this.swaggerOpen = swaggerOpen;
}
public Integer getSessionInvalidateTime() {
return sessionInvalidateTime;
}
public void setSessionInvalidateTime(Integer sessionInvalidateTime) {
this.sessionInvalidateTime = sessionInvalidateTime;
}
public Integer getSessionValidationInterval() {
return sessionValidationInterval;
}
public void setSessionValidationInterval(Integer sessionValidationInterval) {
this.sessionValidationInterval = sessionValidationInterval;
}
public String getFilesUrlPrefix() {
return filesUrlPrefix;
}
public void setFilesUrlPrefix(String filesUrlPrefix) {
this.filesUrlPrefix = filesUrlPrefix;
}
public String getFilesPath() {
return filesPath;
}
public void setFilesPath(String filesPath) {
this.filesPath = filesPath;
}
public Integer getHeartbeatTimeout() {
return heartbeatTimeout;
}
|
public void setHeartbeatTimeout(Integer heartbeatTimeout) {
this.heartbeatTimeout = heartbeatTimeout;
}
public String getPicsPath() {
return picsPath;
}
public void setPicsPath(String picsPath) {
this.picsPath = picsPath;
}
public String getPosapiUrlPrefix() {
return posapiUrlPrefix;
}
public void setPosapiUrlPrefix(String posapiUrlPrefix) {
this.posapiUrlPrefix = posapiUrlPrefix;
}
}
|
repos\SpringBootBucket-master\springboot-shiro\src\main\java\com\xncoding\pos\config\properties\MyProperties.java
| 2
|
请完成以下Java代码
|
private void createDD_OrderLine(final I_DD_Order ddOrder, final RawMaterialsReturnDDOrderLineCandidate candidate)
{
Check.assume(candidate.isValid(), "candidate is valid: {}", candidate);
final IAttributeSetInstanceAware attributeSetInstanceAware = candidate.getM_Product();
final Quantity qtyToMove = Quantity.of(candidate.getQty(), candidate.getC_UOM());
final DistributionNetworkLine networkLine = candidate.getDD_NetworkDistributionLine();
final I_M_Locator locatorFrom = candidate.getM_Locator();
final I_M_Locator locatorTo = candidate.getRawMaterialsLocator();
//
// Create DD Order Line
final I_DD_OrderLine ddOrderline = InterfaceWrapperHelper.newInstance(I_DD_OrderLine.class, ddOrder);
ddOrderline.setAD_Org_ID(ddOrder.getAD_Org_ID());
ddOrderline.setDD_Order(ddOrder);
// ddOrderline.setC_BPartner_ID(bpartnerId);
//
// Locator From/To
ddOrderline.setM_Locator_ID(locatorFrom.getM_Locator_ID());
ddOrderline.setM_LocatorTo_ID(locatorTo.getM_Locator_ID());
//
// Product, UOM, Qty
ddOrderline.setM_Product_ID(attributeSetInstanceAware.getM_Product_ID());
final I_M_AttributeSetInstance asi = attributeSetInstanceAware.getM_AttributeSetInstance();
ddOrderline.setM_AttributeSetInstance(attributeSetInstanceBL.copy(asi));
ddOrderline.setM_AttributeSetInstanceTo(attributeSetInstanceBL.copy(asi));
|
ddOrderline.setC_UOM_ID(qtyToMove.getUomId().getRepoId());
ddOrderline.setQtyEntered(qtyToMove.toBigDecimal());
ddOrderline.setQtyOrdered(qtyToMove.toBigDecimal());
ddOrderline.setTargetQty(qtyToMove.toBigDecimal());
//
// Dates
ddOrderline.setDateOrdered(ddOrder.getDateOrdered());
ddOrderline.setDatePromised(ddOrder.getDatePromised());
//
// Other flags
ddOrderline.setIsInvoiced(false);
ddOrderline.setDD_AllowPush(networkLine.isAllowPush());
ddOrderline.setIsKeepTargetPlant(networkLine.isKeepTargetPlant());
ddOrderLowLevelService.save(ddOrderline);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\de\metas\distribution\ddorder\process\DD_Order_GenerateRawMaterialsReturn.java
| 1
|
请完成以下Java代码
|
public Session getSession() {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", this.host);
props.put("mail.smtp.port", this.port);
return Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
public void sendMail(Session session) throws MessagingException, IOException {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("mail@gmail.com"));
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("mail@gmail.com"));
message.setSubject("Testing Subject");
BodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setText("This is message body");
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
MimeBodyPart attachmentPart = new MimeBodyPart();
attachmentPart.attachFile(getFile("attachment.txt"));
multipart.addBodyPart(attachmentPart);
MimeBodyPart attachmentPart2 = new MimeBodyPart();
attachmentPart2.attachFile(getFile("attachment2.txt"));
|
multipart.addBodyPart(attachmentPart2);
message.setContent(multipart);
Transport.send(message);
}
private File getFile(String filename) {
try {
URI uri = this.getClass()
.getClassLoader()
.getResource(filename)
.toURI();
return new File(uri);
} catch (Exception e) {
throw new IllegalArgumentException("Unable to find file from resources: " + filename);
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-networking-2\src\main\java\com\baeldung\mail\mailwithattachment\MailWithAttachmentService.java
| 1
|
请完成以下Java代码
|
public int getBill_User_ID()
{
return getC_Flatrate_Term().getBill_User_ID();
}
@Override
public int getC_Currency_ID()
{
return Services.get(IPriceListDAO.class).getById(PriceListId.ofRepoId(getM_PriceList_Version().getM_PriceList_ID())).getC_Currency_ID();
}
@Override
public CountryId getCountryId()
{
return CoalesceUtil.coalesceSuppliersNotNull(
// first, try the contract's location from the tine the contract was created
() -> {
final I_C_Location billLocationValue = getC_Flatrate_Term().getBill_Location_Value();
return billLocationValue != null ? CountryId.ofRepoId(billLocationValue.getC_Country_ID()) : null;
},
// second, try the current C_Location of the C_BPartner_Location
() -> {
final IBPartnerDAO bPartnerDAO = Services.get(IBPartnerDAO.class);
return bPartnerDAO.getCountryId(BPartnerLocationId.ofRepoId(getC_Flatrate_Term().getBill_BPartner_ID(), getC_Flatrate_Term().getBill_Location_ID()));
}
);
}
@Override
public I_M_PriceList_Version getM_PriceList_Version()
{
return _priceListVersion;
}
@Override
public PricingSystemId getPricingSystemId()
{
PricingSystemId pricingSystemId = _pricingSystemId;
if (pricingSystemId == null)
{
pricingSystemId = _pricingSystemId = PricingSystemId.ofRepoId(getC_Flatrate_Term().getM_PricingSystem_ID());
|
}
return pricingSystemId;
}
@Override
public I_C_Flatrate_Term getC_Flatrate_Term()
{
if (_flatrateTerm == null)
{
_flatrateTerm = Services.get(IFlatrateDAO.class).getById(materialTracking.getC_Flatrate_Term_ID());
// shouldn't be null because we prevent even material-tracking purchase orders without a flatrate term.
Check.errorIf(_flatrateTerm == null, "M_Material_Tracking {} has no flatrate term", materialTracking);
}
return _flatrateTerm;
}
@Override
public String getInvoiceRule()
{
if (!_invoiceRuleSet)
{
//
// Try getting the InvoiceRule from Flatrate Term
final I_C_Flatrate_Term flatrateTerm = getC_Flatrate_Term();
final String invoiceRule = flatrateTerm
.getC_Flatrate_Conditions()
.getInvoiceRule();
Check.assumeNotEmpty(invoiceRule, "Unable to retrieve invoiceRule from materialTracking {}", materialTracking);
_invoiceRule = invoiceRule;
_invoiceRuleSet = true;
}
return _invoiceRule;
}
/* package */void setM_PriceList_Version(final I_M_PriceList_Version priceListVersion)
{
_priceListVersion = priceListVersion;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingAsVendorInvoicingInfo.java
| 1
|
请完成以下Java代码
|
public final class TableName
{
private final String tableName;
private static final Interner<TableName> interner = Interners.newStrongInterner();
private TableName(@NonNull final String tableName)
{
final String tableNameNorm = StringUtils.trimBlankToNull(tableName);
if (tableNameNorm == null)
{
throw new AdempiereException("Invalid table name: `" + tableName + "`");
}
this.tableName = tableNameNorm;
}
public static TableName ofString(@NonNull final String string)
{
return interner.intern(new TableName(string));
}
@Nullable
public static TableName ofNullableString(@Nullable final String string)
{
final String stringNorm = StringUtils.trimBlankToNull(string);
return stringNorm != null
? ofString(stringNorm)
: null;
}
@Override
@Deprecated
public String toString()
|
{
return getAsString();
}
public String getAsString()
{
return tableName;
}
public boolean equalsIgnoreCase(@Nullable final String otherTableName)
{
return tableName.equalsIgnoreCase(otherTableName);
}
public static boolean equals(@Nullable TableName tableName1, @Nullable TableName tableName2)
{
return Objects.equals(tableName1, tableName2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\TableName.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SecurityConfig {
private final RequestHeaderAuthenticationProvider requestHeaderAuthenticationProvider;
@Value("${api.auth.header.name}")
private String apiAuthHeaderName;
@Autowired
public SecurityConfig( RequestHeaderAuthenticationProvider requestHeaderAuthenticationProvider){
this.requestHeaderAuthenticationProvider = requestHeaderAuthenticationProvider;
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.cors(Customizer.withDefaults()).csrf(AbstractHttpConfigurer::disable)
.sessionManagement(httpSecuritySessionManagementConfigurer -> httpSecuritySessionManagementConfigurer.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterAfter(requestHeaderAuthenticationFilter(), HeaderWriterFilter.class)
.authorizeHttpRequests(authorizationManagerRequestMatcherRegistry -> authorizationManagerRequestMatcherRegistry
.requestMatchers(HttpMethod.GET, "/health").permitAll()
.requestMatchers("/api/**").authenticated())
.exceptionHandling(httpSecurityExceptionHandlingConfigurer -> httpSecurityExceptionHandlingConfigurer
.authenticationEntryPoint((request, response, authException) ->
response.sendError(HttpServletResponse.SC_UNAUTHORIZED)));
return http.build();
|
}
@Bean
public RequestHeaderAuthenticationFilter requestHeaderAuthenticationFilter() {
RequestHeaderAuthenticationFilter filter = new RequestHeaderAuthenticationFilter();
filter.setPrincipalRequestHeader(apiAuthHeaderName);
filter.setExceptionIfHeaderMissing(false);
filter.setRequiresAuthenticationRequestMatcher(new AntPathRequestMatcher("/api/**"));
filter.setAuthenticationManager(authenticationManager());
return filter;
}
@Bean
protected AuthenticationManager authenticationManager() {
return new ProviderManager(Collections.singletonList(requestHeaderAuthenticationProvider));
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-5\src\main\java\com\baeldung\customauth\configuration\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public void save(@NonNull final I_M_AttributeInstance ai)
{
asiDAO.save(ai);
}
@Override
public Set<AttributeId> getAttributeIdsByAttributeSetInstanceId(@NonNull final AttributeSetInstanceId attributeSetInstanceId)
{
return asiDAO.getAttributeIdsByAttributeSetInstanceId(attributeSetInstanceId);
}
@Override
public AttributeSetInstanceId setInitialAttributes(
@NonNull final ProductId productId,
@NonNull final AttributeSetInstanceId asiId,
@NonNull final Evaluatee evalCtx)
{
final ImmutableList<Attribute> attributes = productBL.getAttributeSet(productId)
.getAttributesInOrder()
.stream()
.filter(Attribute::isDefaultValueSet)
.collect(ImmutableList.toImmutableList());
if (attributes.isEmpty())
{
return asiId;
}
final ImmutableAttributeSet existingASI = getImmutableAttributeSetById(asiId);
final ArrayList<CreateAttributeInstanceReq> attributesToInit = new ArrayList<>();
for (final Attribute attribute : attributes)
{
if (existingASI.isValueSet(attribute))
{
continue;
}
generateDefaultValue(attribute, evalCtx)
.ifPresent(defaultValue -> attributesToInit.add(
CreateAttributeInstanceReq.builder()
.attributeCode(attribute.getAttributeCode())
.value(Null.unbox(defaultValue))
.build()
));
}
if (attributesToInit.isEmpty()) {return AttributeSetInstanceId.NONE;}
return addAttributes(
AddAttributesRequest.builder()
.productId(productId)
.existingAttributeSetIdOrNone(AttributeSetInstanceId.NONE)
.attributeInstanceBasicInfos(attributesToInit)
.build()
);
}
private static Optional<Object> generateDefaultValue(final Attribute attribute, final Evaluatee evalCtx)
{
try
{
if (attribute.getDefaultValueSQL() != null)
{
final String defaultValueSQL = attribute.getDefaultValueSQL().evaluate(evalCtx, IExpressionEvaluator.OnVariableNotFound.Fail);
final Object defaultValue = attribute.getValueType().map(new AttributeValueType.CaseMapper<Object>()
{
@Override
|
public Object string()
{
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
@Override
public Object number()
{
return DB.getSQLValueBDEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
@Override
public Object date()
{
return DB.getSQLValueTSEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
@Override
public Object list()
{
// TODO: resolve the M_AttributeValue
return DB.getSQLValueStringEx(ITrx.TRXNAME_ThreadInherited, defaultValueSQL);
}
});
return Optional.of(Null.box(defaultValue));
}
else
{
return Optional.empty();
}
}
catch (Exception ex)
{
logger.warn("Failed generating default value for {}. Returning empty.", attribute, ex);
return Optional.empty();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\impl\AttributeSetInstanceBL.java
| 1
|
请完成以下Java代码
|
public boolean isWindow()
{
return windowId != null;
}
public boolean isProcess()
{
return processId != null;
}
public boolean isView()
{
return viewId != null;
}
public DocumentPath toSingleDocumentPath()
{
if (windowId != null)
{
return DocumentPath.singleWindowDocumentPath(windowId, documentId, tabId, rowId);
}
else if (processId != null)
{
return DocumentPath.rootDocumentPath(DocumentType.Process, processId.toDocumentId(), documentId);
}
else
{
throw new IllegalStateException("Cannot create single document path from " + this);
}
}
private DocumentPath toDocumentPath()
{
final DocumentPath.Builder builder = DocumentPath.builder();
// Window
if (windowId != null)
{
builder.setDocumentType(windowId);
}
|
// Process
else if (processId != null)
{
builder.setDocumentType(DocumentType.Process, processId.toDocumentId());
}
else
{
throw new AdempiereException("Cannot identify the document type because it's not window nor process")
.setParameter("documentPath", this);
}
return builder
.setDocumentId(documentId)
.setDetailId(tabId)
.setRowId(rowId)
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentPath.java
| 1
|
请完成以下Java代码
|
public String getFilename() {
return filename;
}
/**
* Sets the value of the filename property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setFilename(String value) {
this.filename = value;
}
/**
* Gets the value of the mimeType property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getMimeType() {
return mimeType;
|
}
/**
* Sets the value of the mimeType property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMimeType(String value) {
this.mimeType = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\DocumentType.java
| 1
|
请完成以下Java代码
|
public static KieContainer loadKieContainer() throws RuntimeException {
//通过kmodule.xml 找到规则文件,这个文件默认放在resources/META-INF文件夹
log.info("准备创建 KieContainer");
if (kieContainer == null) {
log.info("首次创建:KieContainer");
// 设置drools的日期格式
System.setProperty("drools.dateformat", "yyyy-MM-dd HH:mm:ss");
//线程安全
synchronized (DroolsUtil.class) {
if (kieContainer == null) {
// 创建Container
kieContainer = kieServices.getKieClasspathContainer();
// 检查规则文件是否有错
Results results = kieContainer.verify();
if (results.hasMessages(Message.Level.ERROR)) {
StringBuffer sb = new StringBuffer();
for (Message mes : results.getMessages()) {
sb.append("解析错误的规则:").append(mes.getPath()).append(" 错误位置:").append(mes.getLine()).append(";");
}
throw new RuntimeException(sb.toString());
}
}
}
}
|
log.info("KieContainer创建完毕");
return kieContainer;
}
/**
* 根据kiesession 名称创建KieSession ,每次调用都是一个新的KieSession
* @param name kiesession的名称
* @return 一个新的KieSession,每次使用后要销毁
*/
public static KieSession getKieSessionByName(String name) {
if (kieContainer == null) {
kieContainer = loadKieContainer();
}
KieSession kieSession;
try {
kieSession = kieContainer.newKieSession(name);
} catch (Exception e) {
log.error("根据名称:" + name + " 创建kiesession异常");
throw new RuntimeException(e);
}
return kieSession;
}
}
|
repos\spring-boot-student-master\spring-boot-student-drools\src\main\java\com\xiaolyuh\utils\DroolsUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserCacheManager {
@Resource
private RedisUtils redisUtils;
@Value("${login.user-cache.idle-time}")
private long idleTime;
/**
* 返回用户缓存
* @param userName 用户名
* @return JwtUserDto
*/
public JwtUserDto getUserCache(String userName) {
// 转小写
userName = StringUtils.lowerCase(userName);
if (StringUtils.isNotEmpty(userName)) {
// 获取数据
return redisUtils.get(LoginProperties.cacheKey + userName, JwtUserDto.class);
}
return null;
}
/**
* 添加缓存到Redis
* @param userName 用户名
*/
@Async
public void addUserCache(String userName, JwtUserDto user) {
// 转小写
userName = StringUtils.lowerCase(userName);
if (StringUtils.isNotEmpty(userName)) {
// 添加数据, 避免数据同时过期
long time = idleTime + RandomUtil.randomInt(900, 1800);
|
redisUtils.set(LoginProperties.cacheKey + userName, user, time);
}
}
/**
* 清理用户缓存信息
* 用户信息变更时
* @param userName 用户名
*/
@Async
public void cleanUserCache(String userName) {
// 转小写
userName = StringUtils.lowerCase(userName);
if (StringUtils.isNotEmpty(userName)) {
// 清除数据
redisUtils.del(LoginProperties.cacheKey + userName);
}
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\security\service\UserCacheManager.java
| 2
|
请完成以下Java代码
|
public class NeverFailAutoDeploymentStrategy extends AbstractAutoDeploymentStrategy {
protected static final Logger LOGGER = LoggerFactory.getLogger(NeverFailAutoDeploymentStrategy.class);
public static final String DEPLOYMENT_MODE = "never-fail";
public NeverFailAutoDeploymentStrategy(ApplicationUpgradeContextService applicationUpgradeContextService) {
super(applicationUpgradeContextService);
}
@Override
protected String getDeploymentMode() {
return DEPLOYMENT_MODE;
}
@Override
public void deployResources(String deploymentNameHint, Resource[] resources, RepositoryService repositoryService) {
DeploymentBuilder deploymentBuilder = repositoryService
.createDeployment()
.enableDuplicateFiltering()
.name(deploymentNameHint);
int validProcessCount = 0;
for (final Resource resource : resources) {
final String resourceName = determineResourceName(resource);
if (validateModel(resource, repositoryService)) {
validProcessCount++;
|
deploymentBuilder.addInputStream(resourceName, resource);
} else {
LOGGER.error(
"The following resource wasn't included in the deployment since it is invalid:\n{}",
resourceName
);
}
}
deploymentBuilder = loadApplicationUpgradeContext(deploymentBuilder);
if (validProcessCount != 0) {
deploymentBuilder.deploy();
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\autodeployment\NeverFailAutoDeploymentStrategy.java
| 1
|
请完成以下Java代码
|
private static ThreadPoolExecutor createPlannerThreadExecutor()
{
final CustomizableThreadFactory threadFactory = CustomizableThreadFactory.builder()
.setThreadNamePrefix("QueueProcessorPlanner")
.setDaemon(true)
.build();
return new ThreadPoolExecutor(
1, // corePoolSize
1, // maximumPoolSize
1000, // keepAliveTime
TimeUnit.MILLISECONDS, // timeUnit
new SynchronousQueue<>(), // workQueue
threadFactory, // threadFactory
new ThreadPoolExecutor.AbortPolicy());
}
@NonNull
private static ThreadPoolExecutor createQueueProcessorThreadExecutor()
{
final ThreadFactory threadFactory = CustomizableThreadFactory.builder()
.setThreadNamePrefix("QueueProcessor")
.setDaemon(true)
|
.build();
return new ThreadPoolExecutor(
1, // corePoolSize
100, // maximumPoolSize
1000, // keepAliveTime
TimeUnit.MILLISECONDS, // timeUnit
// SynchronousQueue has *no* capacity. Therefore, each new submitted task will directly cause a new thread to be started,
// which is exactly what we want here.
// Thank you, http://stackoverflow.com/questions/10186397/threadpoolexecutor-without-a-queue !!!
new SynchronousQueue<>(), // workQueue
threadFactory, // threadFactory
new ThreadPoolExecutor.AbortPolicy() // RejectedExecutionHandler
);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\planner\AsyncProcessorPlanner.java
| 1
|
请完成以下Java代码
|
public class DBRes_pt extends ListResourceBundle
{
/** Data */
//Characters encoded to UTF8 Hex, so no more problems with svn commits
//Fernando Lucktemberg - CenturuyOn Consultoria
static final Object[][] contents = new String[][]
{
{ "CConnectionDialog", "Conex\u00e3o" },
{ "Name", "Nome" },
{ "AppsHost", "Servidor de Aplica\u00e7\u00e3o" },
{ "AppsPort", "Porta TCP da Aplica\u00e7\u00e3o" },
{ "TestApps", "Testar Aplica\u00e7\u00e3o" },
{ "DBHost", "Servidor do Banco de Dado" },
{ "DBPort", "Porta TCP do Banco de Dados" },
{ "DBName", "Nome do Banco de Dados" },
{ "DBUidPwd", "Usu\u00e1rio / Senha" },
{ "ViaFirewall", "via Firewall" },
{ "FWHost", "Servidor de Firewall" },
{ "FWPort", "Porta TCP do Firewall" },
{ "TestConnection", "Testar Banco de Dados" },
{ "Type", "Tipo de Banco de Dados" },
{ "BequeathConnection", "Conex\u00e3o Bequeath" },
|
{ "Overwrite", "Sobrescrever" },
{ "ConnectionProfile", "Connection" },
{ "LAN", "LAN" },
{ "TerminalServer", "Terminal Server" },
{ "VPN", "VPN" },
{ "WAN", "WAN" },
{ "ConnectionError", "Erro de Conex\u00e3o" },
{ "ServerNotActive", "Servidor n\u00e3o Ativo" }
};
/**
* Get Contsnts
* @return contents
*/
public Object[][] getContents()
{
return contents;
} // getContent
} // Res
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\connectiondialog\i18n\DBRes_pt.java
| 1
|
请完成以下Java代码
|
public String getJobHandlerConfiguration() {
return jobHandlerConfiguration;
}
public void setJobHandlerConfiguration(String jobHandlerConfiguration) {
this.jobHandlerConfiguration = jobHandlerConfiguration;
}
public String getRepeat() {
return repeat;
}
public void setRepeat(String repeat) {
this.repeat = repeat;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
@Override
public String getExceptionMessage() {
|
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = StringUtils.abbreviate(exceptionMessage, MAX_EXCEPTION_MESSAGE_LENGTH);
}
@Override
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public String getCorrelationId() {
// v5 Jobs have no correlationId
return null;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AbstractJobEntity.java
| 1
|
请完成以下Java代码
|
private void assignSerialNumberToCU(final HuId huId, final String serialNo)
{
final I_M_HU hu = handlingUnitsRepo.getById(huId);
final IContextAware ctxAware = getContextAware(hu);
final IHUContext huContext = handlingUnitsBL.createMutableHUContext(ctxAware);
final IAttributeStorage attributeStorage = getAttributeStorage(huContext, hu);
Check.errorUnless(attributeStorage.hasAttribute(AttributeConstants.ATTR_SerialNo), "There is no SerialNo attribute {} defined for the handling unit {}", AttributeConstants.ATTR_SerialNo, hu);
attributeStorage.setValue(AttributeConstants.ATTR_SerialNo, serialNo.trim());
attributeStorage.saveChangesIfNeeded();
}
private boolean isAggregateHU(final HUEditorRow huRow)
{
final I_M_HU hu = huRow.getM_HU();
return handlingUnitsBL.isAggregateHU(hu);
}
private final IAttributeStorage getAttributeStorage(final IHUContext huContext, final I_M_HU hu)
{
final IAttributeStorageFactory attributeStorageFactory = huContext.getHUAttributeStorageFactory();
final IAttributeStorage attributeStorage = attributeStorageFactory.getAttributeStorage(hu);
return attributeStorage;
}
private final HUTransformService newHUTransformation()
|
{
return HUTransformService.builder()
.referencedObjects(getContextDocumentLines())
.build();
}
/**
* @return context document/lines (e.g. the receipt schedules)
*/
private List<TableRecordReference> getContextDocumentLines()
{
if (view == null)
{
return ImmutableList.of();
}
return view.getReferencingDocumentPaths()
.stream()
.map(referencingDocumentPath -> documentCollections.getTableRecordReference(referencingDocumentPath))
.collect(GuavaCollectors.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUIHUCreationWithSerialNumberService.java
| 1
|
请完成以下Java代码
|
public Mono<Authentication> authenticate(Authentication authentication) {
return Mono.defer(() -> {
OAuth2AuthorizationCodeAuthenticationToken token = (OAuth2AuthorizationCodeAuthenticationToken) authentication;
// Section 3.1.2.1 Authentication Request -
// https://openid.net/specs/openid-connect-core-1_0.html#AuthRequest scope
// REQUIRED. OpenID Connect requests MUST contain the "openid" scope value.
if (token.getAuthorizationExchange().getAuthorizationRequest().getScopes().contains("openid")) {
// This is an OpenID Connect Authentication Request so return null
// and let OidcAuthorizationCodeReactiveAuthenticationManager handle it
// instead once one is created
return Mono.empty();
}
return this.authorizationCodeManager.authenticate(token)
.onErrorMap(OAuth2AuthorizationException.class,
(e) -> new OAuth2AuthenticationException(e.getError(), e.getError().toString(), e))
.cast(OAuth2AuthorizationCodeAuthenticationToken.class)
.flatMap(this::onSuccess);
});
}
/**
* Sets the {@link GrantedAuthoritiesMapper} used for mapping
* {@link OAuth2User#getAuthorities()} to a new set of authorities which will be
* associated to the {@link OAuth2LoginAuthenticationToken}.
* @param authoritiesMapper the {@link GrantedAuthoritiesMapper} used for mapping the
* user's authorities
* @since 5.4
*/
public final void setAuthoritiesMapper(GrantedAuthoritiesMapper authoritiesMapper) {
Assert.notNull(authoritiesMapper, "authoritiesMapper cannot be null");
this.authoritiesMapper = authoritiesMapper;
}
|
private Mono<OAuth2LoginAuthenticationToken> onSuccess(OAuth2AuthorizationCodeAuthenticationToken authentication) {
OAuth2AccessToken accessToken = authentication.getAccessToken();
Map<String, Object> additionalParameters = authentication.getAdditionalParameters();
OAuth2UserRequest userRequest = new OAuth2UserRequest(authentication.getClientRegistration(), accessToken,
additionalParameters);
return this.userService.loadUser(userRequest).map((oauth2User) -> {
Collection<? extends GrantedAuthority> mappedAuthorities = this.authoritiesMapper
.mapAuthorities(oauth2User.getAuthorities());
OAuth2LoginAuthenticationToken authenticationResult = new OAuth2LoginAuthenticationToken(
authentication.getClientRegistration(), authentication.getAuthorizationExchange(), oauth2User,
mappedAuthorities, accessToken, authentication.getRefreshToken());
return authenticationResult;
});
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\authentication\OAuth2LoginReactiveAuthenticationManager.java
| 1
|
请完成以下Java代码
|
protected Set<Class<?>> getCustomMybatisMapperClasses(List<String> customMyBatisMappers) {
Set<Class<?>> mybatisMappers = new HashSet<>();
for (String customMybatisMapperClassName : customMyBatisMappers) {
try {
Class customMybatisClass = Class.forName(customMybatisMapperClassName);
mybatisMappers.add(customMybatisClass);
} catch (ClassNotFoundException e) {
throw new IllegalArgumentException("Class " + customMybatisMapperClassName + " has not been found.", e);
}
}
return mybatisMappers;
}
@Bean
public ProcessEngineFactoryBean processEngine(SpringProcessEngineConfiguration configuration) {
return super.springProcessEngineBean(configuration);
}
@Bean
@ConditionalOnMissingBean
@Override
public RuntimeService runtimeServiceBean(ProcessEngine processEngine) {
return super.runtimeServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public RepositoryService repositoryServiceBean(ProcessEngine processEngine) {
return super.repositoryServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public TaskService taskServiceBean(ProcessEngine processEngine) {
return super.taskServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public HistoryService historyServiceBean(ProcessEngine processEngine) {
return super.historyServiceBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public ManagementService managementServiceBeanBean(ProcessEngine processEngine) {
|
return super.managementServiceBeanBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
public TaskExecutor taskExecutor() {
return new SimpleAsyncTaskExecutor();
}
@Bean
@ConditionalOnMissingBean
@Override
public IntegrationContextManager integrationContextManagerBean(ProcessEngine processEngine) {
return super.integrationContextManagerBean(processEngine);
}
@Bean
@ConditionalOnMissingBean
@Override
public IntegrationContextService integrationContextServiceBean(ProcessEngine processEngine) {
return super.integrationContextServiceBean(processEngine);
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\AbstractProcessEngineAutoConfiguration.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private ItemMetadata resolveItemMetadataGroup(String prefix, MetadataGenerationEnvironment environment) {
Element propertyElement = environment.getTypeUtils().asElement(getType());
String nestedPrefix = ConfigurationMetadata.nestedPrefix(prefix, getName());
String dataType = environment.getTypeUtils().getQualifiedName(propertyElement);
String ownerType = environment.getTypeUtils().getQualifiedName(getDeclaringElement());
String sourceMethod = (getGetter() != null) ? getGetter().toString() : null;
return ItemMetadata.newGroup(nestedPrefix, dataType, ownerType, sourceMethod);
}
private ItemMetadata resolveItemMetadataProperty(String prefix, MetadataGenerationEnvironment environment) {
String dataType = resolveType(environment);
String ownerType = environment.getTypeUtils().getQualifiedName(getDeclaringElement());
String description = resolveDescription(environment);
Object defaultValue = resolveDefaultValue(environment);
ItemDeprecation deprecation = resolveItemDeprecation(environment);
return ItemMetadata.newProperty(prefix, getName(), dataType, ownerType, null, description, defaultValue,
deprecation);
}
protected final ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment,
Element... elements) {
boolean deprecated = Arrays.stream(elements).anyMatch(environment::isDeprecated);
return deprecated ? environment.resolveItemDeprecation(getGetter()) : null;
}
private String resolveType(MetadataGenerationEnvironment environment) {
return environment.getTypeUtils().getType(getDeclaringElement(), getType());
}
/**
* Resolve the property description.
* @param environment the metadata generation environment
* @return the property description
*/
protected abstract String resolveDescription(MetadataGenerationEnvironment environment);
/**
|
* Resolve the default value for this property.
* @param environment the metadata generation environment
* @return the default value or {@code null}
*/
protected abstract Object resolveDefaultValue(MetadataGenerationEnvironment environment);
/**
* Resolve the {@link ItemDeprecation} for this property.
* @param environment the metadata generation environment
* @return the deprecation or {@code null}
*/
protected abstract ItemDeprecation resolveItemDeprecation(MetadataGenerationEnvironment environment);
/**
* Return true if this descriptor is for a property.
* @param environment the metadata generation environment
* @return if this is a property
*/
abstract boolean isProperty(MetadataGenerationEnvironment environment);
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\PropertyDescriptor.java
| 2
|
请完成以下Java代码
|
protected void appendDetail(final StringBuffer buffer, final String fieldName, final Collection<?> col)
{
appendSummarySize(buffer, fieldName, col.size());
final ExtendedReflectionToStringBuilder builder = new ExtendedReflectionToStringBuilder(
col.toArray(), // object
this, // style,
buffer, //buffer,
null, //reflectUpToClass,
true, // outputTransients,
true // outputStatics
);
builder.toString();
}
@Override
protected String getShortClassName(final Class<?> cls)
{
if (cls != null && cls.isArray() && getDepth() > 0)
{
return "";
}
return super.getShortClassName(cls);
}
|
static class MutableInteger
{
private int value;
MutableInteger(final int value)
{
this.value = value;
}
public final int get()
{
return value;
}
public final void increment()
{
++value;
}
public final void decrement()
{
--value;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\text\RecursiveIndentedMultilineToStringStyle.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BigDecimal getQtyDelta()
{
BigDecimal qtyDelta = candidate.getQuantity();
if (previousQty != null)
{
qtyDelta = qtyDelta.subtract(previousQty);
}
return qtyDelta;
}
/**
* @return {@code true} if before the save, there already was a record with a different date.
*/
public boolean isDateMoved()
{
if (previousTime == null)
{
return false;
}
return !DateAndSeqNo.equals(previousTime, DateAndSeqNo.ofCandidate(candidate));
}
public boolean isDateMovedForwards()
{
if (previousTime == null)
{
return false;
}
return previousTime.isBefore(DateAndSeqNo.ofCandidate(candidate));
}
/**
* @return {@code true} there was no record before the save, or the record's date was changed.
*/
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isDateChanged()
{
if (previousTime == null)
{
return true;
}
return !DateAndSeqNo.equals(previousTime, DateAndSeqNo.ofCandidate(candidate));
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isQtyChanged()
{
return getQtyDelta().signum() != 0;
}
// TODO figure out if we really need this
public Candidate toCandidateWithQtyDelta()
|
{
return candidate.withQuantity(getQtyDelta());
}
/**
* Convenience method that returns a new instance whose included {@link Candidate} has the given id.
*/
public CandidateSaveResult withCandidateId(@Nullable final CandidateId candidateId)
{
return toBuilder()
.candidate(candidate.withId(candidateId))
.build();
}
/**
* Convenience method that returns a new instance with negated candidate quantity and previousQty
*/
public CandidateSaveResult withNegatedQuantity()
{
return toBuilder()
.candidate(candidate.withNegatedQuantity())
.previousQty(previousQty == null ? null : previousQty.negate())
.build();
}
public CandidateSaveResult withParentId(@Nullable final CandidateId parentId)
{
return toBuilder()
.candidate(candidate.withParentId(parentId))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\CandidateSaveResult.java
| 2
|
请完成以下Java代码
|
public void setAD_Attachment_ID (final int AD_Attachment_ID)
{
if (AD_Attachment_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Attachment_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Attachment_ID, AD_Attachment_ID);
}
@Override
public int getAD_Attachment_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Attachment_ID);
}
@Override
public void setAD_AttachmentEntry_ID (final int AD_AttachmentEntry_ID)
{
if (AD_AttachmentEntry_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_AttachmentEntry_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_AttachmentEntry_ID, AD_AttachmentEntry_ID);
}
@Override
public int getAD_AttachmentEntry_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_AttachmentEntry_ID);
}
@Override
public void setBinaryData (final @Nullable byte[] BinaryData)
{
set_ValueNoCheck (COLUMNNAME_BinaryData, BinaryData);
}
@Override
public byte[] getBinaryData()
{
return (byte[])get_Value(COLUMNNAME_BinaryData);
}
@Override
public void setContentType (final @Nullable java.lang.String ContentType)
{
set_Value (COLUMNNAME_ContentType, ContentType);
}
@Override
public java.lang.String getContentType()
{
return get_ValueAsString(COLUMNNAME_ContentType);
}
@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 setFileName (final java.lang.String FileName)
{
set_Value (COLUMNNAME_FileName, FileName);
}
@Override
public java.lang.String getFileName()
{
|
return get_ValueAsString(COLUMNNAME_FileName);
}
@Override
public void setTags (final @Nullable java.lang.String Tags)
{
set_Value (COLUMNNAME_Tags, Tags);
}
@Override
public java.lang.String getTags()
{
return get_ValueAsString(COLUMNNAME_Tags);
}
/**
* Type AD_Reference_ID=540751
* Reference name: AD_AttachmentEntry_Type
*/
public static final int TYPE_AD_Reference_ID=540751;
/** Data = D */
public static final String TYPE_Data = "D";
/** URL = U */
public static final String TYPE_URL = "U";
/** Local File-URL = LU */
public static final String TYPE_LocalFile_URL = "LU";
@Override
public void setType (final java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setURL (final @Nullable java.lang.String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
@Override
public java.lang.String getURL()
{
return get_ValueAsString(COLUMNNAME_URL);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AttachmentEntry.java
| 1
|
请完成以下Spring Boot application配置
|
grpc:
server:
port: 9090
logging:
pattern:
console: "[%d{yyyy-MM-dd HH:mm:ss.SSS}] %-5level [%t] [%logger - %line]: %m%n"
level:
com.ba
|
eldung.helloworld.provider: info
include-application-name: false
|
repos\tutorials-master\spring-boot-modules\spring-boot-3-grpc\helloworld-grpc-provider\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public class CommonResult<T> implements Serializable {
public static Integer CODE_SUCCESS = 0;
/**
* 错误码
*/
private Integer code;
/**
* 错误提示
*/
private String message;
/**
* 返回数据
*/
private T data;
/**
* 将传入的 result 对象,转换成另外一个泛型结果的对象
*
* 因为 A 方法返回的 CommonResult 对象,不满足调用其的 B 方法的返回,所以需要进行转换。
*
* @param result 传入的 result 对象
* @param <T> 返回的泛型
* @return 新的 CommonResult 对象
*/
public static <T> CommonResult<T> error(CommonResult<?> result) {
return error(result.getCode(), result.getMessage());
}
public static <T> CommonResult<T> error(Integer code, String message) {
Assert.isTrue(!CODE_SUCCESS.equals(code), "code 必须是错误的!");
CommonResult<T> result = new CommonResult<>();
result.code = code;
result.message = message;
return result;
}
public static <T> CommonResult<T> success(T data) {
CommonResult<T> result = new CommonResult<>();
result.code = CODE_SUCCESS;
result.data = data;
result.message = "";
return result;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
|
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
@JsonIgnore
public boolean isSuccess() {
return CODE_SUCCESS.equals(code);
}
@JsonIgnore
public boolean isError() {
return !isSuccess();
}
@Override
public String toString() {
return "CommonResult{" +
"code=" + code +
", message='" + message + '\'' +
", data=" + data +
'}';
}
}
|
repos\SpringBoot-Labs-master\lab-22\lab-22-validation-01\src\main\java\cn\iocoder\springboot\lab22\validation\core\vo\CommonResult.java
| 1
|
请完成以下Java代码
|
protected void installKeyboardActions (JLabel l)
{
// super.installKeyboardActions(l);
int dka = l.getDisplayedMnemonic();
if (dka != 0)
{
Component lf = l.getLabelFor();
if (lf != null)
{
ActionMap actionMap = l.getActionMap();
actionMap.put(PRESS, ACTION_PRESS);
InputMap inputMap = SwingUtilities.getUIInputMap (l, JComponent.WHEN_IN_FOCUSED_WINDOW);
if (inputMap == null)
{
inputMap = new ComponentInputMapUIResource (l);
SwingUtilities.replaceUIInputMap (l, JComponent.WHEN_IN_FOCUSED_WINDOW, inputMap);
}
inputMap.clear ();
inputMap.put(KeyStroke.getKeyStroke(dka, ActionEvent.SHIFT_MASK + ActionEvent.CTRL_MASK, false), PRESS);
}
}
} // installKeyboardActions
/** Action Name */
private static final String PRESS = "press";
/** Press Action */
private static final PressAction ACTION_PRESS = new PressAction();
/**
* Compiere Label UI Actions
*/
private static class PressAction extends UIAction
{
PressAction ()
{
super (PRESS);
}
@Override
public void actionPerformed (ActionEvent e)
{
JLabel label = (JLabel)e.getSource ();
String key = getName ();
if (key.equals(PRESS))
{
doPress (label);
}
} // actionPerformed
/**
* Do Press - Focus the Field
* @param label label
*/
private void doPress (JLabel label)
{
Component labelFor = label.getLabelFor ();
if (labelFor != null && labelFor.isEnabled ())
{
Component owner = label.getLabelFor ();
if (owner instanceof Container
&& ((Container)owner).isFocusCycleRoot ())
{
owner.requestFocus ();
}
else
{
if (owner instanceof Container)
{
Container container = (Container)owner;
if (container.isFocusCycleRoot())
{
|
FocusTraversalPolicy policy = container.getFocusTraversalPolicy();
Component comp = policy.getDefaultComponent(container);
if (comp != null)
{
comp.requestFocus();
return;
}
}
Container rootAncestor = container.getFocusCycleRootAncestor();
if (rootAncestor != null)
{
FocusTraversalPolicy policy = rootAncestor.getFocusTraversalPolicy();
Component comp = policy.getComponentAfter(rootAncestor, container);
if (comp != null && SwingUtilities.isDescendingFrom(comp, container))
{
comp.requestFocus();
return;
}
}
}
if (owner.isFocusable())
{
owner.requestFocus();
return;
}
// No Forcus
}
}
} // doPress
} // PressAction
} // AdempiereLabelUI
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\AdempiereLabelUI.java
| 1
|
请完成以下Java代码
|
public class Person {
private String firstName;
private String lastName;
private int age;
private List<PhoneNumber> phoneNumbers;
@DiffExclude
private Address address;
public Person(String firstName, String lastName, int age, List<PhoneNumber> phoneNumbers, Address address) {
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
this.phoneNumbers = phoneNumbers;
this.address = address;
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public int getAge() {
return age;
}
public List<PhoneNumber> getPhoneNumbers() {
return phoneNumbers;
}
|
public Address getAddress() {
return address;
}
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
Person person = (Person) o;
return age == person.age && Objects.equals(firstName, person.firstName) && Objects.equals(lastName, person.lastName) && Objects.equals(phoneNumbers, person.phoneNumbers) && Objects.equals(address, person.address);
}
@Override
public int hashCode() {
return Objects.hash(firstName, lastName, age, phoneNumbers, address);
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-6\src\main\java\com\baeldung\compareobjects\Person.java
| 1
|
请完成以下Java代码
|
public String completeIt(final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
forecast.setDocAction(IDocument.ACTION_None);
return IDocument.STATUS_Completed;
}
@Override
public void approveIt(final DocumentTableFields docFields)
{
}
@Override
public void rejectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void voidIt(final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(forecast.getDocStatus());
if (docStatus.isClosedReversedOrVoided())
{
throw new AdempiereException("Document Closed: " + docStatus);
}
getLines(forecast).forEach(this::voidLine);
forecast.setProcessed(true);
forecast.setDocAction(IDocument.ACTION_None);
}
@Override
public void unCloseIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
|
@Override
public void reverseCorrectIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reverseAccrualIt(final DocumentTableFields docFields)
{
throw new UnsupportedOperationException();
}
@Override
public void reactivateIt(final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
forecast.setProcessed(false);
forecast.setDocAction(IDocument.ACTION_Complete);
}
@Override
public LocalDate getDocumentDate(@NonNull final DocumentTableFields docFields)
{
final I_M_Forecast forecast = extractForecast(docFields);
return TimeUtil.asLocalDate(forecast.getDatePromised());
}
private void voidLine(@NonNull final I_M_ForecastLine line)
{
line.setQty(BigDecimal.ZERO);
line.setQtyCalculated(BigDecimal.ZERO);
InterfaceWrapperHelper.save(line);
}
private List<I_M_ForecastLine> getLines(@NonNull final I_M_Forecast forecast)
{
return forecastDAO.retrieveLinesByForecastId(ForecastId.ofRepoId(forecast.getM_Forecast_ID()));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\mforecast\ForecastDocumentHandler.java
| 1
|
请完成以下Java代码
|
private void findById(List<Author> authors) {
Author author1 = this.authorRepository.findById(authors.get(0).getId()).orElse(null);
Author author2 = this.authorRepository.findById(authors.get(1).getId()).orElse(null);
System.out.printf("findById(): author1 = %s%n", author1);
System.out.printf("findById(): author2 = %s%n", author2);
}
private void listAllAuthors() {
List<Author> authors = this.authorRepository.findAll();
for (Author author : authors) {
System.out.printf("listAllAuthors(): author = %s%n", author);
for (Book book : author.getBooks()) {
System.out.printf("\t%s%n", book);
}
}
|
}
private List<Author> insertAuthors() {
Author author1 = this.authorRepository.save(new Author(null, "Josh Long",
Set.of(new Book(null, "Reactive Spring"), new Book(null, "Cloud Native Java"))));
Author author2 = this.authorRepository.save(
new Author(null, "Martin Kleppmann", Set.of(new Book(null, "Designing Data Intensive Applications"))));
System.out.printf("insertAuthors(): author1 = %s%n", author1);
System.out.printf("insertAuthors(): author2 = %s%n", author2);
return Arrays.asList(author1, author2);
}
}
|
repos\spring-data-examples-main\jpa\graalvm-native\src\main\java\com\example\data\jpa\CLR.java
| 1
|
请完成以下Java代码
|
public void updateCurrencyRate(final I_SAP_GLJournal glJournal)
{
final BigDecimal currencyRate = computeCurrencyRate(glJournal);
if (currencyRate == null)
{
return;
}
glJournal.setCurrencyRate(currencyRate);
}
@Nullable
private BigDecimal computeCurrencyRate(final I_SAP_GLJournal glJournal)
{
//
// Extract data from source Journal
final CurrencyId currencyId = CurrencyId.ofRepoIdOrNull(glJournal.getC_Currency_ID());
if (currencyId == null)
{
// not set yet
return null;
}
final CurrencyId acctCurrencyId = CurrencyId.ofRepoIdOrNull(glJournal.getAcct_Currency_ID());
if (acctCurrencyId == null)
{
return null;
|
}
final CurrencyConversionTypeId conversionTypeId = CurrencyConversionTypeId.ofRepoIdOrNull(glJournal.getC_ConversionType_ID());
Instant dateAcct = TimeUtil.asInstant(glJournal.getDateAcct());
if (dateAcct == null)
{
dateAcct = SystemTime.asInstant();
}
final ClientId adClientId = ClientId.ofRepoId(glJournal.getAD_Client_ID());
final OrgId adOrgId = OrgId.ofRepoId(glJournal.getAD_Org_ID());
return currencyBL.getCurrencyRateIfExists(
currencyId,
acctCurrencyId,
dateAcct,
conversionTypeId,
adClientId,
adOrgId)
.map(CurrencyRate::getConversionRate)
.orElse(BigDecimal.ZERO);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\callout\SAP_GLJournal.java
| 1
|
请完成以下Java代码
|
public void updateFailedJobRetriesByJobDefinitionId(String jobDefinitionId, int retries, Date dueDate, boolean isDueDateSet) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("jobDefinitionId", jobDefinitionId);
parameters.put("retries", retries);
parameters.put("dueDate", dueDate);
parameters.put("isDueDateSet", isDueDateSet);
getDbEntityManager().update(JobEntity.class, "updateFailedJobRetriesByParameters", parameters);
}
public void updateJobPriorityByDefinitionId(String jobDefinitionId, long priority) {
Map<String, Object> parameters = new HashMap<>();
parameters.put("jobDefinitionId", jobDefinitionId);
parameters.put("priority", priority);
getDbEntityManager().update(JobEntity.class, "updateJobPriorityByDefinitionId", parameters);
}
protected void configureQuery(JobQueryImpl query) {
getAuthorizationManager().configureJobQuery(query);
getTenantManager().configureQuery(query);
}
|
protected ListQueryParameterObject configureParameterizedQuery(Object parameter) {
return getTenantManager().configureQuery(parameter);
}
protected boolean isEnsureJobDueDateNotNull() {
return Context.getProcessEngineConfiguration().isEnsureJobDueDateNotNull();
}
/**
* Sometimes we get a notification of a job that is not yet due, so we
* should not execute it immediately
*/
protected boolean isJobDue(JobEntity job) {
Date duedate = job.getDuedate();
Date now = ClockUtil.getCurrentTime();
return duedate == null || duedate.getTime() <= now.getTime();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\JobManager.java
| 1
|
请完成以下Java代码
|
public boolean isActive()
{
return active;
}
}
default RegisterListenerRequest newEventListener(@NonNull final TrxEventTiming timing)
{
return new RegisterListenerRequest(this, timing);
}
/**
* This method shall only be called by the framework. Instead, call {@link #newEventListener(TrxEventTiming)}
* and be sure to call {@link RegisterListenerRequest#registerHandlingMethod(EventHandlingMethod)} at the end.
*/
void registerListener(RegisterListenerRequest listener);
boolean canRegisterOnTiming(TrxEventTiming timing);
default void runAfterCommit(@NonNull final Runnable runnable)
{
newEventListener(TrxEventTiming.AFTER_COMMIT)
.invokeMethodJustOnce(true)
.registerHandlingMethod(trx -> runnable.run());
}
default void runBeforeCommit(@NonNull final Runnable runnable)
{
newEventListener(TrxEventTiming.BEFORE_COMMIT)
.invokeMethodJustOnce(true)
.registerHandlingMethod(trx -> runnable.run());
}
default void runAfterRollback(@NonNull final Runnable runnable)
{
newEventListener(TrxEventTiming.AFTER_ROLLBACK)
.invokeMethodJustOnce(true)
.registerHandlingMethod(trx -> runnable.run());
}
default void runAfterClose(@NonNull final Consumer<ITrx> runnable)
{
newEventListener(TrxEventTiming.AFTER_CLOSE)
.invokeMethodJustOnce(true)
.registerHandlingMethod(runnable::accept);
|
}
/**
* This method shall only be called by the framework.
*/
void fireBeforeCommit(ITrx trx);
/**
* This method shall only be called by the framework.
*/
void fireAfterCommit(ITrx trx);
/**
* This method shall only be called by the framework.
*/
void fireAfterRollback(ITrx trx);
/**
* This method shall only be called by the framework.
*/
void fireAfterClose(ITrx trx);
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\ITrxListenerManager.java
| 1
|
请完成以下Java代码
|
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Frequency.
@param Frequency
Frequency of events
*/
@Override
public void setFrequency (int Frequency)
{
set_Value (COLUMNNAME_Frequency, Integer.valueOf(Frequency));
}
/** Get Frequency.
@return Frequency of events
*/
@Override
public int getFrequency ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Frequency);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* FrequencyType AD_Reference_ID=540067
* Reference name: Recurrent Payment Frequency Type
*/
public static final int FREQUENCYTYPE_AD_Reference_ID=540067;
/** Day = D */
public static final String FREQUENCYTYPE_Day = "D";
/** Month = M */
public static final String FREQUENCYTYPE_Month = "M";
/** Set Frequency Type.
@param FrequencyType
Frequency of event
*/
@Override
public void setFrequencyType (java.lang.String FrequencyType)
{
set_Value (COLUMNNAME_FrequencyType, FrequencyType);
}
/** Get Frequency Type.
@return Frequency of event
*/
@Override
public java.lang.String getFrequencyType ()
{
return (java.lang.String)get_Value(COLUMNNAME_FrequencyType);
}
/** Set Next Payment Date.
@param NextPaymentDate Next Payment Date */
@Override
public void setNextPaymentDate (java.sql.Timestamp NextPaymentDate)
{
set_ValueNoCheck (COLUMNNAME_NextPaymentDate, NextPaymentDate);
}
/** Get Next Payment Date.
@return Next Payment Date */
@Override
public java.sql.Timestamp getNextPaymentDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_NextPaymentDate);
|
}
/** Set Payment amount.
@param PayAmt
Amount being paid
*/
@Override
public void setPayAmt (java.math.BigDecimal PayAmt)
{
set_Value (COLUMNNAME_PayAmt, PayAmt);
}
/** Get Payment amount.
@return Amount being paid
*/
@Override
public java.math.BigDecimal getPayAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PayAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPaymentLine.java
| 1
|
请完成以下Spring Boot application配置
|
jwt.sessionTime=86400
logging.level.org.springframework.data.mongodb.core.ReactiveMongoTemplate=DEBUG
spring.data.mongodb.auto-index-creation=true
#spring.data.mongodb.username=root
#spring.data.mongodb.
|
password=1234
#spring.data.mongodb.port=27017
#spring.data.mongodb.database=realworld-db
|
repos\realworld-spring-webflux-master\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public ImmutableList<OLCand> validateOLCands(@NonNull final List<OLCand> olCandList)
{
setValidationProcessInProgress(true); // avoid the InterfaceWrapperHelper.save to trigger another validation from a MV.
final OLCandFactory olCandFactory = new OLCandFactory();
final ImmutableList.Builder<OLCand> validatedOlCands = ImmutableList.builder();
try
{
for (final OLCand cand : olCandList)
{
final I_C_OLCand olCandRecord = cand.unbox();
validate(olCandRecord);
InterfaceWrapperHelper.save(olCandRecord); // will only access the DB is there are changes in cand
validatedOlCands.add(olCandFactory.toOLCand(olCandRecord));
}
return validatedOlCands.build();
}
finally
{
setValidationProcessInProgress(false);
}
}
@NonNull
private List<OLCandValidationResult> validateOLCandRecords(@NonNull final List<I_C_OLCand> olCandList)
|
{
setValidationProcessInProgress(true); // avoid the InterfaceWrapperHelper.save to trigger another validation from a MV.
final ImmutableList.Builder<OLCandValidationResult> olCandValidationResultBuilder = ImmutableList.builder();
try
{
for (final I_C_OLCand cand : olCandList)
{
validate(cand);
InterfaceWrapperHelper.save(cand); // will only access the DB is there are changes in cand
olCandValidationResultBuilder.add(cand.isError()
? OLCandValidationResult.error(OLCandId.ofRepoId(cand.getC_OLCand_ID()))
: OLCandValidationResult.ok(OLCandId.ofRepoId(cand.getC_OLCand_ID())));
}
return olCandValidationResultBuilder.build();
}
finally
{
setValidationProcessInProgress(false);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\api\OLCandValidatorService.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static MethodInterceptor preFilterAuthorizationMethodInterceptor(
ObjectProvider<PrePostMethodSecurityConfiguration> _prePostMethodSecurityConfiguration) {
return new DeferringMethodInterceptor<>(preFilterPointcut,
() -> _prePostMethodSecurityConfiguration.getObject().preFilterMethodInterceptor);
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static MethodInterceptor preAuthorizeAuthorizationMethodInterceptor(
ObjectProvider<PrePostMethodSecurityConfiguration> _prePostMethodSecurityConfiguration) {
return new DeferringMethodInterceptor<>(preAuthorizePointcut,
() -> _prePostMethodSecurityConfiguration.getObject().preAuthorizeMethodInterceptor);
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static MethodInterceptor postAuthorizeAuthorizationMethodInterceptor(
ObjectProvider<PrePostMethodSecurityConfiguration> _prePostMethodSecurityConfiguration) {
return new DeferringMethodInterceptor<>(postAuthorizePointcut,
() -> _prePostMethodSecurityConfiguration.getObject().postAuthorizeMethodInterceptor);
}
@Bean
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static MethodInterceptor postFilterAuthorizationMethodInterceptor(
ObjectProvider<PrePostMethodSecurityConfiguration> _prePostMethodSecurityConfiguration) {
return new DeferringMethodInterceptor<>(postFilterPointcut,
() -> _prePostMethodSecurityConfiguration.getObject().postFilterMethodInterceptor);
}
@Bean
|
@Role(BeanDefinition.ROLE_INFRASTRUCTURE)
static SecurityHintsRegistrar prePostAuthorizeExpressionHintsRegistrar() {
return new PrePostAuthorizeHintsRegistrar();
}
@Override
public void setImportMetadata(AnnotationMetadata importMetadata) {
EnableMethodSecurity annotation = importMetadata.getAnnotations().get(EnableMethodSecurity.class).synthesize();
this.preFilterMethodInterceptor.setOrder(this.preFilterMethodInterceptor.getOrder() + annotation.offset());
this.preAuthorizeMethodInterceptor
.setOrder(this.preAuthorizeMethodInterceptor.getOrder() + annotation.offset());
this.postAuthorizeMethodInterceptor
.setOrder(this.postAuthorizeMethodInterceptor.getOrder() + annotation.offset());
this.postFilterMethodInterceptor.setOrder(this.postFilterMethodInterceptor.getOrder() + annotation.offset());
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\method\configuration\PrePostMethodSecurityConfiguration.java
| 2
|
请完成以下Java代码
|
protected String doIt() throws Exception
{
final I_M_Product product = InterfaceWrapperHelper.create(getCtx(), getRecord_ID(), I_M_Product.class, getTrxName());
if (product == null)
{
return "@NotFound@" + "@M_Product_ID@";
}
final I_M_Product targetProduct = InterfaceWrapperHelper.create(getCtx(), p_targetProductID, I_M_Product.class, getTrxName());
if (targetProduct == null)
{
return "@NotFound@" + "@M_Product_Target_ID@";
}
final I_M_Product_Mapping currentProdMapping = product.getM_Product_Mapping();
final I_M_Product_Mapping targetProdMapping = targetProduct.getM_Product_Mapping();
// in case there is no mapping for any of the products, create one and assign it to both of them
if (currentProdMapping == null && targetProdMapping == null)
{
final I_M_Product_Mapping mappingToSet = InterfaceWrapperHelper.newInstance(I_M_Product_Mapping.class, product);
mappingToSet.setValue(product.getValue());
InterfaceWrapperHelper.save(mappingToSet);
product.setM_Product_Mapping(mappingToSet);
targetProduct.setM_Product_Mapping(mappingToSet);
}
// in case the target product doesn't have a mapping, set the one of the given products
else if (targetProdMapping == null)
{
targetProduct.setM_Product_Mapping(currentProdMapping);
}
// in case the current product doesn't have a mapping but the target has one, set it to the current product as well
else if (currentProdMapping == null)
{
product.setM_Product_Mapping(targetProdMapping);
}
else
{
|
// in case the two products have different mappings, will pick the one from the current product,
// set it to the target and update all the other products that have the target's ex-mapping with the current one
final List<I_M_Product> mappedProducts = Services.get(IProductDAO.class).retrieveAllMappedProducts(targetProduct);
for (final I_M_Product mappedProduct : mappedProducts)
{
mappedProduct.setM_Product_Mapping(currentProdMapping);
InterfaceWrapperHelper.save(mappedProduct);
}
// finally, set the current mapping to the target product as well
targetProduct.setM_Product_Mapping(currentProdMapping);
}
InterfaceWrapperHelper.save(product);
InterfaceWrapperHelper.save(targetProduct);
return "@Success@";
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\process\M_Product_Create_Mappings_Process.java
| 1
|
请完成以下Java代码
|
public String getViewUrl(@NonNull final String windowId, @NonNull final String viewId)
{
return getFrontendURL(SYSCONFIG_VIEW_PATH, ImmutableMap.<String, Object>builder()
.put(PARAM_windowId, windowId)
.put(PARAM_viewId, viewId)
.build());
}
@Nullable
public String getResetPasswordUrl(final String token)
{
Check.assumeNotEmpty(token, "token is not empty");
return getFrontendURL(SYSCONFIG_RESET_PASSWORD_PATH, ImmutableMap.<String, Object>builder()
.put(PARAM_ResetPasswordToken, token)
.build());
}
public boolean isCrossSiteUsageAllowed()
{
return sysConfigBL.getBooleanValue(SYSCONFIG_IsCrossSiteUsageAllowed, false);
}
public String getAppApiUrl()
|
{
final String url = StringUtils.trimBlankToNull(sysConfigBL.getValue(SYSCONFIG_APP_API_URL));
if (url != null && !url.equals("-"))
{
return url;
}
final String frontendUrl = getFrontendURL();
if (frontendUrl != null)
{
return frontendUrl + "/app";
}
return null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\ui\web\WebuiURLs.java
| 1
|
请完成以下Java代码
|
static DocumentArchiveEntry of(final DocumentId id, final I_AD_Archive archive)
{
return new DocumentArchiveEntry(id, archive);
}
private final DocumentId id;
private final I_AD_Archive archive;
private DocumentArchiveEntry(final DocumentId id, final I_AD_Archive archive)
{
this.id = id;
this.archive = archive;
}
@Override
public DocumentId getId()
{
return id;
}
@Override
public AttachmentEntryType getType()
{
return AttachmentEntryType.Data;
}
@Override
public String getFilename()
{
final String contentType = getContentType();
final String fileExtension = MimeType.getExtensionByType(contentType);
final String name = archive.getName();
return FileUtil.changeFileExtension(name, fileExtension);
}
@Override
public byte[] getData()
{
return archiveBL.getBinaryData(archive);
|
}
@Override
public String getContentType()
{
return archiveBL.getContentType(archive);
}
@Override
public URI getUrl()
{
return null;
}
@Override
public Instant getCreated()
{
return archive.getCreated().toInstant();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentArchiveEntry.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setEmail(String email) {
this.email = email;
}
public Pharmacy website(String website) {
this.website = website;
return this;
}
/**
* Get website
* @return website
**/
@Schema(example = "http://www.vitalapotheke.de", description = "")
public String getWebsite() {
return website;
}
public void setWebsite(String website) {
this.website = website;
}
public Pharmacy timestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return timestamp
**/
@Schema(description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getTimestamp() {
return timestamp;
}
public void setTimestamp(OffsetDateTime timestamp) {
this.timestamp = timestamp;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Pharmacy pharmacy = (Pharmacy) o;
return Objects.equals(this._id, pharmacy._id) &&
Objects.equals(this.name, pharmacy.name) &&
Objects.equals(this.address, pharmacy.address) &&
Objects.equals(this.postalCode, pharmacy.postalCode) &&
Objects.equals(this.city, pharmacy.city) &&
Objects.equals(this.phone, pharmacy.phone) &&
Objects.equals(this.fax, pharmacy.fax) &&
Objects.equals(this.email, pharmacy.email) &&
Objects.equals(this.website, pharmacy.website) &&
Objects.equals(this.timestamp, pharmacy.timestamp);
}
|
@Override
public int hashCode() {
return Objects.hash(_id, name, address, postalCode, city, phone, fax, email, website, timestamp);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class Pharmacy {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" name: ").append(toIndentedString(name)).append("\n");
sb.append(" address: ").append(toIndentedString(address)).append("\n");
sb.append(" postalCode: ").append(toIndentedString(postalCode)).append("\n");
sb.append(" city: ").append(toIndentedString(city)).append("\n");
sb.append(" phone: ").append(toIndentedString(phone)).append("\n");
sb.append(" fax: ").append(toIndentedString(fax)).append("\n");
sb.append(" email: ").append(toIndentedString(email)).append("\n");
sb.append(" website: ").append(toIndentedString(website)).append("\n");
sb.append(" timestamp: ").append(toIndentedString(timestamp)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-patient-api\src\main\java\io\swagger\client\model\Pharmacy.java
| 2
|
请完成以下Java代码
|
protected final void checkAllowIfAllAbstainDecisions() {
if (!this.isAllowIfAllAbstainDecisions()) {
throw new AccessDeniedException(
this.messages.getMessage("AbstractAccessDecisionManager.accessDenied", "Access is denied"));
}
}
public List<AccessDecisionVoter<?>> getDecisionVoters() {
return this.decisionVoters;
}
public boolean isAllowIfAllAbstainDecisions() {
return this.allowIfAllAbstainDecisions;
}
public void setAllowIfAllAbstainDecisions(boolean allowIfAllAbstainDecisions) {
this.allowIfAllAbstainDecisions = allowIfAllAbstainDecisions;
}
@Override
public void setMessageSource(MessageSource messageSource) {
this.messages = new MessageSourceAccessor(messageSource);
}
@Override
public boolean supports(ConfigAttribute attribute) {
for (AccessDecisionVoter<?> voter : this.decisionVoters) {
if (voter.supports(attribute)) {
return true;
}
}
return false;
}
/**
* Iterates through all <code>AccessDecisionVoter</code>s and ensures each can support
* the presented class.
|
* <p>
* If one or more voters cannot support the presented class, <code>false</code> is
* returned.
* @param clazz the type of secured object being presented
* @return true if this type is supported
*/
@Override
public boolean supports(Class<?> clazz) {
for (AccessDecisionVoter<?> voter : this.decisionVoters) {
if (!voter.supports(clazz)) {
return false;
}
}
return true;
}
@Override
public String toString() {
return this.getClass().getSimpleName() + " [DecisionVoters=" + this.decisionVoters
+ ", AllowIfAllAbstainDecisions=" + this.allowIfAllAbstainDecisions + "]";
}
}
|
repos\spring-security-main\access\src\main\java\org\springframework\security\access\vote\AbstractAccessDecisionManager.java
| 1
|
请完成以下Java代码
|
public HUPPOrderIssueProducer processCandidates(@NonNull final ProcessIssueCandidatesPolicy processCandidatesPolicy)
{
this.processCandidatesPolicy = processCandidatesPolicy;
return this;
}
private boolean isProcessCandidates()
{
final ProcessIssueCandidatesPolicy processCandidatesPolicy = this.processCandidatesPolicy;
if (ProcessIssueCandidatesPolicy.NEVER.equals(processCandidatesPolicy))
{
return false;
}
else if (ProcessIssueCandidatesPolicy.ALWAYS.equals(processCandidatesPolicy))
{
return true;
}
else if (ProcessIssueCandidatesPolicy.IF_ORDER_PLANNING_STATUS_IS_COMPLETE.equals(processCandidatesPolicy))
{
final I_PP_Order ppOrder = getPpOrder();
final PPOrderPlanningStatus orderPlanningStatus = PPOrderPlanningStatus.ofCode(ppOrder.getPlanningStatus());
return PPOrderPlanningStatus.COMPLETE.equals(orderPlanningStatus);
}
else
{
throw new AdempiereException("Unknown processCandidatesPolicy: " + processCandidatesPolicy);
|
}
}
public HUPPOrderIssueProducer changeHUStatusToIssued(final boolean changeHUStatusToIssued)
{
this.changeHUStatusToIssued = changeHUStatusToIssued;
return this;
}
public HUPPOrderIssueProducer generatedBy(final IssueCandidateGeneratedBy generatedBy)
{
this.generatedBy = generatedBy;
return this;
}
public HUPPOrderIssueProducer failIfIssueOnlyForReceived(final boolean fail)
{
this.failIfIssueOnlyForReceived = fail;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\HUPPOrderIssueProducer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setAuthenticationEventPublisher(AuthenticationEventPublisher authenticationEventPublisher) {
this.authenticationEventPublisher = authenticationEventPublisher;
}
public void setObservationRegistry(ObservationRegistry observationRegistry) {
this.observationRegistry = observationRegistry;
}
}
static class ObservationRegistryFactory implements FactoryBean<ObservationRegistry> {
@Override
public ObservationRegistry getObject() throws Exception {
return ObservationRegistry.NOOP;
}
@Override
public Class<?> getObjectType() {
return ObservationRegistry.class;
}
}
public static final class FilterChainDecoratorFactory
implements FactoryBean<FilterChainProxy.FilterChainDecorator> {
private ObservationRegistry observationRegistry = ObservationRegistry.NOOP;
@Override
public FilterChainProxy.FilterChainDecorator getObject() throws Exception {
if (this.observationRegistry.isNoop()) {
return new FilterChainProxy.VirtualFilterChainDecorator();
}
|
return new ObservationFilterChainDecorator(this.observationRegistry);
}
@Override
public Class<?> getObjectType() {
return FilterChainProxy.FilterChainDecorator.class;
}
public void setObservationRegistry(ObservationRegistry registry) {
this.observationRegistry = registry;
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\HttpSecurityBeanDefinitionParser.java
| 2
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.