instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getI_InOutLineConfirm_ID()));
}
/** Set Imported.
@param I_IsImported
Has this import been processed
*/
public void setI_IsImported (boolean I_IsImported)
{
set_Value (COLUMNNAME_I_IsImported, Boolean.valueOf(I_IsImported));
}
/** Get Imported.
@return Has this import been processed
*/
public boolean isI_IsImported ()
{
Object oo = get_Value(COLUMNNAME_I_IsImported);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
public I_M_InOutLineConfirm getM_InOutLineConfirm() throws RuntimeException
{
return (I_M_InOutLineConfirm)MTable.get(getCtx(), I_M_InOutLineConfirm.Table_Name)
.getPO(getM_InOutLineConfirm_ID(), get_TrxName()); }
/** Set Ship/Receipt Confirmation Line.
@param M_InOutLineConfirm_ID
Material Shipment or Receipt Confirmation Line
*/
public void setM_InOutLineConfirm_ID (int M_InOutLineConfirm_ID)
{
if (M_InOutLineConfirm_ID < 1)
set_Value (COLUMNNAME_M_InOutLineConfirm_ID, null);
else
set_Value (COLUMNNAME_M_InOutLineConfirm_ID, Integer.valueOf(M_InOutLineConfirm_ID));
}
/** Get Ship/Receipt Confirmation Line.
@return Material Shipment or Receipt Confirmation Line
*/
public int getM_InOutLineConfirm_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLineConfirm_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
|
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** 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;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_InOutLineConfirm.java
| 1
|
请完成以下Java代码
|
public class CompositePriceLimitRule implements IPriceLimitRule
{
private final CopyOnWriteArrayList<IPriceLimitRule> enforcers = new CopyOnWriteArrayList<>();
public void addEnforcer(@NonNull final IPriceLimitRule enforcer)
{
enforcers.addIfAbsent(enforcer);
}
@Override
public PriceLimitRuleResult compute(@NonNull final PriceLimitRuleContext context)
{
final BigDecimal priceActual = context.getPriceActual();
//
// Check each enforcer
PriceLimitRuleResult applicableResultWithMaxPriceLimit = null;
final ArrayList<PriceLimitRuleResult> notApplicableResults = new ArrayList<>();
for (final IPriceLimitRule enforcer : enforcers)
{
final PriceLimitRuleResult result = enforcer.compute(context);
final BooleanWithReason applicable = result.checkApplicableAndBelowPriceLimit(priceActual);
if (applicable.isTrue())
{
if (applicableResultWithMaxPriceLimit == null)
{
applicableResultWithMaxPriceLimit = result;
}
else if (applicableResultWithMaxPriceLimit.getPriceLimit().compareTo(result.getPriceLimit()) < 0)
{
applicableResultWithMaxPriceLimit = result;
}
else
{
// keep current applicableResultWithMaxPriceLimit
}
}
else
{
notApplicableResults.add(result);
}
}
//
// Case: we have a applicable limit:
if (applicableResultWithMaxPriceLimit != null)
{
return applicableResultWithMaxPriceLimit;
}
//
// Case: we don't have an applicable limit but we have a limit from price list
else if (context.getPriceLimit().signum() != 0)
{
return PriceLimitRuleResult.priceLimit(context.getPriceLimit(), "pricing PriceLimit (context/default)");
}
//
// Case: found nothing applicable
else
{
if (notApplicableResults.isEmpty())
{
return PriceLimitRuleResult.notApplicable("default PriceLimit=0 is not eligible");
|
}
else
{
return mergeNotApplicableResults(notApplicableResults);
}
}
}
private static PriceLimitRuleResult mergeNotApplicableResults(final List<PriceLimitRuleResult> notApplicableResults)
{
if (notApplicableResults.size() == 1)
{
return notApplicableResults.get(0);
}
final TranslatableStringBuilder builder = TranslatableStrings.builder();
for (final PriceLimitRuleResult notApplicableResult : notApplicableResults)
{
if (!builder.isEmpty())
{
builder.append("; ");
}
builder.append(notApplicableResult.getNotApplicableReason());
}
return PriceLimitRuleResult.notApplicable(builder.build());
}
@Override
public Set<CountryId> getPriceCountryIds()
{
return enforcers.stream()
.flatMap(enforcer -> enforcer.getPriceCountryIds().stream())
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\limit\CompositePriceLimitRule.java
| 1
|
请完成以下Java代码
|
public void setQty(final BigDecimal qty)
{
order.setQty_FastInput(qty);
}
@Override
public BigDecimal getQty()
{
return order.getQty_FastInput();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
return order.getM_HU_PI_Item_Product_ID();
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
order.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
@Override
public BigDecimal getQtyTU()
{
return order.getQty_FastInput_TU();
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
order.setQty_FastInput_TU(qtyPacks);
|
}
@Override
public void setC_BPartner_ID(final int bpartnerId)
{
order.setC_BPartner_ID(bpartnerId);
}
@Override
public int getC_BPartner_ID()
{
return order.getC_BPartner_ID();
}
@Override
public boolean isInDispute()
{
return false;
}
@Override
public void setInDispute(final boolean inDispute)
{
throw new UnsupportedOperationException();
}
@Override
public String toString()
{
return String
.format("OrderHUPackingAware [order=%s, getM_Product_ID()=%s, getM_Product()=%s, getM_AttributeSetInstance_ID()=%s, getC_UOM()=%s, getQty()=%s, getM_HU_PI_Item_Product()=%s, getQtyPacks()=%s, getC_BPartner()=%s, getM_HU_PI_Item_Product_ID()=%s, isInDispute()=%s]",
order, getM_Product_ID(), getM_Product_ID(), getM_AttributeSetInstance_ID(), getC_UOM_ID(), getQty(), getM_HU_PI_Item_Product_ID(), getQtyTU(), getC_BPartner_ID(),
getM_HU_PI_Item_Product_ID(), isInDispute());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\OrderHUPackingAware.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PageBean queryAccountListPage(PageParam pageParam, Map<String, Object> params) {
return rpAccountDao.listPage(pageParam, params);
}
/**
* 根据参数分页查询账户历史.
*
* @param pageParam
* 分页参数.
* @param params
* 查询参数,可以为null.
* @return AccountHistoryList.
* @throws BizException
*/
public PageBean queryAccountHistoryListPage(PageParam pageParam, Map<String, Object> params) {
|
return rpAccountHistoryDao.listPage(pageParam, params);
}
/**
* 获取所有账户
* @return
*/
@Override
public List<RpAccount> listAll(){
Map<String, Object> paramMap = new HashMap<String, Object>();
paramMap.put("status", PublicStatusEnum.ACTIVE.name());
return rpAccountDao.listBy(paramMap);
}
}
|
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\service\impl\RpAccountQueryServiceImpl.java
| 2
|
请完成以下Java代码
|
public class HealthEndpoint extends HealthEndpointSupport<Health, HealthDescriptor> {
/**
* Health endpoint id.
*/
public static final EndpointId ID = EndpointId.of("health");
/**
* Create a new {@link HealthEndpoint} instance.
* @param registry the health contributor registry
* @param fallbackRegistry the fallback registry or {@code null}
* @param groups the health endpoint groups
* @param slowContributorLoggingThreshold duration after which slow health indicator
* logging should occur
*/
public HealthEndpoint(HealthContributorRegistry registry,
@Nullable ReactiveHealthContributorRegistry fallbackRegistry, HealthEndpointGroups groups,
@Nullable Duration slowContributorLoggingThreshold) {
super(Contributor.blocking(registry, fallbackRegistry), groups, slowContributorLoggingThreshold);
}
@ReadOperation
public HealthDescriptor health() {
HealthDescriptor health = health(ApiVersion.V3, EMPTY_PATH);
return (health != null) ? health : IndicatedHealthDescriptor.UP;
|
}
@ReadOperation
public @Nullable HealthDescriptor healthForPath(@Selector(match = Match.ALL_REMAINING) String... path) {
return health(ApiVersion.V3, path);
}
private @Nullable HealthDescriptor health(ApiVersion apiVersion, String... path) {
Result<HealthDescriptor> result = getResult(apiVersion, null, SecurityContext.NONE, true, path);
return (result != null) ? result.descriptor() : null;
}
@Override
protected HealthDescriptor aggregateDescriptors(ApiVersion apiVersion, Map<String, HealthDescriptor> contributions,
StatusAggregator statusAggregator, boolean showComponents, @Nullable Set<String> groupNames) {
return getCompositeDescriptor(apiVersion, contributions, statusAggregator, showComponents, groupNames);
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\actuate\endpoint\HealthEndpoint.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PatientNote noteText(String noteText) {
this.noteText = noteText;
return this;
}
/**
* Text der Patientennotiz
* @return noteText
**/
@Schema(example = "MRSA positiv", description = "Text der Patientennotiz")
public String getNoteText() {
return noteText;
}
public void setNoteText(String noteText) {
this.noteText = noteText;
}
public PatientNote patientId(String patientId) {
this.patientId = patientId;
return this;
}
/**
* Id des Patienten in Alberta
* @return patientId
**/
@Schema(example = "a4adecb6-126a-4fa6-8fac-e80165ac4264", description = "Id des Patienten in Alberta")
public String getPatientId() {
return patientId;
}
public void setPatientId(String patientId) {
this.patientId = patientId;
}
public PatientNote archived(Boolean archived) {
this.archived = archived;
return this;
}
/**
* Kennzeichen, ob die Notiz vom Benutzer archiviert wurde
* @return archived
**/
@Schema(example = "false", description = "Kennzeichen, ob die Notiz vom Benutzer archiviert wurde")
public Boolean isArchived() {
return archived;
}
public void setArchived(Boolean archived) {
|
this.archived = archived;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PatientNote patientNote = (PatientNote) o;
return Objects.equals(this.status, patientNote.status) &&
Objects.equals(this.noteText, patientNote.noteText) &&
Objects.equals(this.patientId, patientNote.patientId) &&
Objects.equals(this.archived, patientNote.archived);
}
@Override
public int hashCode() {
return Objects.hash(status, noteText, patientId, archived);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class PatientNote {\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append(" noteText: ").append(toIndentedString(noteText)).append("\n");
sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).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\PatientNote.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class StudentManagementController {
//
private static final List<Student> STUDENTS = Arrays.asList(
new Student(1, "James Bond"),
new Student(2, "Lary Gaga"),
new Student(3, "Faktor2"),
new Student(4, "Anna "),
new Student(5, "Anna German ")
);
@GetMapping
public List<Student> getAllStudents(){
return STUDENTS;
}
@PostMapping
public void registerNewStudent(@RequestBody Student student){
|
System.out.println("registerNewStudent");
System.out.println(student);
}
@DeleteMapping(path = "{studentId}")
public void deleteStudent(@PathVariable() Integer studentId){
System.out.println("deleteStudent");
System.out.println(studentId);
}
@PutMapping(path = "{studentId}")
public void updateStudent(@PathVariable("studentId") Integer studentId, @RequestBody Student student){
System.out.println("Update student INFO.");
System.out.println(String.format("%s %s", studentId, student));
}
}
|
repos\SpringBoot-Projects-FullStack-master\Advanced-SpringSecure\spring-management-api\spring-management-api\src\main\java\uz\bepro\springmanagementapi\controller\StudentManagementController.java
| 2
|
请完成以下Java代码
|
private void checkParam(OrderProcessContext orderProcessContext) {
// 受理上下文为空
if (orderProcessContext == null) {
throw new CommonSysException(ExpCodeEnum.PROCESSCONTEXT_NULL);
}
// 受理请求为空
if (orderProcessContext.getOrderProcessReq() == null) {
throw new CommonSysException(ExpCodeEnum.PROCESSREQ_NULL);
}
// 受理请求枚举为空
if (orderProcessContext.getOrderProcessReq().getProcessReqEnum() == null) {
throw new CommonSysException(ExpCodeEnum.PROCESSREQ_ENUM_NULL);
}
|
// orderId为空(除下单外)
if (orderProcessContext.getOrderProcessReq().getOrderId() == null
&& orderProcessContext.getOrderProcessReq().getProcessReqEnum() != ProcessReqEnum.PlaceOrder) {
throw new CommonSysException(ExpCodeEnum.PROCESSREQ_ORDERID_NULL);
}
// userId为空
if (orderProcessContext.getOrderProcessReq().getUserId() == null) {
throw new CommonSysException(ExpCodeEnum.PROCESSREQ_USERID_NULL);
}
}
}
|
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\java\com\gaoxi\order\engine\ProcessEngine.java
| 1
|
请完成以下Spring Boot application配置
|
---
info:
scm-url: "@scm.url@"
build-url: "https://travis-ci.org/codecentric/spring-boot-admin"
logging:
level:
ROOT: info
de.codecentric: info
org.springframework.web: info
file:
name: "target/boot-admin-sample-servlet.log"
pattern:
file: "%clr(%d{yyyy-MM-dd HH:mm:ss.SSS}){faint} %clr(%5p) %clr(${PID}){magenta} %clr(---){faint} %clr([%15.15t]){faint} %clr(%-40.40logger{39}){cyan} %clr(:){faint} %m%n%wEx"
group:
Spring Boot Admin:
- de.codecentric.boot.admin.server
- de.codecentric.boot.admin.client
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
refresh:
enabled: true
restart:
enabled: true
shutdown:
enabled: true
env:
post:
enabled: true
health:
show-details: ALWAYS
spring:
application:
name: spring-boot-admin-sample-servlet
cloud:
discovery:
client:
simple:
instances:
SBA:
- uri: http://localhost:8080
metadata:
management.context-path: /actuator
service-url: http://localhost:8080
service-path: /
boot:
admin:
client:
url: http://localhost:8080
instance:
service-host-type: IP
metadata:
service-path: /foo
service-url: http://localhost:8080
hide-url: true
tags:
environment: test
de-service-test-1: A large content
de-service-test-2: A large content
de-service-test-3: A large content
de-service-test-4: A large content
de-service-test-5: A large content
de-service-test-6: A large content
kubectl.kubernetes.io/last-applied-configuration: '{"name":"jvm.threads.peak","description":"The peak live thread count since the Java virtual machine started or peak was reset","baseUnit":"threads","measurements":[{"statistic":"VALUE","value":64.0}],"availableTags":[]}'
config:
import: optional:configserver:http://localhost:8888/
jmx:
enabled: true
main:
lazy-initialization: true
---
# tag::customization-external-views-simple-link[]
spring:
boot:
admin:
ui:
external-views:
- label: "🚀" #<1>
url: "https://codecentric.de" #<2>
order: 2000 #<3>
# end::customization-external-views-simple-link[]
---
# tag::customization-external-views-dropdown-with-links[]
spring:
boot:
admin:
ui:
external-views:
- label: Link w/o children
children:
- label: "📖 Docs"
url: https://codecentric.github.io/spring-boot-admin/current/
- label: "📦 Maven"
url: https://search.maven.org/search?q=g:de.codecentric%20AND%20a:spring-boot-admin-starter-ser
|
ver
- label: "🐙 GitHub"
url: https://github.com/codecentric/spring-boot-admin
# end::customization-external-views-dropdown-with-links[]
---
# tag::customization-external-views-dropdown-is-link-with-links-as-children[]
spring:
boot:
admin:
ui:
external-views:
- label: Link w children
url: https://codecentric.de #<1>
children:
- label: "📖 Docs"
url: https://codecentric.github.io/spring-boot-admin/current/
- label: "📦 Maven"
url: https://search.maven.org/search?q=g:de.codecentric%20AND%20a:spring-boot-admin-starter-server
- label: "🐙 GitHub"
url: https://github.com/codecentric/spring-boot-admin
- label: "🎅 Is it christmas"
url: https://isitchristmas.com
iframe: true
# end::customization-external-views-dropdown-is-link-with-links-as-children[]
---
# tag::customization-view-settings[]
spring:
boot:
admin:
ui:
view-settings:
- name: "journal"
enabled: false
# end::customization-view-settings[]
management:
endpoint:
sbom:
application:
location: classpath:bom.json
|
repos\spring-boot-admin-master\spring-boot-admin-samples\spring-boot-admin-sample-servlet\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public class FastJsonRedisSerializer<T> implements RedisSerializer<T> {
public static final Charset DEFAULT_CHARSET = Charset.forName("UTF-8");
public static final String EMPTY_OBJECT_FLAG = "EMPTY_OBJECT_FLAG_@$#";
private Class<T> clazz;
public FastJsonRedisSerializer(Class<T> clazz) {
super();
this.clazz = clazz;
}
@Override
public byte[] serialize(T t) throws SerializationException {
if (t == null || t instanceof NullValue) {
// 如果是NULL,则存空对象标示
return EMPTY_OBJECT_FLAG.getBytes(DEFAULT_CHARSET);
|
}
return JSON.toJSONString(t, SerializerFeature.WriteClassName).getBytes(DEFAULT_CHARSET);
}
@Override
public T deserialize(byte[] bytes) throws SerializationException {
if (bytes == null || bytes.length <= 0) {
return null;
}
String str = new String(bytes, DEFAULT_CHARSET);
// 判断存储对象是否是NULL,是就返回null
if (EMPTY_OBJECT_FLAG.equals(str)) {
return null;
}
return (T) JSON.parseObject(str, clazz);
}
}
|
repos\spring-boot-student-master\spring-boot-student-cache-redis-caffeine\src\main\java\com\xiaolyuh\cache\redis\serializer\FastJsonRedisSerializer.java
| 1
|
请完成以下Java代码
|
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 Serial No.
@param SerNo
Product Serial Number
*/
public void setSerNo (String SerNo)
{
set_Value (COLUMNNAME_SerNo, SerNo);
}
/** Get Serial No.
@return Product Serial Number
*/
public String getSerNo ()
{
return (String)get_Value(COLUMNNAME_SerNo);
}
/** Set Usable Life - Months.
@param UseLifeMonths
Months of the usable life of the asset
*/
public void setUseLifeMonths (int UseLifeMonths)
{
set_Value (COLUMNNAME_UseLifeMonths, Integer.valueOf(UseLifeMonths));
}
/** Get Usable Life - Months.
@return Months of the usable life of the asset
*/
public int getUseLifeMonths ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeMonths);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usable Life - Years.
@param UseLifeYears
Years of the usable life of the asset
*/
public void setUseLifeYears (int UseLifeYears)
{
set_Value (COLUMNNAME_UseLifeYears, Integer.valueOf(UseLifeYears));
}
/** Get Usable Life - Years.
@return Years of the usable life of the asset
*/
public int getUseLifeYears ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeYears);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Use units.
@param UseUnits
|
Currently used units of the assets
*/
public void setUseUnits (int UseUnits)
{
set_Value (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits));
}
/** Get Use units.
@return Currently used units of the assets
*/
public int getUseUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Version No.
@param VersionNo
Version Number
*/
public void setVersionNo (String VersionNo)
{
set_Value (COLUMNNAME_VersionNo, VersionNo);
}
/** Get Version No.
@return Version Number
*/
public String getVersionNo ()
{
return (String)get_Value(COLUMNNAME_VersionNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Asset.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Saml2JacksonModule extends SecurityJacksonModule {
public Saml2JacksonModule() {
super(Saml2JacksonModule.class.getName(), new Version(1, 0, 0, null, null, null));
}
@Override
public void configurePolymorphicTypeValidator(BasicPolymorphicTypeValidator.Builder builder) {
builder.allowIfSubType(Saml2ResponseAssertion.class)
.allowIfSubType(DefaultSaml2AuthenticatedPrincipal.class)
.allowIfSubType(Saml2PostAuthenticationRequest.class)
.allowIfSubType(Saml2LogoutRequest.class)
.allowIfSubType(Saml2RedirectAuthenticationRequest.class)
.allowIfSubType(Saml2AuthenticationException.class)
.allowIfSubType(Saml2Error.class)
.allowIfSubType(Saml2AssertionAuthentication.class)
.allowIfSubType(Saml2Authentication.class);
}
|
@Override
public void setupModule(SetupContext context) {
context.setMixIn(Saml2Authentication.class, Saml2AuthenticationMixin.class);
context.setMixIn(Saml2AssertionAuthentication.class, Saml2AssertionAuthenticationMixin.class);
context.setMixIn(Saml2ResponseAssertion.class, SimpleSaml2ResponseAssertionAccessorMixin.class);
context.setMixIn(DefaultSaml2AuthenticatedPrincipal.class, DefaultSaml2AuthenticatedPrincipalMixin.class);
context.setMixIn(Saml2LogoutRequest.class, Saml2LogoutRequestMixin.class);
context.setMixIn(Saml2RedirectAuthenticationRequest.class, Saml2RedirectAuthenticationRequestMixin.class);
context.setMixIn(Saml2PostAuthenticationRequest.class, Saml2PostAuthenticationRequestMixin.class);
context.setMixIn(Saml2Error.class, Saml2ErrorMixin.class);
context.setMixIn(Saml2AuthenticationException.class, Saml2AuthenticationExceptionMixin.class);
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\jackson\Saml2JacksonModule.java
| 2
|
请完成以下Java代码
|
public List<HistoricPlanItemInstance> findByCaseDefinitionId(String caseDefinitionId) {
List<? extends HistoricPlanItemInstance> list = getList("selectHistoricPlanItemInstancesByCaseDefinitionId", caseDefinitionId, historicPlanItemInstanceByCaseDefinitionIdMatcher, true);
return (List<HistoricPlanItemInstance>) list;
}
@Override
public long countByCriteria(HistoricPlanItemInstanceQueryImpl query) {
setSafeInValueLists(query);
return (Long) getDbSqlSession().selectOne("selectHistoricPlanItemInstancesCountByQueryCriteria", query);
}
@Override
public void deleteByCaseDefinitionId(String caseDefinitionId) {
getDbSqlSession().delete("deleteHistoricPlanItemInstanceByCaseDefinitionId", caseDefinitionId, getManagedEntityClass());
}
@Override
public void bulkDeleteHistoricPlanItemInstancesForCaseInstanceIds(Collection<String> caseInstanceIds) {
getDbSqlSession().delete("bulkDeleteHistoricPlanItemInstancesByCaseInstanceIds", createSafeInValuesList(caseInstanceIds), getManagedEntityClass());
}
@Override
public void deleteHistoricPlanItemInstancesForNonExistingCaseInstances() {
getDbSqlSession().delete("bulkDeleteHistoricPlanItemInstancesForNonExistingCaseInstances", null, getManagedEntityClass());
}
@Override
@SuppressWarnings("unchecked")
public List<HistoricPlanItemInstance> findWithVariablesByCriteria(HistoricPlanItemInstanceQueryImpl historicPlanItemInstanceQuery) {
setSafeInValueLists(historicPlanItemInstanceQuery);
return getDbSqlSession().selectList("selectHistoricPlanItemInstancesWithLocalVariablesByQueryCriteria", historicPlanItemInstanceQuery,
getManagedEntityClass());
}
@Override
public Class<? extends HistoricPlanItemInstanceEntity> getManagedEntityClass() {
return HistoricPlanItemInstanceEntityImpl.class;
}
|
@Override
public HistoricPlanItemInstanceEntity create() {
return new HistoricPlanItemInstanceEntityImpl();
}
@Override
public HistoricPlanItemInstanceEntity create(PlanItemInstance planItemInstance) {
return new HistoricPlanItemInstanceEntityImpl(planItemInstance);
}
protected void setSafeInValueLists(HistoricPlanItemInstanceQueryImpl planItemInstanceQuery) {
if (planItemInstanceQuery.getInvolvedGroups() != null) {
planItemInstanceQuery.setSafeInvolvedGroups(createSafeInValuesList(planItemInstanceQuery.getInvolvedGroups()));
}
if(planItemInstanceQuery.getCaseInstanceIds() != null) {
planItemInstanceQuery.setSafeCaseInstanceIds(createSafeInValuesList(planItemInstanceQuery.getCaseInstanceIds()));
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisHistoricPlanItemInstanceDataManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getCARRIERDESC() {
return carrierdesc;
}
/**
* Sets the value of the carrierdesc property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCARRIERDESC(String value) {
this.carrierdesc = value;
}
/**
* Gets the value of the locationqual property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONQUAL() {
return locationqual;
}
/**
* Sets the value of the locationqual property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONQUAL(String value) {
this.locationqual = value;
}
/**
* Gets the value of the locationcode property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONCODE() {
return locationcode;
}
/**
* Sets the value of the locationcode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONCODE(String value) {
this.locationcode = value;
}
|
/**
* Gets the value of the locationname property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONNAME() {
return locationname;
}
/**
* Sets the value of the locationname property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONNAME(String value) {
this.locationname = value;
}
/**
* Gets the value of the locationdate property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getLOCATIONDATE() {
return locationdate;
}
/**
* Sets the value of the locationdate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setLOCATIONDATE(String value) {
this.locationdate = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DTRSD1.java
| 2
|
请完成以下Java代码
|
public static Object instantiateDelegate(String className, List<FieldDeclaration> fieldDeclarations) {
Object object = ReflectUtil.instantiate(className);
applyFieldDeclaration(fieldDeclarations, object);
return object;
}
public static void applyFieldDeclaration(List<FieldDeclaration> fieldDeclarations, Object target) {
if (fieldDeclarations != null) {
for (FieldDeclaration declaration : fieldDeclarations) {
applyFieldDeclaration(declaration, target);
}
}
}
public static void applyFieldDeclaration(FieldDeclaration declaration, Object target) {
Method setterMethod = ReflectUtil.getSetter(declaration.getName(), target.getClass(), declaration.getValue().getClass());
if (setterMethod != null) {
try {
setterMethod.invoke(target, declaration.getValue());
} catch (IllegalArgumentException e) {
throw new FlowableException("Error while invoking '" + declaration.getName() + "' on class " + target.getClass().getName(), e);
} catch (IllegalAccessException e) {
throw new FlowableException("Illegal access when calling '" + declaration.getName() + "' on class " + target.getClass().getName(), e);
} catch (InvocationTargetException e) {
throw new FlowableException("Exception while invoking '" + declaration.getName() + "' on class " + target.getClass().getName(), e);
}
|
} else {
Field field = ReflectUtil.getField(declaration.getName(), target);
if (field == null) {
throw new FlowableIllegalArgumentException("Field definition uses non-existing field '" + declaration.getName() + "' on class " + target.getClass().getName());
}
// Check if the delegate field's type is correct
if (!fieldTypeCompatible(declaration, field)) {
throw new FlowableIllegalArgumentException("Incompatible type set on field declaration '" + declaration.getName() + "' for class " + target.getClass().getName() + ". Declared value has type "
+ declaration.getValue().getClass().getName() + ", while expecting " + field.getType().getName());
}
ReflectUtil.setField(field, target, declaration.getValue());
}
}
public static boolean fieldTypeCompatible(FieldDeclaration declaration, Field field) {
if (declaration.getValue() != null) {
return field.getType().isAssignableFrom(declaration.getValue().getClass());
} else {
// Null can be set any field type
return true;
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\helper\ClassDelegateUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PaymentAllocationBuilder allowPartialAllocations(final boolean allowPartialAllocations)
{
assertNotBuilt();
this.allowPartialAllocations = allowPartialAllocations;
return this;
}
public PaymentAllocationBuilder allowInvoiceToCreditMemoAllocation(final boolean allowInvoiceToCreditMemoAllocation)
{
assertNotBuilt();
this.allowInvoiceToCreditMemoAllocation = allowInvoiceToCreditMemoAllocation;
return this;
}
public PaymentAllocationBuilder allowPurchaseSalesInvoiceCompensation(final boolean allowPurchaseSalesInvoiceCompensation)
{
assertNotBuilt();
this.allowPurchaseSalesInvoiceCompensation = allowPurchaseSalesInvoiceCompensation;
return this;
}
public PaymentAllocationBuilder payableRemainingOpenAmtPolicy(@NonNull final PayableRemainingOpenAmtPolicy payableRemainingOpenAmtPolicy)
{
assertNotBuilt();
this.payableRemainingOpenAmtPolicy = payableRemainingOpenAmtPolicy;
return this;
}
public PaymentAllocationBuilder dryRun()
{
this.dryRun = true;
return this;
}
public PaymentAllocationBuilder payableDocuments(final Collection<PayableDocument> payableDocuments)
{
_payableDocuments = ImmutableList.copyOf(payableDocuments);
return this;
}
public PaymentAllocationBuilder paymentDocuments(final Collection<PaymentDocument> paymentDocuments)
{
_paymentDocuments = ImmutableList.copyOf(paymentDocuments);
return this;
}
public PaymentAllocationBuilder paymentDocument(final PaymentDocument paymentDocument)
{
return paymentDocuments(ImmutableList.of(paymentDocument));
}
@VisibleForTesting
final ImmutableList<PayableDocument> getPayableDocuments()
{
|
return _payableDocuments;
}
@VisibleForTesting
final ImmutableList<PaymentDocument> getPaymentDocuments()
{
return _paymentDocuments;
}
public PaymentAllocationBuilder invoiceProcessingServiceCompanyService(@NonNull final InvoiceProcessingServiceCompanyService invoiceProcessingServiceCompanyService)
{
assertNotBuilt();
this.invoiceProcessingServiceCompanyService = invoiceProcessingServiceCompanyService;
return this;
}
/**
* @param allocatePayableAmountsAsIs if true, we allow the allocated amount to exceed the payment's amount,
* if the given payable is that big.
* We need this behavior when we want to allocate a remittance advice and know that *in sum* the payables' amounts will match the payment
*/
public PaymentAllocationBuilder allocatePayableAmountsAsIs(final boolean allocatePayableAmountsAsIs)
{
assertNotBuilt();
this.allocatePayableAmountsAsIs = allocatePayableAmountsAsIs;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\paymentallocation\service\PaymentAllocationBuilder.java
| 2
|
请完成以下Java代码
|
public void setModelValidationClass (String ModelValidationClass)
{
set_Value (COLUMNNAME_ModelValidationClass, ModelValidationClass);
}
/** Get Model Validation Class.
@return Model Validation Class */
public String getModelValidationClass ()
{
return (String)get_Value(COLUMNNAME_ModelValidationClass);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
|
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ModelValidator.java
| 1
|
请完成以下Java代码
|
public PostalAddress6CH createPostalAddress6CH() {
return new PostalAddress6CH();
}
/**
* Create an instance of {@link Purpose2CHCode }
*
*/
public Purpose2CHCode createPurpose2CHCode() {
return new Purpose2CHCode();
}
/**
* Create an instance of {@link ReferredDocumentInformation3 }
*
*/
public ReferredDocumentInformation3 createReferredDocumentInformation3() {
return new ReferredDocumentInformation3();
}
/**
* Create an instance of {@link ReferredDocumentType1Choice }
*
*/
public ReferredDocumentType1Choice createReferredDocumentType1Choice() {
return new ReferredDocumentType1Choice();
}
/**
* Create an instance of {@link ReferredDocumentType2 }
*
*/
public ReferredDocumentType2 createReferredDocumentType2() {
return new ReferredDocumentType2();
}
/**
* Create an instance of {@link RegulatoryAuthority2 }
*
*/
public RegulatoryAuthority2 createRegulatoryAuthority2() {
return new RegulatoryAuthority2();
}
/**
* Create an instance of {@link RegulatoryReporting3 }
*
*/
public RegulatoryReporting3 createRegulatoryReporting3() {
return new RegulatoryReporting3();
}
/**
* Create an instance of {@link RemittanceAmount1 }
*
*/
public RemittanceAmount1 createRemittanceAmount1() {
return new RemittanceAmount1();
}
/**
* Create an instance of {@link RemittanceInformation5CH }
*
*/
public RemittanceInformation5CH createRemittanceInformation5CH() {
return new RemittanceInformation5CH();
}
/**
* Create an instance of {@link ServiceLevel8Choice }
*
*/
public ServiceLevel8Choice createServiceLevel8Choice() {
return new ServiceLevel8Choice();
|
}
/**
* Create an instance of {@link StructuredRegulatoryReporting3 }
*
*/
public StructuredRegulatoryReporting3 createStructuredRegulatoryReporting3() {
return new StructuredRegulatoryReporting3();
}
/**
* Create an instance of {@link StructuredRemittanceInformation7 }
*
*/
public StructuredRemittanceInformation7 createStructuredRemittanceInformation7() {
return new StructuredRemittanceInformation7();
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >}
*/
@XmlElementDecl(namespace = "http://www.six-interbank-clearing.com/de/pain.001.001.03.ch.02.xsd", name = "Document")
public JAXBElement<Document> createDocument(Document value) {
return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\ObjectFactory.java
| 1
|
请完成以下Java代码
|
public Record1<Integer> key() {
return (Record1) super.key();
}
// -------------------------------------------------------------------------
// Record4 type implementation
// -------------------------------------------------------------------------
@Override
public Row4<Integer, String, String, Integer> fieldsRow() {
return (Row4) super.fieldsRow();
}
@Override
public Row4<Integer, String, String, Integer> valuesRow() {
return (Row4) super.valuesRow();
}
@Override
public Field<Integer> field1() {
return Author.AUTHOR.ID;
}
@Override
public Field<String> field2() {
return Author.AUTHOR.FIRST_NAME;
}
@Override
public Field<String> field3() {
return Author.AUTHOR.LAST_NAME;
}
@Override
public Field<Integer> field4() {
return Author.AUTHOR.AGE;
}
@Override
public Integer component1() {
return getId();
}
@Override
public String component2() {
return getFirstName();
}
@Override
public String component3() {
return getLastName();
}
@Override
public Integer component4() {
return getAge();
}
@Override
public Integer value1() {
return getId();
}
@Override
public String value2() {
return getFirstName();
}
@Override
public String value3() {
return getLastName();
}
@Override
public Integer value4() {
return getAge();
}
@Override
public AuthorRecord value1(Integer value) {
setId(value);
return this;
}
@Override
public AuthorRecord value2(String value) {
setFirstName(value);
return this;
}
@Override
public AuthorRecord value3(String value) {
|
setLastName(value);
return this;
}
@Override
public AuthorRecord value4(Integer value) {
setAge(value);
return this;
}
@Override
public AuthorRecord values(Integer value1, String value2, String value3, Integer value4) {
value1(value1);
value2(value2);
value3(value3);
value4(value4);
return this;
}
// -------------------------------------------------------------------------
// Constructors
// -------------------------------------------------------------------------
/**
* Create a detached AuthorRecord
*/
public AuthorRecord() {
super(Author.AUTHOR);
}
/**
* Create a detached, initialised AuthorRecord
*/
public AuthorRecord(Integer id, String firstName, String lastName, Integer age) {
super(Author.AUTHOR);
set(0, id);
set(1, firstName);
set(2, lastName);
set(3, age);
}
}
|
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\model\tables\records\AuthorRecord.java
| 1
|
请完成以下Java代码
|
private void setPlannedQtyPerUnit(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (importRecord.getQty() != null && importRecord.getQty().intValue() > 0)
{
contract.setPlannedQtyPerUnit(importRecord.getQty());
}
}
private void setEndDate(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (importRecord.getEndDate() != null)
{
contract.setEndDate(importRecord.getEndDate());
}
}
private void setMasterStartdDate(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (importRecord.getMasterStartDate() != null)
{
contract.setMasterStartDate(importRecord.getMasterStartDate());
}
}
private void setMasterEnddDate(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (importRecord.getMasterEndDate() != null)
{
contract.setMasterEndDate(importRecord.getMasterEndDate());
}
}
private boolean isEndedContract(@NonNull final I_I_Flatrate_Term importRecord)
{
final Timestamp contractEndDate = importRecord.getEndDate();
final Timestamp today = SystemTime.asDayTimestamp();
return contractEndDate != null && today.after(contractEndDate);
|
}
private void endContractIfNeeded(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract)
{
if (isEndedContract(importRecord))
{
contract.setContractStatus(X_C_Flatrate_Term.CONTRACTSTATUS_Quit);
contract.setNoticeDate(contract.getEndDate());
contract.setIsAutoRenew(false);
contract.setProcessed(true);
contract.setDocAction(X_C_Flatrate_Term.DOCACTION_None);
contract.setDocStatus(X_C_Flatrate_Term.DOCSTATUS_Completed);
}
}
private void setTaxCategoryAndIsTaxIncluded(@NonNull final I_C_Flatrate_Term newTerm)
{
final IPricingResult pricingResult = calculateFlatrateTermPrice(newTerm);
newTerm.setC_TaxCategory_ID(TaxCategoryId.toRepoId(pricingResult.getTaxCategoryId()));
newTerm.setIsTaxIncluded(pricingResult.isTaxIncluded());
}
private IPricingResult calculateFlatrateTermPrice(@NonNull final I_C_Flatrate_Term newTerm)
{
return FlatrateTermPricing.builder()
.termRelatedProductId(ProductId.ofRepoId(newTerm.getM_Product_ID()))
.qty(newTerm.getPlannedQtyPerUnit())
.term(newTerm)
.priceDate(TimeUtil.asLocalDate(newTerm.getStartDate()))
.build()
.computeOrThrowEx();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\impexp\FlatrateTermImporter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Collection<Saml2Error> getErrors() {
return Collections.unmodifiableCollection(this.errors);
}
/**
* Construct a successful {@link Saml2LogoutValidatorResult}
* @return an {@link Saml2LogoutValidatorResult} with no errors
*/
public static Saml2LogoutValidatorResult success() {
return NO_ERRORS;
}
/**
* Construct a {@link Saml2LogoutValidatorResult.Builder}, starting with the given
* {@code errors}.
*
* Note that a result with no errors is considered a success.
* @param errors
* @return
*/
public static Saml2LogoutValidatorResult.Builder withErrors(Saml2Error... errors) {
return new Builder(errors);
}
public static final class Builder {
private final Collection<Saml2Error> errors;
private Builder(Saml2Error... errors) {
this(Arrays.asList(errors));
|
}
private Builder(Collection<Saml2Error> errors) {
Assert.noNullElements(errors, "errors cannot have null elements");
this.errors = new ArrayList<>(errors);
}
public Builder errors(Consumer<Collection<Saml2Error>> errorsConsumer) {
errorsConsumer.accept(this.errors);
return this;
}
public Saml2LogoutValidatorResult build() {
return new Saml2LogoutValidatorResult(this.errors);
}
}
}
|
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\authentication\logout\Saml2LogoutValidatorResult.java
| 2
|
请完成以下Java代码
|
public void setCS_Creditpass_BP_Group_ID (int CS_Creditpass_BP_Group_ID)
{
if (CS_Creditpass_BP_Group_ID < 1)
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_BP_Group_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_BP_Group_ID, Integer.valueOf(CS_Creditpass_BP_Group_ID));
}
/** Get CS Creditpass business partner group.
@return CS Creditpass business partner group */
@Override
public int getCS_Creditpass_BP_Group_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CS_Creditpass_BP_Group_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config getCS_Creditpass_Config() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_CS_Creditpass_Config_ID, de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config.class);
}
@Override
public void setCS_Creditpass_Config(de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config CS_Creditpass_Config)
|
{
set_ValueFromPO(COLUMNNAME_CS_Creditpass_Config_ID, de.metas.vertical.creditscore.creditpass.model.I_CS_Creditpass_Config.class, CS_Creditpass_Config);
}
/** Get Creditpass Einstellung.
@return Creditpass Einstellung */
@Override
public int getCS_Creditpass_Config_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CS_Creditpass_Config_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Creditpass Einstellung.
@param CS_Creditpass_Config_ID Creditpass Einstellung */
@Override
public void setCS_Creditpass_Config_ID (int CS_Creditpass_Config_ID)
{
if (CS_Creditpass_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CS_Creditpass_Config_ID, Integer.valueOf(CS_Creditpass_Config_ID));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.creditscore\creditpass\src\main\java-gen\de\metas\vertical\creditscore\creditpass\model\X_CS_Creditpass_BP_Group.java
| 1
|
请完成以下Java代码
|
public String getSingleValue(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider)
{
return concatValues(getValueList(attributeType, valueProvider));
}
@NonNull
private ImmutableList<String> getValueList(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider)
{
return streamEligibleConfigs(attributeType, valueProvider)
.map(config -> valueProvider.apply(config.getAttributeValue()))
.filter(Check::isNotBlank)
.collect(ImmutableList.toImmutableList());
}
public ImmutableList<String> getDetailGroupKeysForType(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider)
{
return streamEligibleConfigs(attributeType, valueProvider)
.map(JsonMappingConfig::getGroupKey)
.filter(Check::isNotBlank)
.distinct()
.collect(ImmutableList.toImmutableList());
}
public List<JsonDetail> getDetailsForGroupAndType(
@NonNull final String attributeGroupKey,
@NonNull final String attributeType,
|
@NonNull final Function<String, String> valueProvider)
{
final Map<Integer, String> detailsByKindId = streamEligibleConfigs(attributeType, valueProvider)
.filter(config -> attributeGroupKey.equals(config.getGroupKey()))
.filter(config -> Check.isNotBlank(config.getAttributeKey()))
.map(config -> new AbstractMap.SimpleImmutableEntry<>(
Integer.parseInt(config.getAttributeKey()),
valueProvider.apply(config.getAttributeValue())))
.filter(entry -> Check.isNotBlank(entry.getValue()))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.joining(" "))));
return detailsByKindId.entrySet().stream()
.map(entry -> JsonDetail.builder()
.kindId(entry.getKey())
.value(entry.getValue())
.build())
.collect(Collectors.toList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftMappingConfigs.java
| 1
|
请完成以下Java代码
|
public abstract class BaseElementImpl extends BpmnModelElementInstanceImpl implements BaseElement {
protected static Attribute<String> idAttribute;
protected static ChildElementCollection<Documentation> documentationCollection;
protected static ChildElement<ExtensionElements> extensionElementsChild;
public static void registerType(ModelBuilder bpmnModelBuilder) {
ModelElementTypeBuilder typeBuilder = bpmnModelBuilder.defineType(BaseElement.class, BPMN_ELEMENT_BASE_ELEMENT)
.namespaceUri(BPMN20_NS)
.abstractType();
idAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ID)
.idAttribute()
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
documentationCollection = sequenceBuilder.elementCollection(Documentation.class)
.build();
extensionElementsChild = sequenceBuilder.element(ExtensionElements.class)
.build();
typeBuilder.build();
}
public BaseElementImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public String getId() {
return idAttribute.getValue(this);
}
public void setId(String id) {
idAttribute.setValue(this, id);
}
public Collection<Documentation> getDocumentations() {
return documentationCollection.get(this);
}
public ExtensionElements getExtensionElements() {
return extensionElementsChild.getChild(this);
}
public void setExtensionElements(ExtensionElements extensionElements) {
extensionElementsChild.setChild(this, extensionElements);
}
@SuppressWarnings("rawtypes")
public DiagramElement getDiagramElement() {
Collection<Reference> incomingReferences = getIncomingReferencesByType(DiagramElement.class);
for (Reference<?> reference : incomingReferences) {
for (ModelElementInstance sourceElement : reference.findReferenceSourceElements(this)) {
|
String referenceIdentifier = reference.getReferenceIdentifier(sourceElement);
if (referenceIdentifier != null && referenceIdentifier.equals(getId())) {
return (DiagramElement) sourceElement;
}
}
}
return null;
}
@SuppressWarnings("rawtypes")
public Collection<Reference> getIncomingReferencesByType(Class<? extends ModelElementInstance> referenceSourceTypeClass) {
Collection<Reference> references = new ArrayList<Reference>();
// we traverse all incoming references in reverse direction
for (Reference<?> reference : idAttribute.getIncomingReferences()) {
ModelElementType sourceElementType = reference.getReferenceSourceElementType();
Class<? extends ModelElementInstance> sourceInstanceType = sourceElementType.getInstanceType();
// if the referencing element (source element) is a BPMNDI element, dig deeper
if (referenceSourceTypeClass.isAssignableFrom(sourceInstanceType)) {
references.add(reference);
}
}
return references;
}
}
|
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\BaseElementImpl.java
| 1
|
请完成以下Java代码
|
public class CalculatorOperationHandler extends SimpleChannelInboundHandler<Operation> {
protected void channelRead0(ChannelHandlerContext ctx, Operation msg) throws Exception {
Long result = calculateEndpoint(msg);
sendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CREATED), result.toString());
ctx.fireChannelRead(result);
}
private long calculateEndpoint(Operation operation) {
String operator = operation.getOperator().toLowerCase().trim();
switch (operator) {
case "add":
return operation.getNumber1() + operation.getNumber2();
case "multiply":
return operation.getNumber1() * operation.getNumber2();
default:
throw new IllegalArgumentException("Operation not defined");
}
}
public static void sendHttpResponse(ChannelHandlerContext ctx, FullHttpResponse res, String content) {
|
// Generate an error page if response getStatus code is not OK (200).
ByteBuf buf = Unpooled.copiedBuffer(content, CharsetUtil.UTF_8);
res.content().writeBytes(buf);
HttpUtil.setContentLength(res, res.content().readableBytes());
ctx.channel().writeAndFlush(res);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
throws Exception {
sendHttpResponse(ctx, new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.INTERNAL_SERVER_ERROR), "Operation not defined");
ctx.fireExceptionCaught(cause);
}
}
|
repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\netty\CalculatorOperationHandler.java
| 1
|
请完成以下Java代码
|
public Object getValue(ELContext context, Object base, Object property) {
Objects.requireNonNull(context, "context is null");
if (isResolvable(base)) {
int idx = coerce(property);
context.setPropertyResolved(base, property);
List<?> list = (List<?>) base;
if (idx < 0 || idx >= list.size()) {
return null;
}
return list.get(idx);
}
return null;
}
@Override
public void setValue(ELContext context, Object base, Object property, Object value) {
Objects.requireNonNull(context, "context is null");
if (isResolvable(base)) {
context.setPropertyResolved(base, property);
@SuppressWarnings("unchecked") // Must be OK to cast to Object
List<Object> list = (List<Object>) base;
if (readOnly) {
throw new PropertyNotWritableException("resolver is read-only");
}
int idx = coerce(property);
try {
list.set(idx, value);
} catch (UnsupportedOperationException e) {
throw new PropertyNotWritableException(e);
} catch (IndexOutOfBoundsException e) {
throw new PropertyNotFoundException(e);
}
}
}
@Override
public boolean isReadOnly(ELContext context, Object base, Object property) {
Objects.requireNonNull(context, "context is null");
if (isResolvable(base)) {
List<?> list = (List<?>) base;
context.setPropertyResolved(base, property);
try {
int idx = coerce(property);
checkBounds(list, idx);
} catch (IllegalArgumentException e) {
// ignore
}
return this.readOnly || UNMODIFIABLE.equals(list.getClass());
}
return readOnly;
}
@Override
public Class<?> getCommonPropertyType(ELContext context, Object base) {
return isResolvable(base) ? Integer.class : null;
}
/**
* Test whether the given base should be resolved by this ELResolver.
*
* @param base
* The bean to analyze.
|
* @return base instanceof List
*/
private static boolean isResolvable(Object base) {
return base instanceof List<?>;
}
private static void checkBounds(List<?> list, int idx) {
if (idx < 0 || idx >= list.size()) {
throw new PropertyNotFoundException(new ArrayIndexOutOfBoundsException(idx).getMessage());
}
}
private static int coerce(Object property) {
if (property instanceof Number) {
return ((Number) property).intValue();
}
if (property instanceof Character) {
return (Character) property;
}
if (property instanceof Boolean) {
return (Boolean) property ? 1 : 0;
}
if (property instanceof String) {
try {
return Integer.parseInt((String) property);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Cannot parse list index: " + property, e);
}
}
throw new IllegalArgumentException("Cannot coerce property to list index: " + property);
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\javax\el\ListELResolver.java
| 1
|
请完成以下Java代码
|
default String getClientName() {
return getClaimAsString(OAuth2ClientMetadataClaimNames.CLIENT_NAME);
}
/**
* Returns the redirection {@code URI} values used by the Client
* {@code (redirect_uris)}.
* @return the redirection {@code URI} values used by the Client
*/
default List<String> getRedirectUris() {
return getClaimAsStringList(OAuth2ClientMetadataClaimNames.REDIRECT_URIS);
}
/**
* Returns the authentication method used by the Client for the Token Endpoint
* {@code (token_endpoint_auth_method)}.
* @return the authentication method used by the Client for the Token Endpoint
*/
default String getTokenEndpointAuthenticationMethod() {
return getClaimAsString(OAuth2ClientMetadataClaimNames.TOKEN_ENDPOINT_AUTH_METHOD);
}
/**
* Returns the OAuth 2.0 {@code grant_type} values that the Client will restrict
* itself to using {@code (grant_types)}.
* @return the OAuth 2.0 {@code grant_type} values that the Client will restrict
* itself to using
*/
default List<String> getGrantTypes() {
return getClaimAsStringList(OAuth2ClientMetadataClaimNames.GRANT_TYPES);
}
|
/**
* Returns the OAuth 2.0 {@code response_type} values that the Client will restrict
* itself to using {@code (response_types)}.
* @return the OAuth 2.0 {@code response_type} values that the Client will restrict
* itself to using
*/
default List<String> getResponseTypes() {
return getClaimAsStringList(OAuth2ClientMetadataClaimNames.RESPONSE_TYPES);
}
/**
* Returns the OAuth 2.0 {@code scope} values that the Client will restrict itself to
* using {@code (scope)}.
* @return the OAuth 2.0 {@code scope} values that the Client will restrict itself to
* using
*/
default List<String> getScopes() {
return getClaimAsStringList(OAuth2ClientMetadataClaimNames.SCOPE);
}
/**
* Returns the {@code URL} for the Client's JSON Web Key Set {@code (jwks_uri)}.
* @return the {@code URL} for the Client's JSON Web Key Set {@code (jwks_uri)}
*/
default URL getJwkSetUrl() {
return getClaimAsURL(OAuth2ClientMetadataClaimNames.JWKS_URI);
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\OAuth2ClientMetadataClaimAccessor.java
| 1
|
请完成以下Java代码
|
public SqlAndParams buildOrderBy(@NonNull final String selectionTableAlias)
{
return SqlAndParams.of(selectionTableAlias + "." + I_T_ES_FTS_Search_Result.COLUMNNAME_Line);
}
}
//
//
// ------------------------------
//
//
@EqualsAndHashCode
@ToString
@NonFinal // because we want to mock it while testing
public static class RecordsToAlwaysIncludeSql
{
@NonNull private final SqlAndParams sqlAndParams;
private RecordsToAlwaysIncludeSql(@NonNull final SqlAndParams sqlAndParams)
{
if (sqlAndParams.isEmpty())
{
throw new AdempiereException("empty sqlAndParams is not allowed");
}
this.sqlAndParams = sqlAndParams;
}
public static RecordsToAlwaysIncludeSql ofColumnNameAndRecordIds(@NonNull final String columnName, @NonNull final Collection<?> recordIds)
{
final InArrayQueryFilter<?> builder = new InArrayQueryFilter<>(columnName, recordIds)
.setEmbedSqlParams(false);
final SqlAndParams sqlAndParams = SqlAndParams.of(builder.getSql(), builder.getSqlParams(Env.getCtx()));
return new RecordsToAlwaysIncludeSql(sqlAndParams);
}
public static RecordsToAlwaysIncludeSql ofColumnNameAndRecordIds(@NonNull final String columnName, @NonNull final Object... recordIds)
{
return ofColumnNameAndRecordIds(columnName, Arrays.asList(recordIds));
|
}
@Nullable
public static RecordsToAlwaysIncludeSql mergeOrNull(@Nullable final Collection<RecordsToAlwaysIncludeSql> collection)
{
if (collection == null || collection.isEmpty())
{
return null;
}
else if (collection.size() == 1)
{
return collection.iterator().next();
}
else
{
return SqlAndParams.orNullables(
collection.stream()
.filter(Objects::nonNull)
.map(RecordsToAlwaysIncludeSql::toSqlAndParams)
.collect(ImmutableSet.toImmutableSet()))
.map(RecordsToAlwaysIncludeSql::new)
.orElse(null);
}
}
public SqlAndParams toSqlAndParams()
{
return sqlAndParams;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\sql\FilterSql.java
| 1
|
请完成以下Java代码
|
public static Builder builder(ProcessDefinition processDefinition) {
return new Builder(processDefinition);
}
public static class Builder {
private final ProcessDefinition processDefinition;
private String businessKey;
private String processInstanceName;
private Map<String, Object> variables;
private Map<String, Object> transientVariables;
private String linkedProcessInstanceId;
private String linkedProcessInstanceType;
private Builder(ProcessDefinition processDefinition) {
this.processDefinition = processDefinition;
}
public Builder businessKey(String businessKey) {
this.businessKey = businessKey;
return this;
}
public Builder processInstanceName(String processInstanceName) {
this.processInstanceName = processInstanceName;
return this;
}
public Builder variables(Map<String, Object> variables) {
this.variables = variables;
return this;
}
public Builder transientVariables(Map<String, Object> transientVariables) {
this.transientVariables = transientVariables;
return this;
}
|
public Builder linkedProcessInstanceId(String linkedProcessInstanceId) {
this.linkedProcessInstanceId = linkedProcessInstanceId;
return this;
}
public Builder linkedProcessInstanceType(String linkedProcessInstanceType) {
this.linkedProcessInstanceType = linkedProcessInstanceType;
return this;
}
public ProcessInstanceCreationOptions build() {
return new ProcessInstanceCreationOptions(this);
}
}
public ProcessDefinition getProcessDefinition() { return processDefinition; }
public String getBusinessKey() { return businessKey; }
public String getProcessInstanceName() { return processInstanceName; }
public Map<String, Object> getVariables() { return variables; }
public Map<String, Object> getTransientVariables() { return transientVariables; }
public String getLinkedProcessInstanceId() { return linkedProcessInstanceId; }
public String getLinkedProcessInstanceType() { return linkedProcessInstanceType; }
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\ProcessInstanceCreationOptions.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected Job getJobById(String jobId) {
Job job = managementService.createJobQuery().jobId(jobId).singleResult();
validateJob(job, jobId);
return job;
}
protected Job getTimerJobById(String jobId) {
Job job = managementService.createTimerJobQuery().jobId(jobId).singleResult();
validateJob(job, jobId);
return job;
}
protected Job getSuspendedJobById(String jobId) {
Job job = managementService.createSuspendedJobQuery().jobId(jobId).singleResult();
validateJob(job, jobId);
return job;
}
protected Job getDeadLetterJobById(String jobId) {
Job job = managementService.createDeadLetterJobQuery().jobId(jobId).singleResult();
validateJob(job, jobId);
return job;
}
protected HistoryJob getHistoryJobById(String jobId) {
HistoryJob job = managementService.createHistoryJobQuery().jobId(jobId).singleResult();
validateHistoryJob(job, jobId);
return job;
}
protected void validateJob(Job job, String jobId) {
if (job == null) {
|
throw new FlowableObjectNotFoundException("Could not find a job with id '" + jobId + "'.", Job.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessJobInfoById(job);
}
}
protected void validateHistoryJob(HistoryJob job, String jobId) {
if (job == null) {
throw new FlowableObjectNotFoundException("Could not find a history job with id '" + jobId + "'.", HistoryJob.class);
}
if (restApiInterceptor != null) {
restApiInterceptor.accessHistoryJobInfoById(job);
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\management\JobBaseResource.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class M_InventoryLine
{
@Init
public void registerCallout()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_M_InventoryLine.COLUMNNAME_InventoryType)
@CalloutMethod(columnNames = I_M_InventoryLine.COLUMNNAME_InventoryType)
public void onChargeAccountChangeForInternalInventory(final I_M_InventoryLine inventoryLine)
{
final IInventoryBL inventoryBL = Services.get(IInventoryBL.class);
final String inventoryType = inventoryLine.getInventoryType();
if (!X_M_InventoryLine.INVENTORYTYPE_ChargeAccount.equals(inventoryType))
{
// nothing to do
return;
}
if (!inventoryBL.isInternalUseInventory(inventoryLine))
{
// nothing to do, this is covered by the
return;
}
if (inventoryLine.getC_Charge_ID() > 0)
|
{
// nothing to do, it's already set
return;
}
inventoryBL.setDefaultInternalChargeId(inventoryLine);
}
// moved here from org.compiere.model.MInventoryLine.beforeSave
@ModelChange(
timings = { ModelValidator.TYPE_BEFORE_NEW, ModelValidator.TYPE_BEFORE_CHANGE },
ifColumnsChanged = { I_M_InventoryLine.COLUMNNAME_QtyCount, I_M_InventoryLine.COLUMNNAME_QtyBook })
public void enforceQtyCountNotNegative(@NonNull final I_M_InventoryLine inventoryLineRecord)
{
// Tolerate negative qtyCount if qtyCount=QtyBooked. We sometimes have this in the area of costing adjustments.
if (inventoryLineRecord.getQtyCount().compareTo(inventoryLineRecord.getQtyBook()) == 0)
{
return;
}
// Enforce QtyCount >= 0 - teo_sarca BF [ 1722982 ]
if (inventoryLineRecord.getQtyCount().signum() < 0)
{
throw new AdempiereException("@Warning@ @" + I_M_InventoryLine.COLUMNNAME_QtyCount + "@ < 0");
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\interceptor\M_InventoryLine.java
| 2
|
请完成以下Java代码
|
public boolean isNotifyUserInCharge()
{
return notificationTypes.contains(NotificationType.NotifyUserInCharge);
}
public boolean isNotifyByEMail()
{
return notificationTypes.contains(NotificationType.EMail);
}
public boolean isNotifyByInternalMessage()
{
return notificationTypes.contains(NotificationType.Notice);
}
public boolean hasAnyNotificationTypesExceptUserInCharge()
{
return hasAnyNotificationTypesExcept(NotificationType.NotifyUserInCharge);
}
|
public boolean hasAnyNotificationTypesExcept(final NotificationType typeToExclude)
{
final int notificationTypesCount = notificationTypes.size();
if (notificationTypesCount <= 0)
{
return false;
}
else if (notificationTypesCount == 1)
{
return !notificationTypes.contains(typeToExclude);
}
else // notificationTypesCount > 1
{
return true;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\UserNotificationsGroup.java
| 1
|
请完成以下Java代码
|
private static void addDescriptionToEntry(SyndEntry entry) {
SyndContent description = new SyndContentImpl();
description.setType("text/html");
description.setValue("First entry");
entry.setDescription(description);
}
private static void addCategoryToEntry(SyndEntry entry) {
List<SyndCategory> categories = new ArrayList<>();
SyndCategory category = new SyndCategoryImpl();
category.setName("Sophisticated category");
categories.add(category);
entry.setCategories(categories);
|
}
private static void publishFeed(SyndFeed feed) throws IOException, FeedException {
Writer writer = new FileWriter("xyz.txt");
SyndFeedOutput syndFeedOutput = new SyndFeedOutput();
syndFeedOutput.output(feed, writer);
writer.close();
}
private static SyndFeed readFeed() throws IOException, FeedException, URISyntaxException {
URL feedSource = new URI("http://rssblog.whatisrss.com/feed/").toURL();
SyndFeedInput input = new SyndFeedInput();
return input.build(new XmlReader(feedSource));
}
}
|
repos\tutorials-master\web-modules\rome\src\main\java\com\baeldung\rome\RSSRomeExample.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void deleteStudent(@PathVariable long id) {
studentRepository.deleteById(id);
}
@PostMapping
public ResponseEntity<Object> createStudent(@RequestBody Student student) {
Student savedStudent = studentRepository.save(student);
URI location = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}")
.buildAndExpand(savedStudent.getId())
.toUri();
return ResponseEntity.created(location).build();
}
@PutMapping(ID)
|
public ResponseEntity<Object> updateStudent(@RequestBody Student student,
@PathVariable long id) {
Optional<Student> studentOptional = studentRepository.findById(id);
if (studentOptional.isEmpty())
return ResponseEntity.notFound().build();
student.setId(id);
studentRepository.save(student);
return ResponseEntity.noContent().build();
}
}
|
repos\spring-boot-examples-master\spring-boot-2-rest-service-content-negotiation\src\main\java\com\in28minutes\springboot\rest\example\student\StudentResource.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Long timeStamp) {
this.timeStamp = timeStamp;
}
public String getEvent() {
return event;
}
|
public void setEvent(String event) {
this.event = event;
}
public Long getParentId() {
return parentId;
}
public void setParentId(Long parentId) {
this.parentId = parentId;
}
public String getChecksum() {
return checksum;
}
public void setChecksum(String checksum) {
this.checksum = checksum;
}
}
|
repos\spring-examples-java-17\spring-bank\bank-server\src\main\java\itx\examples\springbank\server\repository\model\LedgerEntity.java
| 2
|
请完成以下Java代码
|
public String toString()
{
return "TableCacheConfig [tableName=" + tableName
+ ", enabled=" + enabled
+ ", trxLevel=" + trxLevel
+ ", cacheMapType=" + cacheMapType
+ ", initialCapacity=" + initialCapacity
+ ", maxCapacity=" + maxCapacity
+ ", expireMinutes=" + expireMinutes
+ "]";
}
@Override
public String getTableName()
{
return tableName;
}
@Override
public final boolean isEnabled()
{
return enabled;
}
@Override
public void setEnabled(final boolean enabled)
{
this.enabled = enabled;
}
@Override
public TrxLevel getTrxLevel()
{
return this.trxLevel;
}
@Override
public void setTrxLevel(final TrxLevel trxLevel)
{
Check.assumeNotNull(trxLevel, "trxLevel not null");
this.trxLevel = trxLevel;
}
@Override
public CacheMapType getCacheMapType()
{
return cacheMapType;
}
@Override
public void setCacheMapType(CacheMapType cacheMapType)
{
Check.assumeNotNull(cacheMapType, "cacheMapType not null");
this.cacheMapType = cacheMapType;
}
@Override
public int getInitialCapacity()
{
return initialCapacity;
}
@Override
|
public void setInitialCapacity(int initalCapacity)
{
Check.assume(initalCapacity > 0, "initialCapacity > 0");
this.initialCapacity = initalCapacity;
}
@Override
public int getMaxCapacity()
{
return maxCapacity;
}
@Override
public void setMaxCapacity(int maxCapacity)
{
this.maxCapacity = maxCapacity;
}
@Override
public int getExpireMinutes()
{
return expireMinutes;
}
@Override
public void setExpireMinutes(int expireMinutes)
{
this.expireMinutes = expireMinutes > 0 ? expireMinutes : EXPIREMINUTES_Never;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\model\impl\MutableTableCacheConfig.java
| 1
|
请完成以下Java代码
|
public InSubQueryFilter<T> build()
{
return new InSubQueryFilter<>(this);
}
public Builder<T> tableName(final String tableName)
{
this.tableName = tableName;
return this;
}
public Builder<T> subQuery(final IQuery<?> subQuery)
{
this.subQuery = subQuery;
return this;
}
|
public Builder<T> matchingColumnNames(final String columnName, final String subQueryColumnName, final IQueryFilterModifier modifier)
{
matchers.add(ColumnNamePair.builder()
.columnName(columnName)
.subQueryColumnName(subQueryColumnName)
.modifier(modifier)
.build());
return this;
}
public Builder<T> matchingColumnNames(final String columnName, final String subQueryColumnName)
{
return matchingColumnNames(columnName, subQueryColumnName, NullQueryFilterModifier.instance);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\InSubQueryFilter.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setParamValue (final java.lang.String ParamValue)
{
set_Value (COLUMNNAME_ParamValue, ParamValue);
}
@Override
public java.lang.String getParamValue()
{
return get_ValueAsString(COLUMNNAME_ParamValue);
}
@Override
public org.compiere.model.I_PP_ComponentGenerator getPP_ComponentGenerator()
{
return get_ValueAsPO(COLUMNNAME_PP_ComponentGenerator_ID, org.compiere.model.I_PP_ComponentGenerator.class);
}
@Override
public void setPP_ComponentGenerator(final org.compiere.model.I_PP_ComponentGenerator PP_ComponentGenerator)
{
set_ValueFromPO(COLUMNNAME_PP_ComponentGenerator_ID, org.compiere.model.I_PP_ComponentGenerator.class, PP_ComponentGenerator);
}
@Override
public void setPP_ComponentGenerator_ID (final int PP_ComponentGenerator_ID)
{
if (PP_ComponentGenerator_ID < 1)
set_Value (COLUMNNAME_PP_ComponentGenerator_ID, null);
|
else
set_Value (COLUMNNAME_PP_ComponentGenerator_ID, PP_ComponentGenerator_ID);
}
@Override
public int getPP_ComponentGenerator_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_ID);
}
@Override
public void setPP_ComponentGenerator_Param_ID (final int PP_ComponentGenerator_Param_ID)
{
if (PP_ComponentGenerator_Param_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_Param_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_ComponentGenerator_Param_ID, PP_ComponentGenerator_Param_ID);
}
@Override
public int getPP_ComponentGenerator_Param_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_ComponentGenerator_Param_ID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PP_ComponentGenerator_Param.java
| 1
|
请完成以下Java代码
|
public void addAuthorizationsForNewProcessDefinition(Process process, ProcessDefinitionEntity processDefinition) {
CommandContext commandContext = Context.getCommandContext();
if (process != null) {
addAuthorizationsFromIterator(
commandContext,
process.getCandidateStarterUsers(),
processDefinition,
ExpressionType.USER
);
addAuthorizationsFromIterator(
commandContext,
process.getCandidateStarterGroups(),
processDefinition,
ExpressionType.GROUP
);
}
}
protected void addAuthorizationsFromIterator(
CommandContext commandContext,
List<String> expressions,
ProcessDefinitionEntity processDefinition,
ExpressionType expressionType
) {
if (expressions != null) {
Iterator<String> iterator = expressions.iterator();
while (iterator.hasNext()) {
@SuppressWarnings("cast")
String expression = iterator.next();
IdentityLinkEntity identityLink = commandContext.getIdentityLinkEntityManager().create();
|
identityLink.setProcessDef(processDefinition);
if (expressionType.equals(ExpressionType.USER)) {
identityLink.setUserId(expression);
} else if (expressionType.equals(ExpressionType.GROUP)) {
identityLink.setGroupId(expression);
}
identityLink.setType(IdentityLinkType.CANDIDATE);
commandContext.getIdentityLinkEntityManager().insert(identityLink);
}
}
}
public TimerManager getTimerManager() {
return timerManager;
}
public void setTimerManager(TimerManager timerManager) {
this.timerManager = timerManager;
}
public EventSubscriptionManager getEventSubscriptionManager() {
return eventSubscriptionManager;
}
public void setEventSubscriptionManager(EventSubscriptionManager eventSubscriptionManager) {
this.eventSubscriptionManager = eventSubscriptionManager;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\deployer\BpmnDeploymentHelper.java
| 1
|
请完成以下Java代码
|
public class AD_JavaClass_Type
{
/**
* Loads the given {@code type}'s {@link I_AD_JavaClass} records and attempts to initialize them. This method only needs to be called on java class type changes (because new types don't have
* classes). It needs to be called <b>after</b> the change, because the classes are loaded from DB and the in turn load the type from DB (so it's mandatory that the type has already been stored
* within the current transaction).
*
* @param type
*/
@ModelChange(
timings = { ModelValidator.TYPE_AFTER_CHANGE },
ifColumnsChanged = { I_AD_JavaClass_Type.COLUMNNAME_Classname })
public void onChangeClassname(final I_AD_JavaClass_Type type)
{
final IJavaClassDAO javaClassDAO = Services.get(IJavaClassDAO.class);
final List<I_AD_JavaClass> classes = javaClassDAO.retrieveAllJavaClasses(type);
for (final I_AD_JavaClass clazz : classes)
{
if(!clazz.isActive())
{
continue;
}
if(clazz.isInterface())
{
continue;
}
Services.get(IJavaClassBL.class).newInstance(clazz);
}
}
@ModelChange(
timings = { ModelValidator.TYPE_BEFORE_CHANGE, ModelValidator.TYPE_BEFORE_NEW },
ifColumnsChanged = { I_AD_JavaClass_Type.COLUMNNAME_Classname })
public void checkClassAndUpdateInternalName(final I_AD_JavaClass_Type javaClassType)
|
{
final boolean throwEx = true; // we don't want an exception.
checkClassAndUpdateInternalName(javaClassType, throwEx);
}
@CalloutMethod(columnNames = I_AD_JavaClass_Type.COLUMNNAME_Classname)
public void checkClassAndUpdateInternalName(I_AD_JavaClass_Type javaClassType, ICalloutField field)
{
final boolean throwEx = false; // we don't want an exception.
checkClassAndUpdateInternalName(javaClassType, throwEx);
}
private void checkClassAndUpdateInternalName(I_AD_JavaClass_Type javaClassType, final boolean throwEx)
{
final IJavaClassTypeBL javaClassTypeBL = Services.get(IJavaClassTypeBL.class);
final Class<?> classNameClass = javaClassTypeBL.checkClassName(javaClassType, throwEx);
if (classNameClass == null)
{
javaClassType.setInternalName(null);
return;
}
javaClassType.setInternalName(classNameClass.getName());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\javaclasses\model\interceptor\AD_JavaClass_Type.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void beforeApplicationStart(final CamelContext camelContext)
{
camelContext.setAutoStartup(false);
final Environment env = context.getEnvironment();
logger.log(Level.INFO, "Configured RabbitMQ hostname:port is {}:{}", env.getProperty("camel.component.rabbitmq.hostname"), env.getProperty("camel.component.rabbitmq.port-number"));
final String metasfreshAPIBaseURL = context.getEnvironment().getProperty(ExternalSystemCamelConstants.MF_API_BASE_URL_PROPERTY);
if (Check.isBlank(metasfreshAPIBaseURL))
{
throw new RuntimeException("Missing mandatory property! property = " + ExternalSystemCamelConstants.MF_API_BASE_URL_PROPERTY);
}
camelContext.getManagementStrategy()
.addEventNotifier(new MetasfreshAuthorizationTokenNotifier(metasfreshAuthProvider, metasfreshAPIBaseURL, customRouteController, producerTemplate));
|
camelContext.getManagementStrategy()
.addEventNotifier(new AuditEventNotifier(producerTemplate));
}
@Override
public void afterApplicationStart(final CamelContext camelContext)
{
customRouteController().startAlwaysRunningRoutes();
producerTemplate
.sendBody("direct:" + CUSTOM_TO_MF_ROUTE_ID, "Trigger external system authentication!");
}
};
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\AppConfiguration.java
| 2
|
请完成以下Java代码
|
public class ProgrammerNotAnnotated {
private String name;
private String favouriteLanguage;
private Keyboard keyboard;
public ProgrammerNotAnnotated(String name, String favouriteLanguage, Keyboard keyboard) {
this.name = name;
this.favouriteLanguage = favouriteLanguage;
this.keyboard = keyboard;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
|
public String getFavouriteLanguage() {
return favouriteLanguage;
}
public void setFavouriteLanguage(String favouriteLanguage) {
this.favouriteLanguage = favouriteLanguage;
}
public Keyboard getKeyboard() {
return keyboard;
}
public void setKeyboard(Keyboard keyboard) {
this.keyboard = keyboard;
}
@Override
public String toString() {
return "Programmer{" + "name='" + name + '\'' + ", favouriteLanguage='" + favouriteLanguage + '\'' + ", keyboard=" + keyboard + '}';
}
}
|
repos\tutorials-master\jackson-modules\jackson-annotations\src\main\java\com\baeldung\jackson\jsonmerge\ProgrammerNotAnnotated.java
| 1
|
请完成以下Java代码
|
public int length()
{
return getValue().length();
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append('[');
int i = 1;
for (Word word : innerList)
{
sb.append(word.getValue());
String label = word.getLabel();
if (label != null)
{
sb.append('/').append(label);
}
if (i != innerList.size())
{
sb.append(' ');
}
++i;
}
sb.append("]/");
sb.append(label);
return sb.toString();
}
/**
* 转换为一个简单词
* @return
*/
public Word toWord()
{
return new Word(getValue(), getLabel());
}
|
public CompoundWord(List<Word> innerList, String label)
{
this.innerList = innerList;
this.label = label;
}
public static CompoundWord create(String param)
{
if (param == null) return null;
int cutIndex = param.lastIndexOf(']');
if (cutIndex <= 2 || cutIndex == param.length() - 1) return null;
String wordParam = param.substring(1, cutIndex);
List<Word> wordList = new LinkedList<Word>();
for (String single : wordParam.split("\\s+"))
{
if (single.length() == 0) continue;
Word word = Word.create(single);
if (word == null)
{
Predefine.logger.warning("使用参数" + single + "构造单词时发生错误");
return null;
}
wordList.add(word);
}
String labelParam = param.substring(cutIndex + 1);
if (labelParam.startsWith("/"))
{
labelParam = labelParam.substring(1);
}
return new CompoundWord(wordList, labelParam);
}
@Override
public Iterator<Word> iterator()
{
return innerList.iterator();
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\sentence\word\CompoundWord.java
| 1
|
请完成以下Java代码
|
public void setHelp (final @Nullable java.lang.String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
@Override
public java.lang.String getHelp()
{
return get_ValueAsString(COLUMNNAME_Help);
}
@Override
public void setIsMandatory (final boolean IsMandatory)
{
set_Value (COLUMNNAME_IsMandatory, IsMandatory);
}
@Override
public boolean isMandatory()
{
return get_ValueAsBoolean(COLUMNNAME_IsMandatory);
}
@Override
public void setIsPartUniqueIndex (final boolean IsPartUniqueIndex)
{
set_Value (COLUMNNAME_IsPartUniqueIndex, IsPartUniqueIndex);
}
@Override
public boolean isPartUniqueIndex()
{
return get_ValueAsBoolean(COLUMNNAME_IsPartUniqueIndex);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPosition (final int Position)
{
set_Value (COLUMNNAME_Position, Position);
}
@Override
|
public int getPosition()
{
return get_ValueAsInt(COLUMNNAME_Position);
}
/**
* Type AD_Reference_ID=53241
* Reference name: EXP_Line_Type
*/
public static final int TYPE_AD_Reference_ID=53241;
/** XML Element = E */
public static final String TYPE_XMLElement = "E";
/** XML Attribute = A */
public static final String TYPE_XMLAttribute = "A";
/** Embedded EXP Format = M */
public static final String TYPE_EmbeddedEXPFormat = "M";
/** Referenced EXP Format = R */
public static final String TYPE_ReferencedEXPFormat = "R";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@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);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_EXP_FormatLine.java
| 1
|
请完成以下Java代码
|
public Integer convertBinaryToDecimal(Integer binaryNumber) {
Integer decimalNumber = 0;
Integer base = 1;
while (binaryNumber > 0) {
int lastDigit = binaryNumber % 10;
binaryNumber = binaryNumber / 10;
decimalNumber += lastDigit * base;
base = base * 2;
}
return decimalNumber;
}
/**
* This method accepts two binary numbers and returns sum of input numbers.
* Example:- firstNum: 101, secondNum: 100, output: 1001
*
* @param firstNum
* @param secondNum
* @return addition of input numbers
*/
public Integer addBinaryNumber(Integer firstNum, Integer secondNum) {
StringBuilder output = new StringBuilder();
int carry = 0;
int temp;
while (firstNum != 0 || secondNum != 0) {
temp = (firstNum % 10 + secondNum % 10 + carry) % 2;
output.append(temp);
carry = (firstNum % 10 + secondNum % 10 + carry) / 2;
firstNum = firstNum / 10;
secondNum = secondNum / 10;
}
if (carry != 0) {
output.append(carry);
}
return Integer.valueOf(output.reverse()
.toString());
}
/**
* This method takes two binary number as input and subtract second number from the first number.
|
* example:- firstNum: 1000, secondNum: 11, output: 101
* @param firstNum
* @param secondNum
* @return Result of subtraction of secondNum from first
*/
public Integer substractBinaryNumber(Integer firstNum, Integer secondNum) {
int onesComplement = Integer.valueOf(getOnesComplement(secondNum));
StringBuilder output = new StringBuilder();
int carry = 0;
int temp;
while (firstNum != 0 || onesComplement != 0) {
temp = (firstNum % 10 + onesComplement % 10 + carry) % 2;
output.append(temp);
carry = (firstNum % 10 + onesComplement % 10 + carry) / 2;
firstNum = firstNum / 10;
onesComplement = onesComplement / 10;
}
String additionOfFirstNumAndOnesComplement = output.reverse()
.toString();
if (carry == 1) {
return addBinaryNumber(Integer.valueOf(additionOfFirstNumAndOnesComplement), carry);
} else {
return getOnesComplement(Integer.valueOf(additionOfFirstNumAndOnesComplement));
}
}
public Integer getOnesComplement(Integer num) {
StringBuilder onesComplement = new StringBuilder();
while (num > 0) {
int lastDigit = num % 10;
if (lastDigit == 0) {
onesComplement.append(1);
} else {
onesComplement.append(0);
}
num = num / 10;
}
return Integer.valueOf(onesComplement.reverse()
.toString());
}
}
|
repos\tutorials-master\core-java-modules\core-java-numbers-2\src\main\java\com\baeldung\binarynumbers\BinaryNumbers.java
| 1
|
请完成以下Java代码
|
private boolean isRefreshViewOnChangeEvents()
{
return _refreshViewOnChangeEvents;
}
public Builder setPrintProcessId(final AdProcessId printProcessId)
{
_printProcessId = printProcessId;
return this;
}
private AdProcessId getPrintProcessId()
{
return _printProcessId;
}
private boolean isCloneEnabled()
{
return isCloneEnabled(_tableName);
}
private static boolean isCloneEnabled(@Nullable final Optional<String> tableName)
{
if (tableName == null || !tableName.isPresent())
{
return false;
}
|
return CopyRecordFactory.isEnabledForTableName(tableName.get());
}
public DocumentQueryOrderByList getDefaultOrderBys()
{
return getFieldBuilders()
.stream()
.filter(DocumentFieldDescriptor.Builder::isDefaultOrderBy)
.sorted(Ordering.natural().onResultOf(DocumentFieldDescriptor.Builder::getDefaultOrderByPriority))
.map(field -> DocumentQueryOrderBy.byFieldName(field.getFieldName(), field.isDefaultOrderByAscending()))
.collect(DocumentQueryOrderByList.toDocumentQueryOrderByList());
}
public Builder queryIfNoFilters(final boolean queryIfNoFilters)
{
this.queryIfNoFilters = queryIfNoFilters;
return this;
}
public Builder notFoundMessages(@Nullable final NotFoundMessages notFoundMessages)
{
this.notFoundMessages = notFoundMessages;
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentEntityDescriptor.java
| 1
|
请完成以下Java代码
|
public ActivityImpl getConditionalActivity() {
return conditionalActivity;
}
public void setConditionalActivity(ActivityImpl conditionalActivity) {
this.conditionalActivity = conditionalActivity;
}
public boolean isInterrupting() {
return interrupting;
}
public void setInterrupting(boolean interrupting) {
this.interrupting = interrupting;
}
public String getVariableName() {
return variableName;
}
public void setVariableName(String variableName) {
this.variableName = variableName;
}
public Set<String> getVariableEvents() {
return variableEvents;
}
public void setVariableEvents(Set<String> variableEvents) {
this.variableEvents = variableEvents;
}
public String getConditionAsString() {
return conditionAsString;
}
public void setConditionAsString(String conditionAsString) {
this.conditionAsString = conditionAsString;
}
public boolean shouldEvaluateForVariableEvent(VariableEvent event) {
return
((variableName == null || event.getVariableInstance().getName().equals(variableName))
&&
((variableEvents == null || variableEvents.isEmpty()) || variableEvents.contains(event.getEventName())));
|
}
public boolean evaluate(DelegateExecution execution) {
if (condition != null) {
return condition.evaluate(execution, execution);
}
throw new IllegalStateException("Conditional event must have a condition!");
}
public boolean tryEvaluate(DelegateExecution execution) {
if (condition != null) {
return condition.tryEvaluate(execution, execution);
}
throw new IllegalStateException("Conditional event must have a condition!");
}
public boolean tryEvaluate(VariableEvent variableEvent, DelegateExecution execution) {
return (variableEvent == null || shouldEvaluateForVariableEvent(variableEvent)) && tryEvaluate(execution);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\ConditionalEventDefinition.java
| 1
|
请完成以下Java代码
|
public void run() {
FlowElement currentFlowElement = getCurrentFlowElement(execution);
if (currentFlowElement instanceof FlowNode) {
ActivityBehavior activityBehavior = (ActivityBehavior) ((FlowNode) currentFlowElement).getBehavior();
if (activityBehavior instanceof TriggerableActivityBehavior) {
if (!triggerAsync) {
((TriggerableActivityBehavior) activityBehavior).trigger(execution, null, null);
} else {
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
JobService jobService = processEngineConfiguration.getJobServiceConfiguration().getJobService();
JobEntity job = JobUtil.createJob(execution, currentFlowElement, AsyncTriggerJobHandler.TYPE, processEngineConfiguration);
jobService.createAsyncJob(job, true);
jobService.scheduleAsyncJob(job);
}
} else {
|
throw new FlowableException("Cannot trigger " + execution
+ " : the activityBehavior " + activityBehavior.getClass() + " does not implement the "
+ TriggerableActivityBehavior.class.getName() + " interface");
}
} else if (currentFlowElement == null) {
throw new FlowableException("Cannot trigger " + execution
+ " : no current flow element found. Check the execution id that is being passed "
+ "(it should not be a process instance execution, but a child execution currently referencing a flow element).");
} else {
throw new FlowableException("Programmatic error: cannot trigger " + execution + ", invalid flow element type found: "
+ currentFlowElement.getClass().getName() + ".");
}
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\agenda\TriggerExecutionOperation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public PageResult<DictDetailDto> queryAll(DictDetailQueryCriteria criteria, Pageable pageable) {
Page<DictDetail> page = dictDetailRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
return PageUtil.toPage(page.map(dictDetailMapper::toDto));
}
@Override
@Transactional(rollbackFor = Exception.class)
public void create(DictDetail resources) {
dictDetailRepository.save(resources);
// 清理缓存
delCaches(resources);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void update(DictDetail resources) {
DictDetail dictDetail = dictDetailRepository.findById(resources.getId()).orElseGet(DictDetail::new);
ValidationUtil.isNull( dictDetail.getId(),"DictDetail","id",resources.getId());
resources.setId(dictDetail.getId());
dictDetailRepository.save(resources);
// 清理缓存
delCaches(resources);
}
@Override
public List<DictDetailDto> getDictByName(String name) {
String key = CacheKey.DICT_NAME + name;
List<DictDetail> dictDetails = redisUtils.getList(key, DictDetail.class);
if(CollUtil.isEmpty(dictDetails)){
dictDetails = dictDetailRepository.findByDictName(name);
|
redisUtils.set(key, dictDetails, 1 , TimeUnit.DAYS);
}
return dictDetailMapper.toDto(dictDetails);
}
@Override
@Transactional(rollbackFor = Exception.class)
public void delete(Long id) {
DictDetail dictDetail = dictDetailRepository.findById(id).orElseGet(DictDetail::new);
// 清理缓存
delCaches(dictDetail);
dictDetailRepository.deleteById(id);
}
public void delCaches(DictDetail dictDetail){
Dict dict = dictRepository.findById(dictDetail.getDict().getId()).orElseGet(Dict::new);
redisUtils.del(CacheKey.DICT_NAME + dict.getName());
}
}
|
repos\eladmin-master\eladmin-system\src\main\java\me\zhengjie\modules\system\service\impl\DictDetailServiceImpl.java
| 2
|
请完成以下Java代码
|
private static IDevice newDeviceInstance(final DeviceConfig deviceConfig)
{
final String deviceClassname = deviceConfig.getDeviceClassname();
try
{
return Util.getInstance(IDevice.class, deviceClassname);
}
catch (final Exception e)
{
throw DeviceConfigException.permanentFailure("Failed loading deviceClass: " + deviceClassname, e);
}
}
/**
* Returns all requests that the given device configuration and given <code>attributeCode</code>.
*
* @param deviceConfig device configuration
* @param attributeCode attribute code
* @param responseClazz optional, maybe be <code>null</code>. If set, then the result is filtered and only those requests are returned whose response is assignable from this parameter.
*/
public static <T extends IDeviceResponse> List<IDeviceRequest<T>> getAllRequestsFor(
final DeviceConfig deviceConfig,
final AttributeCode attributeCode,
final Class<T> responseClazz)
{
final Collection<String> requestClassnames = deviceConfig.getRequestClassnames(attributeCode);
if (requestClassnames.isEmpty())
{
logger.warn("Possible configuration issue on {} for attribute '{}': no request classnames found", deviceConfig, attributeCode);
return ImmutableList.of();
}
|
final List<IDeviceRequest<T>> result = new ArrayList<>();
for (final String currentRequestClassName : requestClassnames)
{
@SuppressWarnings("rawtypes") final IDeviceRequest request = Util.getInstance(IDeviceRequest.class, currentRequestClassName);
if (responseClazz == null || responseClazz.isAssignableFrom(request.getResponseClass()))
{
//noinspection unchecked
result.add(request);
}
}
return result;
}
@NonNull
public static ImmutableList<BeforeAcquireValueHook> instantiateHooks(@NonNull final DeviceConfig deviceConfig)
{
return deviceConfig.getBeforeHooksClassname()
.stream()
.map(classname -> {
try
{
return Util.getInstance(BeforeAcquireValueHook.class, classname);
}
catch (final Exception e)
{
throw DeviceConfigException.permanentFailure("Failed instantiating BeforeAcquireValueHook: " + classname, e);
}
})
.collect(ImmutableList.toImmutableList());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.device.adempiere\src\main\java\de\metas\device\accessor\DeviceInstanceUtils.java
| 1
|
请完成以下Java代码
|
public class CatSpan implements Span {
private Transaction transaction;
public CatSpan(Transaction transaction) {
this.transaction = transaction;
}
@Override
public SpanContext context() {
return null;
}
@Override
public Span setTag(String key, String value) {
return null;
}
@Override
public Span setTag(String key, boolean value) {
return null;
}
@Override
public Span setTag(String key, Number value) {
return null;
}
@Override
public <T> Span setTag(Tag<T> tag, T value) {
return null;
}
@Override
public Span log(Map<String, ?> fields) {
return null;
}
@Override
public Span log(long timestampMicroseconds, Map<String, ?> fields) {
return null;
}
@Override
|
public Span log(String event) {
return null;
}
@Override
public Span log(long timestampMicroseconds, String event) {
return null;
}
@Override
public Span setBaggageItem(String key, String value) {
return null;
}
@Override
public String getBaggageItem(String key) {
return null;
}
@Override
public Span setOperationName(String operationName) {
return null;
}
@Override
public void finish() {
transaction.setStatus(Transaction.SUCCESS);
transaction.complete();
}
@Override
public void finish(long finishMicros) {
}
}
|
repos\SpringBoot-Labs-master\lab-61\lab-61-cat-opentracing\src\main\java\cn\iocoder\springboot\lab61\cat\opentracing\CatSpan.java
| 1
|
请完成以下Java代码
|
public class City implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private String state;
private String country;
public Long getId() {
return this.id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
|
public String getCountry() {
return this.country;
}
public void setCountry(String country) {
this.country = country;
}
@Override
public String toString() {
return getId() + "," + getName() + "," + getState() + "," + getCountry();
}
}
|
repos\pagehelper-spring-boot-master\pagehelper-spring-boot-samples\pagehelper-spring-boot-sample-xml\src\main\java\tk\mybatis\pagehelper\domain\City.java
| 1
|
请完成以下Java代码
|
public boolean isEmpty() {
return operations.isEmpty() && futureOperations.isEmpty();
}
@Override
public Runnable getNextOperation() {
assertOperationsNotEmpty();
if (!operations.isEmpty()) {
return operations.poll();
} else {
// If there are no more operations then we need to wait until any of the schedule future operations are done
List<ExecuteFutureActionOperation<?>> copyOperations = new ArrayList<>(futureOperations);
futureOperations.clear();
Duration maxWaitTimeout = getFutureMaxWaitTimeout();
return new WaitForAnyFutureToFinishOperation(this, copyOperations, maxWaitTimeout);
}
}
protected void assertOperationsNotEmpty() {
if (operations.isEmpty() && futureOperations.isEmpty()) {
throw new FlowableException("Unable to peek empty agenda.");
}
}
/**
* Generic method to plan a {@link Runnable}.
*/
@Override
public void planOperation(Runnable operation) {
operations.add(operation);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Operation {} added to agenda", operation.getClass());
}
}
@Override
public <V> void planFutureOperation(CompletableFuture<V> future, BiConsumer<V, Throwable> completeAction) {
ExecuteFutureActionOperation<V> operation = new ExecuteFutureActionOperation<>(future, completeAction);
if (future.isDone()) {
// If the future is done, then plan the operation first (this makes sure that the complete action is invoked before any other operation is run)
operations.addFirst(operation);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Operation {} added to agenda", operation.getClass());
}
} else {
futureOperations.add(operation);
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Future {} with action {} added to agenda", future, completeAction.getClass());
}
}
}
protected Duration getFutureMaxWaitTimeout() {
|
AgendaFutureMaxWaitTimeoutProvider futureOperationTimeoutProvider = getAgendaFutureMaxWaitTimeoutProvider();
return futureOperationTimeoutProvider != null ? futureOperationTimeoutProvider.getMaxWaitTimeout(commandContext) : null;
}
public LinkedList<Runnable> getOperations() {
return operations;
}
public CommandContext getCommandContext() {
return commandContext;
}
public void setCommandContext(CommandContext commandContext) {
this.commandContext = commandContext;
}
protected abstract AgendaFutureMaxWaitTimeoutProvider getAgendaFutureMaxWaitTimeoutProvider();
@Override
public void flush() {
}
@Override
public void close() {
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\agenda\AbstractAgenda.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class BadRequestAlertException extends ErrorResponseException {
private static final long serialVersionUID = 1L;
private final String entityName;
private final String errorKey;
public BadRequestAlertException(String defaultMessage, String entityName, String errorKey) {
this(ErrorConstants.DEFAULT_TYPE, defaultMessage, entityName, errorKey);
}
public BadRequestAlertException(URI type, String defaultMessage, String entityName, String errorKey) {
super(
HttpStatus.BAD_REQUEST,
ProblemDetailWithCauseBuilder.instance()
.withStatus(HttpStatus.BAD_REQUEST.value())
.withType(type)
.withTitle(defaultMessage)
.withProperty("message", "error." + errorKey)
.withProperty("params", entityName)
.build(),
null
|
);
this.entityName = entityName;
this.errorKey = errorKey;
}
public String getEntityName() {
return entityName;
}
public String getErrorKey() {
return errorKey;
}
public ProblemDetailWithCause getProblemDetailWithCause() {
return (ProblemDetailWithCause) this.getBody();
}
}
|
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\car-app\src\main\java\com\cars\app\web\rest\errors\BadRequestAlertException.java
| 2
|
请完成以下Java代码
|
public void setSerNo (String SerNo)
{
set_Value (COLUMNNAME_SerNo, SerNo);
}
/** Get Serial No.
@return Product Serial Number
*/
public String getSerNo ()
{
return (String)get_Value(COLUMNNAME_SerNo);
}
/** Set Usable Life - Months.
@param UseLifeMonths
Months of the usable life of the asset
*/
public void setUseLifeMonths (int UseLifeMonths)
{
set_Value (COLUMNNAME_UseLifeMonths, Integer.valueOf(UseLifeMonths));
}
/** Get Usable Life - Months.
@return Months of the usable life of the asset
*/
public int getUseLifeMonths ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeMonths);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usable Life - Years.
@param UseLifeYears
Years of the usable life of the asset
*/
public void setUseLifeYears (int UseLifeYears)
{
set_Value (COLUMNNAME_UseLifeYears, Integer.valueOf(UseLifeYears));
}
/** Get Usable Life - Years.
@return Years of the usable life of the asset
*/
public int getUseLifeYears ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeYears);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Use units.
@param UseUnits
Currently used units of the assets
*/
public void setUseUnits (int UseUnits)
{
set_ValueNoCheck (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits));
}
/** Get Use units.
@return Currently used units of the assets
*/
public int getUseUnits ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
if (ii == null)
return 0;
return ii.intValue();
}
|
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Version No.
@param VersionNo
Version Number
*/
public void setVersionNo (String VersionNo)
{
set_Value (COLUMNNAME_VersionNo, VersionNo);
}
/** Get Version No.
@return Version Number
*/
public String getVersionNo ()
{
return (String)get_Value(COLUMNNAME_VersionNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Student {
private String name;
private int id;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
|
}
@Override
public int hashCode() {
return this.id;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof Student)) {
return false;
}
Student student = (Student) o;
return getName().equals(student.getName());
}
}
|
repos\tutorials-master\spring-web-modules\spring-mvc-basics\src\main\java\com\baeldung\controller\student\Student.java
| 2
|
请完成以下Java代码
|
public void setEndDate (Timestamp EndDate)
{
set_Value (COLUMNNAME_EndDate, EndDate);
}
/** Get End Date.
@return Last effective date (inclusive)
*/
public Timestamp getEndDate ()
{
return (Timestamp)get_Value(COLUMNNAME_EndDate);
}
/** Set Summary Level.
@param IsSummary
This is a summary entity
*/
public void setIsSummary (boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary));
}
/** Get Summary Level.
@return This is a summary entity
*/
public boolean isSummary ()
{
Object oo = get_Value(COLUMNNAME_IsSummary);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set 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);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Campaign.java
| 1
|
请完成以下Java代码
|
public ImmutableList<I_M_Source_HU> retrieveSourceHuMarkers(@NonNull final Collection<HuId> huIds)
{
return sourceHuDAO.retrieveSourceHuMarkers(huIds);
}
public Set<HuId> retrieveMatchingSourceHUIds(@NonNull final MatchingSourceHusQuery query)
{
return sourceHuDAO.retrieveActiveSourceHUIds(query);
}
public boolean isSourceHu(final HuId huId)
{
return sourceHuDAO.isSourceHu(huId);
}
public void addSourceHUMarkerIfCarringComponents(@NonNull final HuId huId, @NonNull final ProductId productId, @NonNull final WarehouseId warehouseId)
{
addSourceHUMarkerIfCarringComponents(ImmutableSet.of(huId), productId, warehouseId);
}
/**
* Creates an M_Source_HU record for the given HU, if it carries component products and the target warehouse has
* the org.compiere.model.I_M_Warehouse#isReceiveAsSourceHU() flag.
*/
public void addSourceHUMarkerIfCarringComponents(@NonNull final Set<HuId> huIds, @NonNull final ProductId productId, @NonNull final WarehouseId warehouseId)
{
if (huIds.isEmpty()) {return;}
final I_M_Warehouse warehouse = warehousesRepo.getById(warehouseId);
if (!warehouse.isReceiveAsSourceHU())
{
return;
}
final boolean referencedInComponentOrVariant = productBOMDAO.isComponent(productId);
if (!referencedInComponentOrVariant)
{
return;
}
huIds.forEach(this::addSourceHuMarker);
}
/**
* Specifies which source HUs (products and warehouse) to retrieve in particular
*/
@lombok.Value
@lombok.Builder
@Immutable
public static class MatchingSourceHusQuery
{
|
/**
* Query for HUs that have any of the given product IDs. Empty means that no HUs will be found.
*/
@Singular
ImmutableSet<ProductId> productIds;
@Singular
ImmutableSet<WarehouseId> warehouseIds;
public static MatchingSourceHusQuery fromHuId(final HuId huId)
{
final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class);
final I_M_HU hu = handlingUnitsBL.getById(huId);
final IHUStorageFactory storageFactory = handlingUnitsBL.getStorageFactory();
final IHUStorage storage = storageFactory.getStorage(hu);
final ImmutableSet<ProductId> productIds = storage.getProductStorages().stream()
.filter(productStorage -> !productStorage.isEmpty())
.map(IProductStorage::getProductId)
.collect(ImmutableSet.toImmutableSet());
final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseId(hu);
return new MatchingSourceHusQuery(productIds, ImmutableSet.of(warehouseId));
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\sourcehu\SourceHUsService.java
| 1
|
请完成以下Java代码
|
public Properties getCtx()
{
return ctx;
}
@Override
public boolean isFailOnFirstError()
{
return failOnFirstError;
}
@Override
public void setFailOnFirstError(final boolean failOnFirstError)
{
this.failOnFirstError = failOnFirstError;
}
@Override
public IMigrationExecutorProvider getMigrationExecutorProvider()
{
return factory;
}
@Override
public void setMigrationOperation(MigrationOperation operation)
{
Check.assumeNotNull(operation, "operation not null");
this.migrationOperation = operation;
}
@Override
public boolean isApplyDML()
{
return migrationOperation == MigrationOperation.BOTH || migrationOperation == MigrationOperation.DML;
}
@Override
public boolean isApplyDDL()
|
{
return migrationOperation == MigrationOperation.BOTH || migrationOperation == MigrationOperation.DDL;
}
@Override
public boolean isSkipMissingColumns()
{
// TODO configuration to be implemented
return true;
}
@Override
public boolean isSkipMissingTables()
{
// TODO configuration to be implemented
return true;
}
@Override
public void addPostponedExecutable(IPostponedExecutable executable)
{
Check.assumeNotNull(executable, "executable not null");
postponedExecutables.add(executable);
}
@Override
public List<IPostponedExecutable> popPostponedExecutables()
{
final List<IPostponedExecutable> result = new ArrayList<IPostponedExecutable>(postponedExecutables);
postponedExecutables.clear();
return result;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationExecutorContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private User deleteUser(TenantId tenantId, UserId userId) {
User userById = edgeCtx.getUserService().findUserById(tenantId, userId);
if (userById == null) {
log.trace("[{}] User with id {} does not exist", tenantId, userId);
return null;
}
edgeCtx.getUserService().deleteUser(tenantId, userById);
return userById;
}
protected void updateUserCredentials(TenantId tenantId, UserCredentialsUpdateMsg updateMsg) {
UserCredentials userCredentials = JacksonUtil.fromString(updateMsg.getEntity(), UserCredentials.class, true);
if (userCredentials == null) {
throw new IllegalArgumentException(String.format("[%s] Failed to parse UserCredentials from updateMsg: %s", tenantId, updateMsg));
}
User user = edgeCtx.getUserService().findUserById(tenantId, userCredentials.getUserId());
if (user == null) {
log.warn("[{}] Can't find user by id [{}] skipping credentials update. UserCredentialsUpdateMsg [{}]",
tenantId, userCredentials.getUserId(), updateMsg);
return;
}
log.debug("[{}] Updating user credentials for user [{}]. New credentials Id [{}], enabled [{}]",
tenantId, user.getName(), userCredentials.getId(), userCredentials.isEnabled());
try {
UserCredentials userCredentialsByUserId = edgeCtx.getUserService().findUserCredentialsByUserId(tenantId, user.getId());
if (userCredentialsByUserId != null && !userCredentialsByUserId.getId().equals(userCredentials.getId())) {
edgeCtx.getUserService().deleteUserCredentials(tenantId, userCredentialsByUserId);
}
edgeCtx.getUserService().saveUserCredentials(tenantId, userCredentials, false);
} catch (Exception e) {
|
log.error("[{}] Can't update user credentials for user [{}], userCredentialsUpdateMsg [{}]",
tenantId, user.getName(), updateMsg, e);
throw new RuntimeException(e);
}
}
private void addRemovedUserMetadata(TbMsgMetaData metaData, User removedUser) {
metaData.putValue("userId", removedUser.getId().toString());
metaData.putValue("userName", removedUser.getName());
metaData.putValue("userEmail", removedUser.getEmail());
if (removedUser.getFirstName() != null) {
metaData.putValue("userFirstName", removedUser.getFirstName());
}
if (removedUser.getLastName() != null) {
metaData.putValue("userLastName", removedUser.getLastName());
}
}
protected abstract void setCustomerId(TenantId tenantId, CustomerId customerId, User user, UserUpdateMsg userUpdateMsg);
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\edge\rpc\processor\user\BaseUserProcessor.java
| 2
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAge() {
return age;
}
|
public void setAge(Integer age) {
this.age = age;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + ", address=" + address + "]";
}
}
|
repos\spring-boot-student-master\spring-boot-student-cache\src\main\java\com\xiaolyuh\entity\Person.java
| 1
|
请完成以下Java代码
|
public class C_TaxDeclaration_CreateLines extends JavaProcess
{
/** Delete Old Lines */
private boolean p_DeleteOld = true;
@Override
protected void prepare()
{
for (final ProcessInfoParameter para : getParametersAsArray())
{
final String name = para.getParameterName();
if (para.getParameter() == null)
{
continue;
}
//
if (name.equals("DeleteOld"))
{
p_DeleteOld = para.getParameterAsBoolean();
}
else
{
log.error("Unknown Parameter: " + name);
}
|
}
} // prepare
@Override
protected String doIt()
{
// Retrieve the tax declaration header (out of transaction).
final I_C_TaxDeclaration taxDeclaration = getProcessInfo().getRecord(I_C_TaxDeclaration.class, ITrx.TRXNAME_None);
Services.get(ITrxManager.class).setThreadInheritedOnRunnableFail(OnRunnableFail.DONT_ROLLBACK); // i.e. don't create savepoints.
final TaxDeclarationLinesBuilder taxDeclarationLinesBuilder = new TaxDeclarationLinesBuilder()
.setC_TaxDeclaration(taxDeclaration)
.setLoggable(this)
.setDeleteOldLines(p_DeleteOld);
taxDeclarationLinesBuilder.build();
return taxDeclarationLinesBuilder.getResultSummary();
} // doIt
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\adempiere\acct\process\C_TaxDeclaration_CreateLines.java
| 1
|
请完成以下Java代码
|
public void setC_OLCandProcessor_ID (final int C_OLCandProcessor_ID)
{
if (C_OLCandProcessor_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OLCandProcessor_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OLCandProcessor_ID, C_OLCandProcessor_ID);
}
@Override
public int getC_OLCandProcessor_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCandProcessor_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
/**
* Granularity AD_Reference_ID=540141
* Reference name: Granularity OLCandAggAndOrder
*/
public static final int GRANULARITY_AD_Reference_ID=540141;
/** Tag = D */
public static final String GRANULARITY_Tag = "D";
/** Woche = W */
public static final String GRANULARITY_Woche = "W";
/** Monat = M */
public static final String GRANULARITY_Monat = "M";
@Override
public void setGranularity (final @Nullable java.lang.String Granularity)
{
set_Value (COLUMNNAME_Granularity, Granularity);
}
@Override
public java.lang.String getGranularity()
{
return get_ValueAsString(COLUMNNAME_Granularity);
}
@Override
public void setGroupBy (final boolean GroupBy)
{
set_Value (COLUMNNAME_GroupBy, GroupBy);
}
|
@Override
public boolean isGroupBy()
{
return get_ValueAsBoolean(COLUMNNAME_GroupBy);
}
@Override
public void setOrderBySeqNo (final int OrderBySeqNo)
{
set_Value (COLUMNNAME_OrderBySeqNo, OrderBySeqNo);
}
@Override
public int getOrderBySeqNo()
{
return get_ValueAsInt(COLUMNNAME_OrderBySeqNo);
}
@Override
public void setSplitOrder (final boolean SplitOrder)
{
set_Value (COLUMNNAME_SplitOrder, SplitOrder);
}
@Override
public boolean isSplitOrder()
{
return get_ValueAsBoolean(COLUMNNAME_SplitOrder);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_OLCandAggAndOrder.java
| 1
|
请完成以下Java代码
|
protected Void execute(CommandContext commandContext, TaskEntity task) {
if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, task.getProcessDefinitionId())) {
Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
compatibilityHandler.claimTask(taskId, userId);
return null;
}
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
if (userId != null) {
Clock clock = processEngineConfiguration.getClock();
task.setClaimTime(clock.getCurrentTime());
task.setClaimedBy(userId);
task.setState(Task.CLAIMED);
if (task.getAssignee() != null) {
if (!task.getAssignee().equals(userId)) {
// When the task is already claimed by another user, throw
// exception. Otherwise, ignore this, post-conditions of method already met.
throw new FlowableTaskAlreadyClaimedException(task.getId(), task.getAssignee());
}
CommandContextUtil.getActivityInstanceEntityManager(commandContext).recordTaskInfoChange(task, clock.getCurrentTime());
} else {
TaskHelper.changeTaskAssignee(task, userId);
if (processEngineConfiguration.getUserTaskStateInterceptor() != null) {
processEngineConfiguration.getUserTaskStateInterceptor().handleClaim(task, userId);
}
}
CommandContextUtil.getHistoryManager().createUserIdentityLinkComment(task, userId, IdentityLinkType.ASSIGNEE, true);
} else {
if (task.getAssignee() != null) {
|
// Task claim time should be null
task.setClaimTime(null);
task.setClaimedBy(null);
if (task.getInProgressStartTime() != null) {
task.setState(Task.IN_PROGRESS);
} else {
task.setState(Task.CREATED);
}
String oldAssigneeId = task.getAssignee();
// Task should be assigned to no one
TaskHelper.changeTaskAssignee(task, null);
if (processEngineConfiguration.getUserTaskStateInterceptor() != null) {
processEngineConfiguration.getUserTaskStateInterceptor().handleUnclaim(task, userId);
}
CommandContextUtil.getHistoryManager().createUserIdentityLinkComment(task, oldAssigneeId, IdentityLinkType.ASSIGNEE, true, true);
}
}
return null;
}
@Override
protected String getSuspendedTaskExceptionPrefix() {
return "Cannot claim";
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\ClaimTaskCmd.java
| 1
|
请完成以下Java代码
|
public String getFormKey() {
return formKey;
}
public CamundaFormRef getCamundaFormRef() {
return camundaFormRef;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTaskState() {
return taskState;
}
public void setTaskState(String taskState) {
this.taskState = taskState;
}
public static TaskDto fromEntity(Task task) {
TaskDto dto = new TaskDto();
dto.id = task.getId();
dto.name = task.getName();
dto.assignee = task.getAssignee();
dto.created = task.getCreateTime();
dto.lastUpdated = task.getLastUpdated();
dto.due = task.getDueDate();
dto.followUp = task.getFollowUpDate();
if (task.getDelegationState() != null) {
dto.delegationState = task.getDelegationState().toString();
}
dto.description = task.getDescription();
dto.executionId = task.getExecutionId();
dto.owner = task.getOwner();
dto.parentTaskId = task.getParentTaskId();
dto.priority = task.getPriority();
dto.processDefinitionId = task.getProcessDefinitionId();
dto.processInstanceId = task.getProcessInstanceId();
dto.taskDefinitionKey = task.getTaskDefinitionKey();
|
dto.caseDefinitionId = task.getCaseDefinitionId();
dto.caseExecutionId = task.getCaseExecutionId();
dto.caseInstanceId = task.getCaseInstanceId();
dto.suspended = task.isSuspended();
dto.tenantId = task.getTenantId();
dto.taskState = task.getTaskState();
try {
dto.formKey = task.getFormKey();
dto.camundaFormRef = task.getCamundaFormRef();
}
catch (BadUserRequestException e) {
// ignore (initializeFormKeys was not called)
}
return dto;
}
public void updateTask(Task task) {
task.setName(getName());
task.setDescription(getDescription());
task.setPriority(getPriority());
task.setAssignee(getAssignee());
task.setOwner(getOwner());
DelegationState state = null;
if (getDelegationState() != null) {
DelegationStateConverter converter = new DelegationStateConverter();
state = converter.convertQueryParameterToType(getDelegationState());
}
task.setDelegationState(state);
task.setDueDate(getDue());
task.setFollowUpDate(getFollowUp());
task.setParentTaskId(getParentTaskId());
task.setCaseInstanceId(getCaseInstanceId());
task.setTenantId(getTenantId());
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\task\TaskDto.java
| 1
|
请完成以下Java代码
|
public ResponseEntity favoriteArticle(
@PathVariable("slug") String slug, @AuthenticationPrincipal User user) {
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
ArticleFavorite articleFavorite = new ArticleFavorite(article.getId(), user.getId());
articleFavoriteRepository.save(articleFavorite);
return responseArticleData(articleQueryService.findBySlug(slug, user).get());
}
@DeleteMapping
public ResponseEntity unfavoriteArticle(
@PathVariable("slug") String slug, @AuthenticationPrincipal User user) {
Article article =
articleRepository.findBySlug(slug).orElseThrow(ResourceNotFoundException::new);
articleFavoriteRepository
.find(article.getId(), user.getId())
.ifPresent(
favorite -> {
|
articleFavoriteRepository.remove(favorite);
});
return responseArticleData(articleQueryService.findBySlug(slug, user).get());
}
private ResponseEntity<HashMap<String, Object>> responseArticleData(
final ArticleData articleData) {
return ResponseEntity.ok(
new HashMap<String, Object>() {
{
put("article", articleData);
}
});
}
}
|
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\ArticleFavoriteApi.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
# datasource 数据源配置内容
datasource:
# 订单数据源配置
orders:
url: jdbc:mysql://127.0.0.1:3306/test_orders?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: root
password:
type: com.alibaba.druid.pool.DruidDataSource # 设置类型为 DruidDataSource
# Druid 自定义配置,对应 DruidDataSource 中的 setting 方法的属性
min-idle: 0 # 池中维护的最小空闲连接数,默认为 0 个。
max-active: 20 # 池中最大连接数,包括闲置和使用中的连接,默认为 8 个。
# 用户数据源配置
users:
url: jdbc:mysql://127.0.0.1:3306/test_users?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: root
password:
type: com.alibaba.druid.pool.DruidDataSource # 设置类型为 DruidDataSource
# Druid 自定义配置,对应 DruidDataSource 中的 setting 方法的属性
min-idle: 0 # 池中维护的最小空闲连接数,默认为 0 个。
max-active: 20 # 池中最大连接数,包括闲置和使用中的连接,默认为 8 个。
# Druid 自定已配置
druid:
# 过滤器配置
filter:
stat: # 配置 StatFilter ,对应文档 https://git
|
hub.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_StatFilter
log-slow-sql: true # 开启慢查询记录
slow-sql-millis: 5000 # 慢 SQL 的标准,单位:毫秒
# StatViewServlet 配置
stat-view-servlet: # 配置 StatViewServlet ,对应文档 https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_StatViewServlet%E9%85%8D%E7%BD%AE
enabled: true # 是否开启 StatViewServlet
login-username: yudaoyuanma # 账号
login-password: javaniubi # 密码
|
repos\SpringBoot-Labs-master\lab-19\lab-19-datasource-pool-druid-multiple\src\main\resources\application.yaml
| 2
|
请完成以下Java代码
|
public String toString()
{
return MoreObjects.toStringHelper(this).addValue(delegate).toString();
}
@Override
public void lockUI(final ProcessInfo pi)
{
invokeInEDT(() -> delegate.lockUI(pi));
}
@Override
public void unlockUI(final ProcessInfo pi)
{
invokeInEDT(() -> delegate.unlockUI(pi));
|
}
private final void invokeInEDT(final Runnable runnable)
{
if (SwingUtilities.isEventDispatchThread())
{
runnable.run();
}
else
{
SwingUtilities.invokeLater(runnable);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\SwingProcessExecutionListener.java
| 1
|
请完成以下Java代码
|
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
this.isbn = isbn;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
|
}
if (getClass() != obj.getClass()) {
return false;
}
return id != null && id.equals(((Book) obj).id);
}
@Override
public int hashCode() {
return 2021;
}
public short getVersion() {
return version;
}
@Override
public String toString() {
return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}';
}
}
|
repos\Hibernate-SpringBoot-master\HibernateSpringBootBatchDeleteCascadeDelete\src\main\java\com\bookstore\entity\Book.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Deployment deployBpmnAndDrl(String url, String drlUrl) {
Deployment deploy = createDeployment().addClasspathResource(url).addClasspathResource(drlUrl).deploy();
return deploy;
}
@Override
public Deployment deploy(String url, String name, String category) {
Deployment deploy = createDeployment().addClasspathResource(url).name(name).category(category).deploy();
return deploy;
}
@Override
public Deployment deploy(String url, String pngUrl, String name, String category) {
Deployment deploy = createDeployment().addClasspathResource(url).addClasspathResource(pngUrl)
.name(name).category(category).deploy();
return deploy;
}
@Override
public boolean exist(String processDefinitionKey) {
ProcessDefinitionQuery processDefinitionQuery
= createProcessDefinitionQuery().processDefinitionKey(processDefinitionKey);
long count = processDefinitionQuery.count();
return count > 0 ? true : false;
}
@Override
public Deployment deploy(String name, String tenantId, String category, InputStream in) {
return createDeployment().addInputStream(name + BPMN_FILE_SUFFIX, in)
.name(name)
.tenantId(tenantId)
.category(category)
.deploy();
}
@Override
public ProcessDefinition queryByProcessDefinitionKey(String processDefinitionKey) {
ProcessDefinition processDefinition
|
= createProcessDefinitionQuery()
.processDefinitionKey(processDefinitionKey)
.active().singleResult();
return processDefinition;
}
@Override
public Deployment deployName(String deploymentName) {
List<Deployment> list = repositoryService
.createDeploymentQuery()
.deploymentName(deploymentName).list();
Assert.notNull(list, "list must not be null");
return list.get(0);
}
@Override
public void addCandidateStarterUser(String processDefinitionKey, String userId) {
repositoryService.addCandidateStarterUser(processDefinitionKey, userId);
}
}
|
repos\spring-boot-quick-master\quick-flowable\src\main\java\com\quick\flowable\service\handler\ProcessHandler.java
| 2
|
请完成以下Java代码
|
public byte[] decrypt(byte[] encryptedBytes) {
synchronized (this.decryptor) {
byte[] iv = iv(encryptedBytes);
CipherUtils.initCipher(this.decryptor, Cipher.DECRYPT_MODE, this.secretKey, this.alg.getParameterSpec(iv));
return CipherUtils.doFinal(this.decryptor,
(this.ivGenerator != NULL_IV_GENERATOR) ? encrypted(encryptedBytes, iv.length) : encryptedBytes);
}
}
private byte[] iv(byte[] encrypted) {
return (this.ivGenerator != NULL_IV_GENERATOR)
? EncodingUtils.subArray(encrypted, 0, this.ivGenerator.getKeyLength())
: NULL_IV_GENERATOR.generateKey();
}
private byte[] encrypted(byte[] encryptedBytes, int ivLength) {
return EncodingUtils.subArray(encryptedBytes, ivLength, encryptedBytes.length);
}
private static final BytesKeyGenerator NULL_IV_GENERATOR = new BytesKeyGenerator() {
private final byte[] VALUE = new byte[16];
@Override
public int getKeyLength() {
return this.VALUE.length;
}
@Override
public byte[] generateKey() {
return this.VALUE;
}
};
public enum CipherAlgorithm {
CBC(AES_CBC_ALGORITHM, NULL_IV_GENERATOR),
GCM(AES_GCM_ALGORITHM, KeyGenerators.secureRandom(16));
private BytesKeyGenerator ivGenerator;
|
private String name;
CipherAlgorithm(String name, BytesKeyGenerator ivGenerator) {
this.name = name;
this.ivGenerator = ivGenerator;
}
@Override
public String toString() {
return this.name;
}
public AlgorithmParameterSpec getParameterSpec(byte[] iv) {
return (this != CBC) ? new GCMParameterSpec(128, iv) : new IvParameterSpec(iv);
}
public Cipher createCipher() {
return CipherUtils.newCipher(this.toString());
}
public BytesKeyGenerator defaultIvGenerator() {
return this.ivGenerator;
}
}
}
|
repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\encrypt\AesBytesEncryptor.java
| 1
|
请完成以下Java代码
|
public void setSEPA_Export_ID (final int SEPA_Export_ID)
{
if (SEPA_Export_ID < 1)
set_ValueNoCheck (COLUMNNAME_SEPA_Export_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SEPA_Export_ID, SEPA_Export_ID);
}
@Override
public int getSEPA_Export_ID()
{
return get_ValueAsInt(COLUMNNAME_SEPA_Export_ID);
}
@Override
public void setSEPA_Export_Line_ID (final int SEPA_Export_Line_ID)
{
if (SEPA_Export_Line_ID < 1)
set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_ID, SEPA_Export_Line_ID);
}
@Override
public int getSEPA_Export_Line_ID()
{
return get_ValueAsInt(COLUMNNAME_SEPA_Export_Line_ID);
}
@Override
public void setSEPA_Export_Line_Ref_ID (final int SEPA_Export_Line_Ref_ID)
{
if (SEPA_Export_Line_Ref_ID < 1)
set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_Ref_ID, null);
|
else
set_ValueNoCheck (COLUMNNAME_SEPA_Export_Line_Ref_ID, SEPA_Export_Line_Ref_ID);
}
@Override
public int getSEPA_Export_Line_Ref_ID()
{
return get_ValueAsInt(COLUMNNAME_SEPA_Export_Line_Ref_ID);
}
@Override
public void setStructuredRemittanceInfo (final @Nullable String StructuredRemittanceInfo)
{
set_Value (COLUMNNAME_StructuredRemittanceInfo, StructuredRemittanceInfo);
}
@Override
public String getStructuredRemittanceInfo()
{
return get_ValueAsString(COLUMNNAME_StructuredRemittanceInfo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\base\src\main\java-gen\de\metas\payment\sepa\model\X_SEPA_Export_Line_Ref.java
| 1
|
请完成以下Java代码
|
public String getOperationId() {
if (!getOperationLogManager().isUserOperationLogEnabled()) {
return null;
}
if (operationId == null) {
operationId = Context.getProcessEngineConfiguration().getIdGenerator().getNextId();
}
return operationId;
}
public void setOperationId(String operationId) {
this.operationId = operationId;
}
public OptimizeManager getOptimizeManager() {
return getSession(OptimizeManager.class);
}
|
public <T> void executeWithOperationLogPrevented(Command<T> command) {
boolean initialLegacyRestrictions =
isRestrictUserOperationLogToAuthenticatedUsers();
disableUserOperationLog();
setRestrictUserOperationLogToAuthenticatedUsers(true);
try {
command.execute(this);
} finally {
enableUserOperationLog();
setRestrictUserOperationLogToAuthenticatedUsers(initialLegacyRestrictions);
}
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\interceptor\CommandContext.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public abstract class PushRegistryProperties {
/**
* Step size (i.e. reporting frequency) to use.
*/
private Duration step = Duration.ofMinutes(1);
/**
* Whether exporting of metrics to this backend is enabled.
*/
private boolean enabled = true;
/**
* Connection timeout for requests to this backend.
*/
private Duration connectTimeout = Duration.ofSeconds(1);
/**
* Read timeout for requests to this backend.
*/
private Duration readTimeout = Duration.ofSeconds(10);
/**
* Number of measurements per request to use for this backend. If more measurements
* are found, then multiple requests will be made.
*/
private Integer batchSize = 10000;
public Duration getStep() {
return this.step;
}
public void setStep(Duration step) {
this.step = step;
}
|
public boolean isEnabled() {
return this.enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public Duration getConnectTimeout() {
return this.connectTimeout;
}
public void setConnectTimeout(Duration connectTimeout) {
this.connectTimeout = connectTimeout;
}
public Duration getReadTimeout() {
return this.readTimeout;
}
public void setReadTimeout(Duration readTimeout) {
this.readTimeout = readTimeout;
}
public Integer getBatchSize() {
return this.batchSize;
}
public void setBatchSize(Integer batchSize) {
this.batchSize = batchSize;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\properties\PushRegistryProperties.java
| 2
|
请完成以下Java代码
|
public ShipmentScheduleLocksMap getByShipmentScheduleIds(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds)
{
Check.assumeNotEmpty(shipmentScheduleIds, "shipmentScheduleIds is not empty");
final List<Object> sqlParams = new ArrayList<>();
final String sql = "SELECT * FROM " + I_M_ShipmentSchedule_Lock.Table_Name
+ " WHERE " + DB.buildSqlList(I_M_ShipmentSchedule_Lock.COLUMNNAME_M_ShipmentSchedule_ID, shipmentScheduleIds, sqlParams);
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited);
DB.setParameters(pstmt, sqlParams);
rs = pstmt.executeQuery();
final List<ShipmentScheduleLock> locks = new ArrayList<>();
while (rs.next())
{
locks.add(retrieveLock(rs));
}
return ShipmentScheduleLocksMap.of(locks);
}
catch (final SQLException ex)
{
throw new DBException(ex, sql, sqlParams);
}
|
finally
{
DB.close(rs, pstmt);
}
}
private static ShipmentScheduleLock retrieveLock(final ResultSet rs) throws SQLException
{
return ShipmentScheduleLock.builder()
.shipmentScheduleId(ShipmentScheduleId.ofRepoId(rs.getInt(I_M_ShipmentSchedule_Lock.COLUMNNAME_M_ShipmentSchedule_ID)))
.lockedBy(UserId.ofRepoId(rs.getInt(I_M_ShipmentSchedule_Lock.COLUMNNAME_LockedBy_User_ID)))
.lockType(ShipmentScheduleLockType.ofCode(rs.getString(I_M_ShipmentSchedule_Lock.COLUMNNAME_LockType)))
.created(rs.getTimestamp(I_M_ShipmentSchedule_Lock.COLUMNNAME_Created).toInstant())
.build();
}
private void fireShipmentSchedulesChanged(final Set<ShipmentScheduleId> shipmentScheduleIds)
{
if (shipmentScheduleIds.isEmpty())
{
return;
}
final CacheInvalidateMultiRequest request = CacheInvalidateMultiRequest.rootRecords(I_M_ShipmentSchedule.Table_Name, shipmentScheduleIds);
modelCacheInvalidationService.invalidate(request, ModelCacheInvalidationTiming.AFTER_CHANGE);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\lock\SqlShipmentScheduleLockRepository.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Security {
private String username;
private String password;
private List<String> roles = new ArrayList<>(Collections.singleton("USER"));
// @fold:on // getters / setters...
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return this.password;
}
|
public void setPassword(String password) {
this.password = password;
}
public List<String> getRoles() {
return this.roles;
}
public void setRoles(List<String> roles) {
this.roles = roles;
}
// @fold:off
}
}
|
repos\spring-boot-4.0.1\documentation\spring-boot-docs\src\main\java\org\springframework\boot\docs\features\externalconfig\typesafeconfigurationproperties\javabeanbinding\MyProperties.java
| 2
|
请完成以下Java代码
|
void updateAggregatedValuesTo(@NonNull final IAttributeSet to)
{
attributeAggregators.values()
.forEach(attributeAggregator -> attributeAggregator.updateAggregatedValueTo(to));
}
private static boolean isAggregable(@NonNull final I_M_Attribute attribute)
{
return !Weightables.isWeightableAttribute(AttributeCode.ofString(attribute.getValue()));
}
//
//
//
@RequiredArgsConstructor
private static class AttributeAggregator
{
private final AttributeCode attributeCode;
private final AttributeValueType attributeValueType;
private final HashSet<Object> values = new HashSet<>();
void collect(@NonNull final IAttributeSet from)
{
final Object value = attributeValueType.map(new AttributeValueType.CaseMapper<Object>()
{
@Nullable
@Override
public Object string()
{
return from.getValueAsString(attributeCode);
}
@Override
|
public Object number()
{
return from.getValueAsBigDecimal(attributeCode);
}
@Nullable
@Override
public Object date()
{
return from.getValueAsDate(attributeCode);
}
@Nullable
@Override
public Object list()
{
return from.getValueAsString(attributeCode);
}
});
values.add(value);
}
void updateAggregatedValueTo(@NonNull final IAttributeSet to)
{
if (values.size() == 1 && to.hasAttribute(attributeCode))
{
to.setValue(attributeCode, values.iterator().next());
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AttributeSetAggregator.java
| 1
|
请完成以下Java代码
|
public boolean isScoped() {
return this.scopes != null && !this.scopes.isEmpty();
}
/**
* scopes
*
* @return scopes
*/
@Override
public Set<String> getScope() {
return stringToSet(scopes);
}
/**
* 授权类型
*
* @return 结果
*/
@Override
public Set<String> getAuthorizedGrantTypes() {
return stringToSet(grantTypes);
}
@Override
public Set<String> getResourceIds() {
return stringToSet(resourceIds);
}
/**
* 获取回调地址
*
* @return redirectUrl
*/
@Override
public Set<String> getRegisteredRedirectUri() {
return stringToSet(redirectUrl);
}
/**
* 这里需要提一下
* 个人觉得这里应该是客户端所有的权限
* 但是已经有 scope 的存在可以很好的对客户端的权限进行认证了
* 那么在 oauth2 的四个角色中,这里就有可能是资源服务器的权限
* 但是一般资源服务器都有自己的权限管理机制,比如拿到用户信息后做 RBAC
* 所以在 spring security 的默认实现中直接给的是空的一个集合
* 这里我们也给他一个空的把
|
*
* @return GrantedAuthority
*/
@Override
public Collection<GrantedAuthority> getAuthorities() {
return Collections.emptyList();
}
/**
* 判断是否自动授权
*
* @param scope scope
* @return 结果
*/
@Override
public boolean isAutoApprove(String scope) {
if (autoApproveScopes == null || autoApproveScopes.isEmpty()) {
return false;
}
Set<String> authorizationSet = stringToSet(authorizations);
for (String auto : authorizationSet) {
if ("true".equalsIgnoreCase(auto) || scope.matches(auto)) {
return true;
}
}
return false;
}
/**
* additional information 是 spring security 的保留字段
* 暂时用不到,直接给个空的即可
*
* @return map
*/
@Override
public Map<String, Object> getAdditionalInformation() {
return Collections.emptyMap();
}
private Set<String> stringToSet(String s) {
return Arrays.stream(s.split(",")).collect(Collectors.toSet());
}
}
|
repos\spring-boot-demo-master\demo-oauth\oauth-authorization-server\src\main\java\com\xkcoding\oauth\entity\SysClientDetails.java
| 1
|
请完成以下Java代码
|
public boolean hasParameters()
{
return !getDependsOnFieldNames().isEmpty();
}
@Override
public abstract boolean isNumericKey();
@Override
public abstract Set<String> getDependsOnFieldNames();
//
//
//
// -----------------------
//
//
@Override
public LookupDataSourceContext.Builder newContextForFetchingById(final Object id)
{
return LookupDataSourceContext.builderWithoutTableName();
}
@Override
@Nullable
public abstract LookupValue retrieveLookupValueById(@NonNull LookupDataSourceContext evalCtx);
@Override
public LookupDataSourceContext.Builder newContextForFetchingList()
{
return LookupDataSourceContext.builderWithoutTableName();
}
@Override
public abstract LookupValuesPage retrieveEntities(LookupDataSourceContext evalCtx);
|
@Override
@Nullable
public final String getCachePrefix()
{
// NOTE: method will never be called because isCached() == true
return null;
}
@Override
public final boolean isCached()
{
return true;
}
@Override
public void cacheInvalidate()
{
}
@Override
public Optional<WindowId> getZoomIntoWindowId()
{
return Optional.empty();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\SimpleLookupDescriptorTemplate.java
| 1
|
请完成以下Java代码
|
public class QuickInputLayoutDescriptor
{
public static Builder builder()
{
return new Builder();
}
public static QuickInputLayoutDescriptor onlyFields(
@NonNull final DocumentEntityDescriptor entityDescriptor,
@NonNull final String[][] fieldNames)
{
Check.assumeNotEmpty(fieldNames, "fieldNames is not empty");
final Builder layoutBuilder = builder();
for (final String[] elementFieldNames : fieldNames)
{
if (elementFieldNames == null || elementFieldNames.length == 0)
{
continue;
}
DocumentLayoutElementDescriptor
.builderOrEmpty(entityDescriptor, elementFieldNames)
.ifPresent(layoutBuilder::element);
}
return layoutBuilder.build();
}
/**
* @deprecated please use {@link #onlyFields(DocumentEntityDescriptor, String[][])}
*/
@Deprecated
public static QuickInputLayoutDescriptor build(@NonNull final DocumentEntityDescriptor entityDescriptor, @NonNull final String[][] fieldNames) {return onlyFields(entityDescriptor, fieldNames);}
public static QuickInputLayoutDescriptor onlyFields(
@NonNull final DocumentEntityDescriptor entityDescriptor,
@NonNull final List<String> fieldNames)
{
Check.assumeNotEmpty(fieldNames, "fieldNames is not empty");
final Builder layoutBuilder = builder();
for (final String fieldName : fieldNames)
{
if (Check.isBlank(fieldName))
{
continue;
}
DocumentLayoutElementDescriptor
.builderOrEmpty(entityDescriptor, fieldName)
.ifPresent(layoutBuilder::element);
}
return layoutBuilder.build();
}
@SuppressWarnings("unused")
public static QuickInputLayoutDescriptor allFields(@NonNull final DocumentEntityDescriptor entityDescriptor)
{
final Builder layoutBuilder = builder();
for (final DocumentFieldDescriptor field : entityDescriptor.getFields())
{
final DocumentLayoutElementDescriptor.Builder element = DocumentLayoutElementDescriptor.builder(field);
layoutBuilder.element(element);
}
return layoutBuilder.build();
}
private final List<DocumentLayoutElementDescriptor> elements;
private QuickInputLayoutDescriptor(final List<DocumentLayoutElementDescriptor> elements)
{
this.elements = ImmutableList.copyOf(elements);
}
|
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("elements", elements.isEmpty() ? null : elements)
.toString();
}
public List<DocumentLayoutElementDescriptor> getElements()
{
return elements;
}
public static final class Builder
{
private final List<DocumentLayoutElementDescriptor> elements = new ArrayList<>();
private Builder()
{
}
public QuickInputLayoutDescriptor build()
{
return new QuickInputLayoutDescriptor(elements);
}
public Builder element(@NonNull final DocumentLayoutElementDescriptor.Builder elementBuilder)
{
elements.add(elementBuilder.build());
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputLayoutDescriptor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JpaTenantDao extends JpaAbstractDao<TenantEntity, Tenant> implements TenantDao {
@Autowired
private TenantRepository tenantRepository;
@Override
protected Class<TenantEntity> getEntityClass() {
return TenantEntity.class;
}
@Override
protected JpaRepository<TenantEntity, UUID> getRepository() {
return tenantRepository;
}
@Override
public TenantInfo findTenantInfoById(TenantId tenantId, UUID id) {
return DaoUtil.getData(tenantRepository.findTenantInfoById(id));
}
@Override
public PageData<Tenant> findTenants(TenantId tenantId, PageLink pageLink) {
return DaoUtil.toPageData(tenantRepository
.findTenantsNextPage(
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<TenantInfo> findTenantInfos(TenantId tenantId, PageLink pageLink) {
return DaoUtil.toPageData(tenantRepository
.findTenantInfosNextPage(
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink, TenantInfoEntity.tenantInfoColumnMap)));
}
@Override
public PageData<TenantId> findTenantsIds(PageLink pageLink) {
return DaoUtil.pageToPageData(tenantRepository.findTenantsIds(DaoUtil.toPageable(pageLink))).mapData(TenantId::fromUUID);
|
}
@Override
public EntityType getEntityType() {
return EntityType.TENANT;
}
@Override
public List<TenantId> findTenantIdsByTenantProfileId(TenantProfileId tenantProfileId) {
return tenantRepository.findTenantIdsByTenantProfileId(tenantProfileId.getId()).stream()
.map(TenantId::fromUUID)
.collect(Collectors.toList());
}
@Override
public Tenant findTenantByName(TenantId tenantId, String name) {
return DaoUtil.getData(tenantRepository.findFirstByTitle(name));
}
@Override
public List<Tenant> findTenantsByIds(UUID tenantId, List<UUID> tenantIds) {
return DaoUtil.convertDataList(tenantRepository.findTenantsByIdIn(tenantIds));
}
@Override
public List<TenantFields> findNextBatch(UUID id, int batchSize) {
return tenantRepository.findNextBatch(id, Limit.of(batchSize));
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\tenant\JpaTenantDao.java
| 2
|
请完成以下Java代码
|
public long executeCount(CommandContext commandContext) {
checkQueryOk();
ensureVariablesInitialized();
return commandContext
.getHistoricVariableInstanceEntityManager()
.findHistoricVariableInstanceCountByQueryCriteria(this);
}
public List<HistoricVariableInstance> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
ensureVariablesInitialized();
List<HistoricVariableInstance> historicVariableInstances = commandContext
.getHistoricVariableInstanceEntityManager()
.findHistoricVariableInstancesByQueryCriteria(this, page);
if (!excludeVariableInitialization) {
for (HistoricVariableInstance historicVariableInstance : historicVariableInstances) {
if (historicVariableInstance instanceof HistoricVariableInstanceEntity) {
HistoricVariableInstanceEntity variableEntity =
(HistoricVariableInstanceEntity) historicVariableInstance;
if (variableEntity != null && variableEntity.getVariableType() != null) {
variableEntity.getValue();
// make sure JPA entities are cached for later retrieval
if (
JPAEntityVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName()) ||
JPAEntityListVariableType.TYPE_NAME.equals(variableEntity.getVariableType().getTypeName())
) {
((CacheableVariable) variableEntity.getVariableType()).setForceCacheable(true);
}
}
}
}
}
return historicVariableInstances;
}
// order by
// /////////////////////////////////////////////////////////////////
public HistoricVariableInstanceQuery orderByProcessInstanceId() {
orderBy(HistoricVariableInstanceQueryProperty.PROCESS_INSTANCE_ID);
return this;
}
public HistoricVariableInstanceQuery orderByVariableName() {
orderBy(HistoricVariableInstanceQueryProperty.VARIABLE_NAME);
return this;
}
// getters and setters
// //////////////////////////////////////////////////////
public String getProcessInstanceId() {
|
return processInstanceId;
}
public String getTaskId() {
return taskId;
}
public String getActivityInstanceId() {
return activityInstanceId;
}
public boolean getExcludeTaskRelated() {
return excludeTaskRelated;
}
public String getVariableName() {
return variableName;
}
public String getVariableNameLike() {
return variableNameLike;
}
public QueryVariableValue getQueryVariableValue() {
return queryVariableValue;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricVariableInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
public boolean schedule(Runnable runnable, boolean isLongRunning) {
if(isLongRunning) {
return scheduleLongRunning(runnable);
} else {
return executeShortRunning(runnable);
}
}
protected boolean executeShortRunning(Runnable runnable) {
try {
workManager.schedule(new CommonjWorkRunnableAdapter(runnable));
return true;
} catch (WorkRejectedException e) {
logger.log(Level.FINE, "Work rejected", e);
} catch (WorkException e) {
logger.log(Level.WARNING, "WorkException while scheduling jobs for execution", e);
}
return false;
}
protected boolean scheduleLongRunning(Runnable acquisitionRunnable) {
// initialize the workManager here, because we have access to the initial context
// of the calling thread (application), so the jndi lookup is working -> see JCA 1.6 specification
if(workManager == null) {
workManager = lookupWorkMananger();
}
try {
workManager.schedule(new CommonjDeamonWorkRunnableAdapter(acquisitionRunnable));
return true;
|
} catch (WorkException e) {
logger.log(Level.WARNING, "Could not schedule Job Acquisition Runnable: "+e.getMessage(), e);
return false;
}
}
public Runnable getExecuteJobsRunnable(List<String> jobIds, ProcessEngineImpl processEngine) {
return new JcaInflowExecuteJobsRunnable(jobIds, processEngine, ra);
}
// getters / setters ////////////////////////////////////
public WorkManager getWorkManager() {
return workManager;
}
}
|
repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\commonj\CommonJWorkManagerExecutorService.java
| 1
|
请完成以下Java代码
|
private static Method getSecurityNameMethod() {
if (getSecurityName == null) {
getSecurityName = getMethod("com.ibm.websphere.security.cred.WSCredential", "getSecurityName",
new String[] {});
}
return getSecurityName;
}
private static Method getNarrowMethod() {
if (narrow == null) {
narrow = getMethod(PORTABLE_REMOTE_OBJECT_CLASSNAME, "narrow",
new String[] { Object.class.getName(), Class.class.getName() });
}
return narrow;
}
// SEC-803
private static Class<?> getWSCredentialClass() {
|
if (wsCredentialClass == null) {
wsCredentialClass = getClass("com.ibm.websphere.security.cred.WSCredential");
}
return wsCredentialClass;
}
private static Class<?> getClass(String className) {
try {
return Class.forName(className);
}
catch (ClassNotFoundException ex) {
logger.error("Required class " + className + " not found");
throw new RuntimeException("Required class " + className + " not found", ex);
}
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\websphere\DefaultWASUsernameAndGroupsExtractor.java
| 1
|
请完成以下Java代码
|
public class GetProcessDefinitionHistoryLevelModelCmd implements Command<HistoryLevel>, Serializable {
private static final long serialVersionUID = 1L;
protected String processDefinitionId;
public GetProcessDefinitionHistoryLevelModelCmd(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
@Override
public HistoryLevel execute(CommandContext commandContext) {
if (processDefinitionId == null) {
throw new FlowableIllegalArgumentException("processDefinitionId is null");
}
HistoryLevel historyLevel = null;
ProcessDefinition processDefinition = CommandContextUtil.getProcessDefinitionEntityManager(commandContext).findById(processDefinitionId);
BpmnModel bpmnModel = ProcessDefinitionUtil.getBpmnModel(processDefinitionId);
Process process = bpmnModel.getProcessById(processDefinition.getKey());
|
if (process.getExtensionElements().containsKey("historyLevel")) {
ExtensionElement historyLevelElement = process.getExtensionElements().get("historyLevel").iterator().next();
String historyLevelValue = historyLevelElement.getElementText();
if (StringUtils.isNotEmpty(historyLevelValue)) {
try {
historyLevel = HistoryLevel.getHistoryLevelForKey(historyLevelValue);
} catch (Exception e) {
}
}
}
if (historyLevel == null) {
historyLevel = CommandContextUtil.getProcessEngineConfiguration(commandContext).getHistoryLevel();
}
return historyLevel;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\GetProcessDefinitionHistoryLevelModelCmd.java
| 1
|
请完成以下Java代码
|
public class SetJobsRetriesByProcessBatchCmd extends AbstractSetJobsRetriesBatchCmd {
protected final List<String> processInstanceIds;
protected final ProcessInstanceQuery query;
protected HistoricProcessInstanceQuery historicProcessInstanceQuery;
public SetJobsRetriesByProcessBatchCmd(List<String> processInstanceIds,
ProcessInstanceQuery query,
HistoricProcessInstanceQuery historicProcessInstanceQuery,
int retries,
Date dueDate,
boolean isDueDateSet) {
this.processInstanceIds = processInstanceIds;
this.query = query;
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
this.retries = retries;
this.dueDate = dueDate;
this.isDueDateSet = isDueDateSet;
}
protected BatchElementConfiguration collectJobIds(CommandContext commandContext) {
Set<String> collectedProcessInstanceIds = new HashSet<>();
if (query != null) {
collectedProcessInstanceIds.addAll(((ProcessInstanceQueryImpl)query).listIds());
}
if (historicProcessInstanceQuery != null) {
List<String> ids =
((HistoricProcessInstanceQueryImpl) historicProcessInstanceQuery).listIds();
collectedProcessInstanceIds.addAll(ids);
}
|
if (this.processInstanceIds != null) {
collectedProcessInstanceIds.addAll(this.processInstanceIds);
}
BatchElementConfiguration elementConfiguration = new BatchElementConfiguration();
if (!CollectionUtil.isEmpty(collectedProcessInstanceIds)) {
JobQueryImpl jobQuery = new JobQueryImpl();
jobQuery.processInstanceIds(collectedProcessInstanceIds);
elementConfiguration.addDeploymentMappings(commandContext.runWithoutAuthorization(jobQuery::listDeploymentIdMappings));
}
return elementConfiguration;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\SetJobsRetriesByProcessBatchCmd.java
| 1
|
请完成以下Java代码
|
public class Book {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column(updatable = false)
private String title;
@Column(insertable = false)
private Instant createdAt;
@ToString.Exclude
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "author_id")
private Author author;
@ToString.Exclude
@OneToMany(fetch = FetchType.LAZY)
@Cascade({ CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REMOVE })
private List<Page> pages;
|
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || Hibernate.getClass(this) != Hibernate.getClass(o))
return false;
Book book = (Book) o;
return id != null && Objects.equals(id, book.id);
}
@Override
public int hashCode() {
return getClass().hashCode();
}
}
|
repos\tutorials-master\persistence-modules\jimmer\src\main\java\com\baeldung\jimmer\introduction\hibernate\Book.java
| 1
|
请完成以下Java代码
|
public int getUser2_ID()
{
return get_ValueAsInt(COLUMNNAME_User2_ID);
}
@Override
public org.compiere.model.I_S_Resource getWorkStation()
{
return get_ValueAsPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class);
}
@Override
public void setWorkStation(final org.compiere.model.I_S_Resource WorkStation)
{
set_ValueFromPO(COLUMNNAME_WorkStation_ID, org.compiere.model.I_S_Resource.class, WorkStation);
}
@Override
public void setWorkStation_ID (final int WorkStation_ID)
{
if (WorkStation_ID < 1)
set_Value (COLUMNNAME_WorkStation_ID, null);
else
set_Value (COLUMNNAME_WorkStation_ID, WorkStation_ID);
}
@Override
public int getWorkStation_ID()
|
{
return get_ValueAsInt(COLUMNNAME_WorkStation_ID);
}
@Override
public void setYield (final BigDecimal Yield)
{
set_Value (COLUMNNAME_Yield, Yield);
}
@Override
public BigDecimal getYield()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Yield);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order.java
| 1
|
请完成以下Java代码
|
public void setOrderedData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
@Override
public void setDeliveredData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
@Override
public PriceAndTax calculatePriceAndTax(final I_C_Invoice_Candidate ic)
{
throw new UnsupportedOperationException();
}
|
@Override
public void setBPartnerData(final I_C_Invoice_Candidate ic)
{
throw new IllegalStateException("Not supported");
}
@Override
public InvoiceCandidateGenerateResult createCandidatesFor(final InvoiceCandidateGenerateRequest request)
{
throw new IllegalStateException("Not supported");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\invoicecandidate\C_Order_Handler.java
| 1
|
请完成以下Java代码
|
public class BoundaryEventXMLConverter extends BaseBpmnXMLConverter {
public Class<? extends BaseElement> getBpmnElementType() {
return BoundaryEvent.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_EVENT_BOUNDARY;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
BoundaryEvent boundaryEvent = new BoundaryEvent();
BpmnXMLUtil.addXMLLocation(boundaryEvent, xtr);
if (StringUtils.isNotEmpty(xtr.getAttributeValue(null, ATTRIBUTE_BOUNDARY_CANCELACTIVITY))) {
String cancelActivity = xtr.getAttributeValue(null, ATTRIBUTE_BOUNDARY_CANCELACTIVITY);
if (ATTRIBUTE_VALUE_FALSE.equalsIgnoreCase(cancelActivity)) {
boundaryEvent.setCancelActivity(false);
}
}
boundaryEvent.setAttachedToRefId(xtr.getAttributeValue(null, ATTRIBUTE_BOUNDARY_ATTACHEDTOREF));
parseChildElements(getXMLElementName(), boundaryEvent, model, xtr);
// Explicitly set cancel activity to false for error boundary events
if (boundaryEvent.getEventDefinitions().size() == 1) {
EventDefinition eventDef = boundaryEvent.getEventDefinitions().get(0);
if (eventDef instanceof ErrorEventDefinition) {
boundaryEvent.setCancelActivity(false);
}
}
return boundaryEvent;
}
|
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
BoundaryEvent boundaryEvent = (BoundaryEvent) element;
if (boundaryEvent.getAttachedToRef() != null) {
writeDefaultAttribute(ATTRIBUTE_BOUNDARY_ATTACHEDTOREF, boundaryEvent.getAttachedToRef().getId(), xtw);
}
if (boundaryEvent.getEventDefinitions().size() == 1) {
EventDefinition eventDef = boundaryEvent.getEventDefinitions().get(0);
if (eventDef instanceof ErrorEventDefinition == false) {
writeDefaultAttribute(
ATTRIBUTE_BOUNDARY_CANCELACTIVITY,
String.valueOf(boundaryEvent.isCancelActivity()).toLowerCase(),
xtw
);
}
}
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
BoundaryEvent boundaryEvent = (BoundaryEvent) element;
writeEventDefinitions(boundaryEvent, boundaryEvent.getEventDefinitions(), model, xtw);
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\BoundaryEventXMLConverter.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static String removePrecedingZeros(final String str)
{
if (str == null)
{
return null;
}
return str.replaceFirst("^0+(?!$)", "");
}
public static String lpadZero(final String value, final int size)
{
if (value == null)
{
throw new IllegalArgumentException("value is null");
}
final String valueFixed = value.trim();
final String s = "0000000000000000000" + valueFixed;
return s.substring(s.length() - size);
}
public static String mkOwnOrderNumber(final String documentNo)
{
final String sevenDigitString = documentNo.length() <= 7 ? documentNo : documentNo.substring(documentNo.length() - 7);
return "006" + lpadZero(sevenDigitString, 7);
}
/**
* Remove trailing zeros after decimal separator
*
* @return <code>bd</code> without trailing zeros after separator; if argument is NULL then NULL will be retu
*/
// NOTE: this is copy-paste of de.metas.util.NumberUtils.stripTrailingDecimalZeros(BigDecimal)
public static BigDecimal stripTrailingDecimalZeros(final BigDecimal bd)
{
if (bd == null)
{
return null;
}
//
// Remove all trailing zeros
|
BigDecimal result = bd.stripTrailingZeros();
// Fix very weird java 6 bug: stripTrailingZeros doesn't work on 0 itself
// http://stackoverflow.com/questions/5239137/clarification-on-behavior-of-bigdecimal-striptrailingzeroes
if (result.signum() == 0)
{
result = BigDecimal.ZERO;
}
//
// If after removing our scale is negative, we can safely set the scale to ZERO because we don't want to get rid of zeros before decimal point
if (result.scale() < 0)
{
result = result.setScale(0, RoundingMode.UNNECESSARY);
}
return result;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\Util.java
| 2
|
请完成以下Java代码
|
public int getHUCount()
{
final int count = item.getQty().intValueExact();
return count;
}
@Override
public int getHUCapacity()
{
if (X_M_HU_Item.ITEMTYPE_HUAggregate.equals(item.getItemType()))
{
return Quantity.QTY_INFINITE.intValue();
}
return Services.get(IHandlingUnitsBL.class).getPIItem(item).getQty().intValueExact();
}
@Override
public IProductStorage getProductStorage(final ProductId productId, final I_C_UOM uom, final ZonedDateTime date)
{
return new HUItemProductStorage(this, productId, uom, date);
}
@Override
public List<IProductStorage> getProductStorages(final ZonedDateTime date)
{
final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item);
final List<IProductStorage> result = new ArrayList<>(storages.size());
for (final I_M_HU_Item_Storage storage : storages)
{
final ProductId productId = ProductId.ofRepoId(storage.getM_Product_ID());
final I_C_UOM uom = extractUOM(storage);
final HUItemProductStorage productStorage = new HUItemProductStorage(this, productId, uom, date);
result.add(productStorage);
}
return result;
}
private I_C_UOM extractUOM(final I_M_HU_Item_Storage storage)
{
return Services.get(IUOMDAO.class).getById(storage.getC_UOM_ID());
}
@Override
public boolean isEmpty()
{
final List<I_M_HU_Item_Storage> storages = dao.retrieveItemStorages(item);
for (final I_M_HU_Item_Storage storage : storages)
{
|
if (!isEmpty(storage))
{
return false;
}
}
return true;
}
private boolean isEmpty(final I_M_HU_Item_Storage storage)
{
final BigDecimal qty = storage.getQty();
if (qty.signum() != 0)
{
return false;
}
return true;
}
@Override
public boolean isEmpty(final ProductId productId)
{
final I_M_HU_Item_Storage storage = dao.retrieveItemStorage(item, productId);
if (storage == null)
{
return true;
}
return isEmpty(storage);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\HUItemStorage.java
| 1
|
请完成以下Java代码
|
public class NumericSumGatherer implements Gatherer<Integer, ArrayList<Integer>, Integer> {
@Override
public Supplier<ArrayList<Integer>> initializer() {
return ArrayList::new;
}
@Override
public Integrator<ArrayList<Integer>, Integer, Integer> integrator() {
return new Integrator<>() {
@Override
public boolean integrate(ArrayList<Integer> state, Integer element, Downstream<? super Integer> downstream) {
if (state.isEmpty()) {
state.add(element);
} else {
state.addFirst(state.getFirst() + element);
}
|
return true;
}
};
}
@Override
public BiConsumer<ArrayList<Integer>, Downstream<? super Integer>> finisher() {
return (state, downstream) -> {
if (!downstream.isRejecting() && !state.isEmpty()) {
downstream.push(state.getFirst());
state.clear();
}
};
}
}
|
repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\gatherer\NumericSumGatherer.java
| 1
|
请完成以下Java代码
|
public void setC_BP_PrintFormat_ID (final int C_BP_PrintFormat_ID)
{
if (C_BP_PrintFormat_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BP_PrintFormat_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BP_PrintFormat_ID, C_BP_PrintFormat_ID);
}
@Override
public int getC_BP_PrintFormat_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_PrintFormat_ID);
}
@Override
public void setC_DocType_ID (final int C_DocType_ID)
{
if (C_DocType_ID < 0)
set_Value (COLUMNNAME_C_DocType_ID, null);
else
set_Value (COLUMNNAME_C_DocType_ID, C_DocType_ID);
}
@Override
public int getC_DocType_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocType_ID);
|
}
@Override
public void setDocumentCopies_Override (final int DocumentCopies_Override)
{
set_Value (COLUMNNAME_DocumentCopies_Override, DocumentCopies_Override);
}
@Override
public int getDocumentCopies_Override()
{
return get_ValueAsInt(COLUMNNAME_DocumentCopies_Override);
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_PrintFormat.java
| 1
|
请完成以下Java代码
|
public class X_AD_UI_Column extends org.compiere.model.PO implements I_AD_UI_Column, org.compiere.model.I_Persistent
{
/**
*
*/
private static final long serialVersionUID = 191928515L;
/** Standard Constructor */
public X_AD_UI_Column (Properties ctx, int AD_UI_Column_ID, String trxName)
{
super (ctx, AD_UI_Column_ID, trxName);
/** if (AD_UI_Column_ID == 0)
{
setAD_UI_Column_ID (0);
setAD_UI_Section_ID (0);
setSeqNo (0);
// @SQL=SELECT COALESCE(MAX(SeqNo), 0) + 10 FROM AD_UI_Column where AD_UI_Column.AD_UI_Section_ID=@AD_UI_Section_ID@
} */
}
/** Load Constructor */
public X_AD_UI_Column (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 UI Column.
@param AD_UI_Column_ID UI Column */
@Override
public void setAD_UI_Column_ID (int AD_UI_Column_ID)
{
if (AD_UI_Column_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UI_Column_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UI_Column_ID, Integer.valueOf(AD_UI_Column_ID));
}
/** Get UI Column.
@return UI Column */
@Override
public int getAD_UI_Column_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_Column_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_UI_Section getAD_UI_Section() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_UI_Section_ID, org.compiere.model.I_AD_UI_Section.class);
}
@Override
public void setAD_UI_Section(org.compiere.model.I_AD_UI_Section AD_UI_Section)
{
set_ValueFromPO(COLUMNNAME_AD_UI_Section_ID, org.compiere.model.I_AD_UI_Section.class, AD_UI_Section);
}
|
/** Set UI Section.
@param AD_UI_Section_ID UI Section */
@Override
public void setAD_UI_Section_ID (int AD_UI_Section_ID)
{
if (AD_UI_Section_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UI_Section_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UI_Section_ID, Integer.valueOf(AD_UI_Section_ID));
}
/** Get UI Section.
@return UI Section */
@Override
public int getAD_UI_Section_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_Section_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_Column.java
| 1
|
请完成以下Java代码
|
public long getId() {
return id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
|
public String getSocialSecurityCode() {
return socialSecurityCode;
}
public void setSocialSecurityCode(String socialSecurityCode) {
this.socialSecurityCode = socialSecurityCode;
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", socialSecurityCode='" + socialSecurityCode + '\'' +
'}';
}
}
|
repos\springboot-demo-master\rmi\rmi-server\src\main\java\com\et\rmi\server\model\Customer.java
| 1
|
请完成以下Java代码
|
public static class Position
extends RetourePositionType
{
@XmlAttribute(name = "RetourenAnteilTyp", required = true)
protected RetourenAnteilTypType retourenAnteilTyp;
/**
* Gets the value of the retourenAnteilTyp property.
*
* @return
* possible object is
* {@link RetourenAnteilTypType }
*
*/
public RetourenAnteilTypType getRetourenAnteilTyp() {
return retourenAnteilTyp;
}
|
/**
* Sets the value of the retourenAnteilTyp property.
*
* @param value
* allowed object is
* {@link RetourenAnteilTypType }
*
*/
public void setRetourenAnteilTyp(RetourenAnteilTypType value) {
this.retourenAnteilTyp = value;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\RetourenavisAnfrageAntwort.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public abstract class BaseController {
/**
* 获取shiro 的session
*
* @return
*/
protected Session getSession() {
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
return session;
}
/**
* 获取当前用户信息
*
* @return
*/
protected PmsOperator getPmsOperator() {
PmsOperator operator = (PmsOperator) this.getSession().getAttribute("PmsOperator");
return operator;
}
/**
* 响应DWZ的ajax失败请求,跳转到ajaxDone视图.
*
* @param message
* 提示消息.
* @param model
* model.
* @return ajaxDone .
*/
protected String operateError(String message, Model model) {
DwzAjax dwz = new DwzAjax();
dwz.setStatusCode(DWZ.ERROR);
dwz.setMessage(message);
model.addAttribute("dwz", dwz);
return "common/ajaxDone";
|
}
/**
* 响应DWZ的ajax失败成功,跳转到ajaxDone视图.
*
* @param model
* model.
* @param dwz
* 页面传过来的dwz参数
* @return ajaxDone .
*/
protected String operateSuccess(Model model, DwzAjax dwz) {
dwz.setStatusCode(DWZ.SUCCESS);
dwz.setMessage("操作成功");
model.addAttribute("dwz", dwz);
return "common/ajaxDone";
}
}
|
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\controller\common\BaseController.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public Object visitPrimitiveAsLong(PrimitiveType type, Void parameter) {
return 0L;
}
@Override
public Object visitPrimitiveAsChar(PrimitiveType type, Void parameter) {
return null;
}
@Override
public Object visitPrimitiveAsFloat(PrimitiveType type, Void parameter) {
return 0F;
}
@Override
public Object visitPrimitiveAsDouble(PrimitiveType type, Void parameter) {
return 0D;
}
}
/**
* Visitor that gets the default using coercion.
*/
private static final class DefaultValueCoercionTypeVisitor extends TypeKindVisitor8<Object, String> {
static final DefaultValueCoercionTypeVisitor INSTANCE = new DefaultValueCoercionTypeVisitor();
private <T extends Number> T parseNumber(String value, Function<String, T> parser,
PrimitiveType primitiveType) {
try {
return parser.apply(value);
}
catch (NumberFormatException ex) {
throw new IllegalArgumentException(
String.format("Invalid %s representation '%s'", primitiveType, value));
}
}
@Override
public Object visitPrimitiveAsBoolean(PrimitiveType type, String value) {
return Boolean.parseBoolean(value);
}
@Override
public Object visitPrimitiveAsByte(PrimitiveType type, String value) {
return parseNumber(value, Byte::parseByte, type);
}
@Override
public Object visitPrimitiveAsShort(PrimitiveType type, String value) {
return parseNumber(value, Short::parseShort, type);
}
@Override
public Object visitPrimitiveAsInt(PrimitiveType type, String value) {
|
return parseNumber(value, Integer::parseInt, type);
}
@Override
public Object visitPrimitiveAsLong(PrimitiveType type, String value) {
return parseNumber(value, Long::parseLong, type);
}
@Override
public Object visitPrimitiveAsChar(PrimitiveType type, String value) {
if (value.length() > 1) {
throw new IllegalArgumentException(String.format("Invalid character representation '%s'", value));
}
return value;
}
@Override
public Object visitPrimitiveAsFloat(PrimitiveType type, String value) {
return parseNumber(value, Float::parseFloat, type);
}
@Override
public Object visitPrimitiveAsDouble(PrimitiveType type, String value) {
return parseNumber(value, Double::parseDouble, type);
}
}
}
|
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\ParameterPropertyDescriptor.java
| 2
|
请完成以下Java代码
|
public int getM_AttributeSetInstance_ID()
{
return forecastLine.getM_AttributeSetInstance_ID();
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
forecastLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
}
@Override
public int getC_UOM_ID()
{
return forecastLine.getC_UOM_ID();
}
@Override
public void setC_UOM_ID(final int uomId)
{
forecastLine.setC_UOM_ID(uomId);
}
@Override
public void setQty(final BigDecimal qty)
{
forecastLine.setQty(qty);
final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID());
final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID());
final BigDecimal qtyCalculated = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qty);
forecastLine.setQtyCalculated(qtyCalculated);
}
@Override
public BigDecimal getQty()
{
return forecastLine.getQty();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
final int forecastLine_PIItemProductId = forecastLine.getM_HU_PI_Item_Product_ID();
if (forecastLine_PIItemProductId > 0)
{
return forecastLine_PIItemProductId;
}
return -1;
}
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
forecastLine.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
@Override
public BigDecimal getQtyTU()
|
{
return forecastLine.getQtyEnteredTU();
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
forecastLine.setQtyEnteredTU(qtyPacks);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
values.setC_BPartner_ID(partnerId);
}
@Override
public int getC_BPartner_ID()
{
return values.getC_BPartner_ID();
}
@Override
public boolean isInDispute()
{
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\ForecastLineHUPackingAware.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.