instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String username) {
this.email = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Collection<Role> getRoles() {
return roles;
}
public void setRoles(Collection<Role> roles) {
this.roles = roles;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isUsing2FA() {
return isUsing2FA;
}
|
public void setUsing2FA(boolean isUsing2FA) {
this.isUsing2FA = isUsing2FA;
}
@Override
public int hashCode() {
int prime = 31;
int result = 1;
result = (prime * result) + ((email == null) ? 0 : email.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
User user = (User) obj;
if (!email.equals(user.email)) {
return false;
}
return true;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("User [id=").append(id).append(", firstName=")
.append(firstName).append(", lastName=").append(lastName).append(", email=").append(email).append(", password=").append(password).append(", enabled=").append(enabled).append(", roles=").append(roles).append("]");
return builder.toString();
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\rolesauthorities\model\User.java
| 1
|
请完成以下Java代码
|
public boolean hasInactive()
{
return false;
}
/**
* Get Zoom - default implementation
* @return Zoom AD_Window_ID
*/
public AdWindowId getZoom()
{
return null;
} // getZoom
/**
* Get Zoom - default implementation
* @param query query
* @return Zoom Window - here 0
*/
public AdWindowId getZoomAD_Window_ID(MQuery query)
{
return null;
} // getZoom
/**
* Get Zoom Query String - default implementation
* @return Zoom Query
*/
public MQuery getZoomQuery()
{
return null;
} // getZoomQuery
/**
* Get Data Direct from Table. Default implementation - does not requery
*
* @param evalCtx evaluation context to be used
* @param key key
* @param saveInCache save in cache for r/w
* @param cacheLocal cache locally for r/o
* @return value
*/
public NamePair getDirect(final IValidationContext evalCtx, Object key, boolean saveInCache, boolean cacheLocal)
{
return get(evalCtx, key);
} // getDirect
/**
* Dispose - clear items w/o firing events
*/
public void dispose()
{
if (p_data != null)
{
p_data.clear();
}
p_data = null;
m_selectedObject = null;
m_tempData = null;
m_loaded = false;
} // dispose
/**
* Wait until async Load Complete
*/
public void loadComplete()
{
} // loadComplete
/**
* Set lookup model as mandatory, use in loading data
* @param flag
*/
public void setMandatory(boolean flag)
{
m_mandatory = flag;
}
/**
* Is lookup model mandatory
* @return boolean
*/
public boolean isMandatory()
{
return m_mandatory;
}
/**
|
* Is this lookup model populated
* @return boolean
*/
public boolean isLoaded()
{
return m_loaded;
}
/**
* Returns a list of parameters on which this lookup depends.
*
* Those parameters will be fetched from context on validation time.
*
* @return list of parameter names
*/
public Set<String> getParameters()
{
return ImmutableSet.of();
}
/**
*
* @return evaluation context
*/
public IValidationContext getValidationContext()
{
return IValidationContext.NULL;
}
/**
* Suggests a valid value for given value
*
* @param value
* @return equivalent valid value or same this value is valid; if there are no suggestions, null will be returned
*/
public NamePair suggestValidValue(final NamePair value)
{
return null;
}
/**
* Returns true if given <code>display</code> value was rendered for a not found item.
* To be used together with {@link #getDisplay} methods.
*
* @param display
* @return true if <code>display</code> contains not found markers
*/
public boolean isNotFoundDisplayValue(String display)
{
return false;
}
} // Lookup
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\Lookup.java
| 1
|
请完成以下Java代码
|
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getOrgCategory() {
return orgCategory;
}
public void setOrgCategory(String orgCategory) {
this.orgCategory = orgCategory;
}
public String getOrgType() {
return orgType;
}
public void setOrgType(String orgType) {
this.orgType = orgType;
}
public String getOrgCode() {
return orgCode;
}
public void setOrgCode(String orgCode) {
this.orgCode = orgCode;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getFax() {
return fax;
|
}
public void setFax(String fax) {
this.fax = fax;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMemo() {
return memo;
}
public void setMemo(String memo) {
this.memo = memo;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\system\vo\SysDepartModel.java
| 1
|
请完成以下Spring Boot application配置
|
spring.redis.database=0
spring.redis.host=localhost
spring.redis.port=16379
spring.redis.password=mypass
spring.redis.timeout=60000
spring.redis.lettuce.pool.max-active=8
spring.redis.lettuce.pool.
|
max-idle=8
spring.redis.lettuce.pool.max-wait=-1
spring.redis.lettuce.pool.min-idle=0
|
repos\tutorials-master\persistence-modules\redis\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
private ImpDataCell parseDataCell(final String line, final ImpFormatColumn column)
{
try
{
final String rawValue = extractCellRawValue(line, column);
final Object value = column.parseCellValue(rawValue);
return ImpDataCell.value(value);
}
catch (final Exception ex)
{
return ImpDataCell.error(ErrorMessage.of(ex));
}
}
private static String extractCellRawValue(final String line, final ImpFormatColumn impFormatColumn)
{
if (impFormatColumn.isConstant())
{
return impFormatColumn.getConstantValue();
|
}
else
{
// check length
if (impFormatColumn.getStartNo() > 0 && impFormatColumn.getEndNo() <= line.length())
{
return line.substring(impFormatColumn.getStartNo() - 1, impFormatColumn.getEndNo());
}
else
{
return null;
}
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\FixedPositionImpDataLineParser.java
| 1
|
请完成以下Java代码
|
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get Ansprechpartner.
@return User within the system - Internal or Business Partner Contact
*/
@Override
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_UserGroup getAD_UserGroup() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_UserGroup_ID, org.compiere.model.I_AD_UserGroup.class);
}
@Override
public void setAD_UserGroup(org.compiere.model.I_AD_UserGroup AD_UserGroup)
{
set_ValueFromPO(COLUMNNAME_AD_UserGroup_ID, org.compiere.model.I_AD_UserGroup.class, AD_UserGroup);
}
/** Set Nutzergruppe.
@param AD_UserGroup_ID Nutzergruppe */
@Override
public void setAD_UserGroup_ID (int AD_UserGroup_ID)
{
if (AD_UserGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UserGroup_ID, Integer.valueOf(AD_UserGroup_ID));
}
/** Get Nutzergruppe.
@return Nutzergruppe */
@Override
public int getAD_UserGroup_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UserGroup_ID);
if (ii == null)
return 0;
return ii.intValue();
|
}
/** Set Datensatz-ID.
@param Record_ID
Direct internal record ID
*/
@Override
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Datensatz-ID.
@return Direct internal record ID
*/
@Override
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Private_Access.java
| 1
|
请完成以下Java代码
|
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Method of ordering records; lowest number comes first
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Max. Wert.
@param ValueMax
Maximum Value for a field
*/
@Override
public void setValueMax (java.lang.String ValueMax)
{
set_Value (COLUMNNAME_ValueMax, ValueMax);
}
/** Get Max. Wert.
@return Maximum Value for a field
*/
@Override
public java.lang.String getValueMax ()
{
return (java.lang.String)get_Value(COLUMNNAME_ValueMax);
}
/** Set Min. Wert.
@param ValueMin
Minimum Value for a field
*/
@Override
public void setValueMin (java.lang.String ValueMin)
{
set_Value (COLUMNNAME_ValueMin, ValueMin);
}
/** Get Min. Wert.
@return Minimum Value for a field
|
*/
@Override
public java.lang.String getValueMin ()
{
return (java.lang.String)get_Value(COLUMNNAME_ValueMin);
}
/** Set Value Format.
@param VFormat
Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
@Override
public void setVFormat (java.lang.String VFormat)
{
set_Value (COLUMNNAME_VFormat, VFormat);
}
/** Get Value Format.
@return Format of the value; Can contain fixed format elements, Variables: "_lLoOaAcCa09"
*/
@Override
public java.lang.String getVFormat ()
{
return (java.lang.String)get_Value(COLUMNNAME_VFormat);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Process_Para.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class WarehouseTypeId implements RepoIdAware
{
int repoId;
@JsonCreator
public static WarehouseTypeId ofRepoId(final int repoId)
{
return new WarehouseTypeId(repoId);
}
@Nullable
public static WarehouseTypeId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new WarehouseTypeId(repoId) : null;
}
public static Optional<WarehouseTypeId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
|
public static int toRepoId(@Nullable final WarehouseTypeId id)
{
return id != null ? id.getRepoId() : -1;
}
private WarehouseTypeId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\WarehouseTypeId.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
private Set<String> getAssociatedUrls(String baseUrl) {
URI url = new URI(baseUrl);
return Arrays.stream(InetAddress.getAllByName(url.getHost()))
.map(InetAddress::getHostAddress)
.map(ip -> {
try {
return new URI(url.getScheme(), null, ip, url.getPort(), "", null, null).toString();
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.toSet());
}
private List<String> getTestTelemetryKeys() {
return checkCalculatedFields ? List.of(TEST_TELEMETRY_KEY, TEST_CF_TELEMETRY_KEY) : List.of(TEST_TELEMETRY_KEY);
|
}
private void stopHealthChecker(BaseHealthChecker<C, T> healthChecker) throws Exception {
healthChecker.destroyClient();
devices.remove(healthChecker.getTarget().getDeviceId());
log.info("Stopped {} for {}", healthChecker.getClass().getSimpleName(), healthChecker.getTarget().getBaseUrl());
}
protected abstract BaseHealthChecker<?, ?> createHealthChecker(C config, T target);
protected abstract T createTarget(String baseUrl);
protected abstract String getName();
}
|
repos\thingsboard-master\monitoring\src\main\java\org\thingsboard\monitoring\service\BaseMonitoringService.java
| 2
|
请完成以下Java代码
|
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getTweet() {
return tweet;
}
public void setTweet(String tweet) {
this.tweet = tweet;
}
|
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
public Set<String> getLikes() {
return likes;
}
public void setLikes(Set<String> likes) {
this.likes = likes;
}
}
|
repos\tutorials-master\spring-security-modules\spring-security-web-boot-3\src\main\java\com\baeldung\relationships\models\Tweet.java
| 1
|
请完成以下Java代码
|
public class Client {
private final ClientId id;
private final String firstName;
private final String lastName;
private final Account account;
@JsonCreator
public Client(@JsonProperty("id") ClientId id,
@JsonProperty("firstName") String firstName,
@JsonProperty("lastName") String lastName,
@JsonProperty("account") Account account) {
this.id = id;
this.firstName = firstName;
this.lastName = lastName;
this.account = account;
}
public ClientId getId() {
return id;
|
}
public String getFirstName() {
return firstName;
}
public String getLastName() {
return lastName;
}
public Account getAccount() {
return account;
}
}
|
repos\spring-examples-java-17\spring-bank\bank-common\src\main\java\itx\examples\springbank\common\dto\Client.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ScheduledExecutorServiceDemo {
private Task runnableTask;
private CallableTask callableTask;
private void execute() {
ScheduledExecutorService executorService = Executors.newSingleThreadScheduledExecutor();
getTasksToRun().apply(executorService);
executorService.shutdown();
}
private void executeWithMultiThread() {
ScheduledExecutorService executorService = Executors.newScheduledThreadPool(2);
getTasksToRun().apply(executorService);
executorService.shutdown();
}
private Function<ScheduledExecutorService, Void> getTasksToRun() {
runnableTask = new Task();
callableTask = new CallableTask();
|
return (executorService -> {
Future<String> resultFuture = executorService.schedule(callableTask, 1, TimeUnit.SECONDS);
executorService.scheduleAtFixedRate( runnableTask, 100, 450, TimeUnit.SECONDS);
executorService.scheduleWithFixedDelay( runnableTask, 100, 150, TimeUnit.SECONDS);
return null;
});
}
public static void main(String... args) {
ScheduledExecutorServiceDemo demo = new ScheduledExecutorServiceDemo();
demo.execute();
demo.executeWithMultiThread();
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-basic\src\main\java\com\baeldung\concurrent\executorservice\ScheduledExecutorServiceDemo.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public TaxCategoryProvider getTaxCategoryProvider(@NonNull final JsonExternalSystemRequest request)
{
return TaxCategoryProvider.builder()
.normalRates(request.getParameters().get(ExternalSystemConstants.PARAM_NORMAL_VAT_RATES))
.reducedRates(request.getParameters().get(ExternalSystemConstants.PARAM_REDUCED_VAT_RATES))
.build();
}
@Nullable
public PriceListBasicInfo getTargetPriceListInfo(@NonNull final JsonExternalSystemRequest request)
{
final String targetPriceListIdStr = request.getParameters().get(ExternalSystemConstants.PARAM_TARGET_PRICE_LIST_ID);
if (Check.isBlank(targetPriceListIdStr))
{
return null;
}
final JsonMetasfreshId priceListId = JsonMetasfreshId.of(Integer.parseInt(targetPriceListIdStr));
final PriceListBasicInfo.PriceListBasicInfoBuilder targetPriceListInfoBuilder = PriceListBasicInfo.builder();
targetPriceListInfoBuilder.priceListId(priceListId);
|
final String isTaxIncluded = request.getParameters().get(ExternalSystemConstants.PARAM_IS_TAX_INCLUDED);
if (isTaxIncluded == null)
{
throw new RuntimeCamelException("isTaxIncluded is missing although priceListId is specified, targetPriceListId: " + priceListId);
}
targetPriceListInfoBuilder.isTaxIncluded(Boolean.parseBoolean(isTaxIncluded));
final String targetCurrencyCode = request.getParameters().get(ExternalSystemConstants.PARAM_PRICE_LIST_CURRENCY_CODE);
if (targetCurrencyCode == null)
{
throw new RuntimeCamelException("targetCurrencyCode param is missing although priceListId is specified, targetPriceListId: " + priceListId);
}
targetPriceListInfoBuilder.currencyCode(targetCurrencyCode);
return targetPriceListInfoBuilder.build();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\product\GetProductsRouteHelper.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public List<DPRIC1> getDPRIC1() {
if (dpric1 == null) {
dpric1 = new ArrayList<DPRIC1>();
}
return this.dpric1;
}
/**
* Gets the value of the drefe1 property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the drefe1 property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDREFE1().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DREFE1 }
*
*
*/
public List<DREFE1> getDREFE1() {
if (drefe1 == null) {
drefe1 = new ArrayList<DREFE1>();
}
return this.drefe1;
}
/**
* Gets the value of the dtaxi1 property.
*
* @return
* possible object is
* {@link DTAXI1 }
*
*/
public DTAXI1 getDTAXI1() {
return dtaxi1;
|
}
/**
* Sets the value of the dtaxi1 property.
*
* @param value
* allowed object is
* {@link DTAXI1 }
*
*/
public void setDTAXI1(DTAXI1 value) {
this.dtaxi1 = value;
}
/**
* Gets the value of the dalch1 property.
*
* <p>
* This accessor method returns a reference to the live list,
* not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object.
* This is why there is not a <CODE>set</CODE> method for the dalch1 property.
*
* <p>
* For example, to add a new item, do as follows:
* <pre>
* getDALCH1().add(newItem);
* </pre>
*
*
* <p>
* Objects of the following type(s) are allowed in the list
* {@link DALCH1 }
*
*
*/
public List<DALCH1> getDALCH1() {
if (dalch1 == null) {
dalch1 = new ArrayList<DALCH1>();
}
return this.dalch1;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_invoic\de\metas\edi\esb\jaxb\stepcom\invoic\DETAILXrech.java
| 2
|
请完成以下Java代码
|
public int getRecord_ID()
{
return Record_ID;
}
public void setRecord_ID(int record_ID)
{
Record_ID = record_ID;
}
@Override
public List<I_C_DunningLevel> getC_DunningLevels()
{
return C_DunningLevels;
}
public void setC_DunningLevels(List<I_C_DunningLevel> c_DunningLevels)
{
C_DunningLevels = c_DunningLevels;
}
@Override
public boolean isActive()
{
return active;
}
public void setActive(boolean active)
{
this.active = active;
}
@Override
public boolean isApplyClientSecurity()
{
return applyClientSecurity;
}
public void setApplyClientSecurity(boolean applyClientSecurity)
{
this.applyClientSecurity = applyClientSecurity;
}
@Override
public Boolean getProcessed()
{
return processed;
}
public void setProcessed(Boolean processed)
{
this.processed = processed;
}
@Override
public Boolean getWriteOff()
|
{
return writeOff;
}
public void setWriteOff(Boolean writeOff)
{
this.writeOff = writeOff;
}
@Override
public String getAdditionalWhere()
{
return additionalWhere;
}
public void setAdditionalWhere(String additionalWhere)
{
this.additionalWhere = additionalWhere;
}
@Override
public ApplyAccessFilter getApplyAccessFilter()
{
return applyAccessFilter;
}
public void setApplyAccessFilter(ApplyAccessFilter applyAccessFilter)
{
this.applyAccessFilter = applyAccessFilter;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\api\impl\DunningCandidateQuery.java
| 1
|
请完成以下Java代码
|
public String getFieldValueFormat ()
{
return (String)get_Value(COLUMNNAME_FieldValueFormat);
}
/** Set Null Value.
@param IsNullFieldValue Null Value */
public void setIsNullFieldValue (boolean IsNullFieldValue)
{
set_Value (COLUMNNAME_IsNullFieldValue, Boolean.valueOf(IsNullFieldValue));
}
/** Get Null Value.
@return Null Value */
public boolean isNullFieldValue ()
{
Object oo = get_Value(COLUMNNAME_IsNullFieldValue);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Eintraege; die kleinste Zahl kommt zuerst
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
|
/** Type AD_Reference_ID=540203 */
public static final int TYPE_AD_Reference_ID=540203;
/** Set Field Value = SV */
public static final String TYPE_SetFieldValue = "SV";
/** Set Art.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
public void setType (String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Type of Validation (SQL, Java Script, Java Language)
*/
public String getType ()
{
return (String)get_Value(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_AD_TriggerUI_Action.java
| 1
|
请完成以下Java代码
|
public void updateNoPriceConditionsColor(@NonNull final I_C_OrderLine orderLine)
{
final HasPricingConditions hasPricingConditions = hasPricingConditions(orderLine);
final ColorId colorId = getColorId(hasPricingConditions);
orderLine.setNoPriceConditionsColor_ID(ColorId.toRepoId(colorId));
}
@Nullable
private ColorId getColorId(final HasPricingConditions hasPricingConditions)
{
if (hasPricingConditions == HasPricingConditions.YES)
{
return null;
}
else if (hasPricingConditions == HasPricingConditions.TEMPORARY)
{
return getTemporaryPriceConditionsColorId();
}
else if (hasPricingConditions == HasPricingConditions.NO)
{
return getNoPriceConditionsColorId();
}
else
{
throw new AdempiereException("Unknown " + HasPricingConditions.class + ": " + hasPricingConditions);
}
}
@Override
public ColorId getTemporaryPriceConditionsColorId()
{
return getColorIdBySysConfig(SYSCONFIG_TemporaryPriceConditionsColorName);
}
private ColorId getNoPriceConditionsColorId()
{
return getColorIdBySysConfig(SYSCONFIG_NoPriceConditionsColorName);
}
@Nullable
private ColorId getColorIdBySysConfig(final String sysConfigName)
{
final String colorName = Services.get(ISysConfigBL.class).getValue(sysConfigName, "-");
if (Check.isEmpty(colorName) || "-".equals(colorName))
{
return null;
}
return Services.get(IColorRepository.class).getColorIdByName(colorName);
}
@Override
public void failForMissingPricingConditions(final de.metas.adempiere.model.I_C_Order order)
{
final boolean mandatoryPricingConditions = isMandatoryPricingConditions();
if (!mandatoryPricingConditions)
{
return;
}
final List<I_C_OrderLine> orderLines = Services.get(IOrderDAO.class).retrieveOrderLines(order);
final boolean existsOrderLineWithNoPricingConditions = orderLines
.stream()
.anyMatch(this::isPricingConditionsMissingButRequired);
if (existsOrderLineWithNoPricingConditions)
{
throw new AdempiereException(MSG_NoPricingConditionsError)
.setParameter("HowToDisablePricingConditionsCheck", "To disable it, please set " + SYSCONFIG_NoPriceConditionsColorName + " to `-`");
|
}
}
private boolean isMandatoryPricingConditions()
{
final ColorId noPriceConditionsColorId = getNoPriceConditionsColorId();
return noPriceConditionsColorId != null;
}
private boolean isPricingConditionsMissingButRequired(final I_C_OrderLine orderLine)
{
// Pricing conditions are not required for packing material line (task 3925)
if (orderLine.isPackagingMaterial())
{
return false;
}
return hasPricingConditions(orderLine) == HasPricingConditions.NO;
}
private HasPricingConditions hasPricingConditions(final I_C_OrderLine orderLine)
{
if (orderLine.isTempPricingConditions())
{
return HasPricingConditions.TEMPORARY;
}
else if (orderLine.getM_DiscountSchemaBreak_ID() > 0)
{
return HasPricingConditions.YES;
}
else
{
return HasPricingConditions.NO;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderLinePricingConditions.java
| 1
|
请完成以下Java代码
|
public Predicate toPredicate(final Root<T> root, final CriteriaQuery<?> query, final CriteriaBuilder builder) {
final List<Object> args = castArguments(root);
final Object argument = args.get(0);
switch (RsqlSearchOperation.getSimpleOperator(operator)) {
case EQUAL: {
if (argument instanceof String) {
return builder.like(root.get(property), argument.toString().replace('*', '%'));
} else if (argument == null) {
return builder.isNull(root.get(property));
} else {
return builder.equal(root.get(property), argument);
}
}
case NOT_EQUAL: {
if (argument instanceof String) {
return builder.notLike(root.<String> get(property), argument.toString().replace('*', '%'));
} else if (argument == null) {
return builder.isNotNull(root.get(property));
} else {
return builder.notEqual(root.get(property), argument);
}
}
case GREATER_THAN: {
return builder.greaterThan(root.<String> get(property), argument.toString());
}
case GREATER_THAN_OR_EQUAL: {
return builder.greaterThanOrEqualTo(root.<String> get(property), argument.toString());
}
case LESS_THAN: {
return builder.lessThan(root.<String> get(property), argument.toString());
}
case LESS_THAN_OR_EQUAL: {
return builder.lessThanOrEqualTo(root.<String> get(property), argument.toString());
}
case IN:
return root.get(property).in(args);
case NOT_IN:
return builder.not(root.get(property).in(args));
}
return null;
}
|
// === private
private List<Object> castArguments(final Root<T> root) {
final Class<? extends Object> type = root.get(property).getJavaType();
final List<Object> args = arguments.stream().map(arg -> {
if (type.equals(Integer.class)) {
return Integer.parseInt(arg);
} else if (type.equals(Long.class)) {
return Long.parseLong(arg);
} else {
return arg;
}
}).collect(Collectors.toList());
return args;
}
}
|
repos\tutorials-master\spring-web-modules\spring-rest-query-language\src\main\java\com\baeldung\persistence\dao\rsql\GenericRsqlSpecification.java
| 1
|
请完成以下Java代码
|
protected void prepare()
{
ProcessInfoParameter[] para = getParametersAsArray();
for (int i = 0; i < para.length; i++)
{
String name = para[i].getParameterName();
if (para[i].getParameter() == null)
;
else if (name.equals("C_Order_ID"))
p_C_Order_ID = ((BigDecimal)para[i].getParameter()).intValue();
else
log.error("Unknown Parameter: " + name);
}
} // prepare
/**
* Perform process.
* @return Message (clear text)
* @throws Exception if not successful
*/
protected String doIt() throws Exception
|
{
int To_C_Order_ID = getRecord_ID();
log.info("From C_Order_ID=" + p_C_Order_ID + " to " + To_C_Order_ID);
if (To_C_Order_ID == 0)
throw new IllegalArgumentException("Target C_Order_ID == 0");
if (p_C_Order_ID == 0)
throw new IllegalArgumentException("Source C_Order_ID == 0");
MOrder from = new MOrder (getCtx(), p_C_Order_ID, get_TrxName());
MOrder to = new MOrder (getCtx(), To_C_Order_ID, get_TrxName());
//
int no = to.copyLinesFrom (from, false, false); // no Attributes
//
return "@Copied@=" + no;
} // doIt
} // CopyFromOrder
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\CopyFromOrder.java
| 1
|
请完成以下Java代码
|
public class SmsFlashPromotionProductRelation implements Serializable {
@ApiModelProperty(value = "编号")
private Long id;
private Long flashPromotionId;
@ApiModelProperty(value = "编号")
private Long flashPromotionSessionId;
private Long productId;
@ApiModelProperty(value = "限时购价格")
private BigDecimal flashPromotionPrice;
@ApiModelProperty(value = "限时购数量")
private Integer flashPromotionCount;
@ApiModelProperty(value = "每人限购数量")
private Integer flashPromotionLimit;
@ApiModelProperty(value = "排序")
private Integer sort;
private static final long serialVersionUID = 1L;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getFlashPromotionId() {
return flashPromotionId;
}
public void setFlashPromotionId(Long flashPromotionId) {
this.flashPromotionId = flashPromotionId;
}
public Long getFlashPromotionSessionId() {
return flashPromotionSessionId;
}
public void setFlashPromotionSessionId(Long flashPromotionSessionId) {
this.flashPromotionSessionId = flashPromotionSessionId;
}
public Long getProductId() {
return productId;
}
public void setProductId(Long productId) {
this.productId = productId;
}
public BigDecimal getFlashPromotionPrice() {
return flashPromotionPrice;
}
|
public void setFlashPromotionPrice(BigDecimal flashPromotionPrice) {
this.flashPromotionPrice = flashPromotionPrice;
}
public Integer getFlashPromotionCount() {
return flashPromotionCount;
}
public void setFlashPromotionCount(Integer flashPromotionCount) {
this.flashPromotionCount = flashPromotionCount;
}
public Integer getFlashPromotionLimit() {
return flashPromotionLimit;
}
public void setFlashPromotionLimit(Integer flashPromotionLimit) {
this.flashPromotionLimit = flashPromotionLimit;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", flashPromotionId=").append(flashPromotionId);
sb.append(", flashPromotionSessionId=").append(flashPromotionSessionId);
sb.append(", productId=").append(productId);
sb.append(", flashPromotionPrice=").append(flashPromotionPrice);
sb.append(", flashPromotionCount=").append(flashPromotionCount);
sb.append(", flashPromotionLimit=").append(flashPromotionLimit);
sb.append(", sort=").append(sort);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsFlashPromotionProductRelation.java
| 1
|
请完成以下Java代码
|
public byte[] serialize(String topic, Headers headers, Object data) {
if (data == null) {
return null;
}
Serializer<Object> delegate = findDelegate(data);
return delegate.serialize(topic, headers, data);
}
protected <T> Serializer<T> findDelegate(T data) {
return findDelegate(data, this.delegates);
}
/**
* Determine the serializer for the data type.
* @param data the data.
* @param delegates the available delegates.
* @param <T> the data type
* @return the delegate.
* @throws SerializationException when there is no match.
* @since 2.8.3
*/
@SuppressWarnings("unchecked")
protected <T> Serializer<T> findDelegate(T data, Map<Class<?>, Serializer<?>> delegates) {
if (!this.assignable) {
Serializer<?> delegate = delegates.get(data.getClass());
if (delegate == null) {
|
throw new SerializationException("No matching delegate for type: " + data.getClass().getName()
+ "; supported types: " + delegates.keySet().stream()
.map(Class::getName)
.toList());
}
return (Serializer<T>) delegate;
}
else {
for (Entry<Class<?>, Serializer<?>> entry : delegates.entrySet()) {
if (entry.getKey().isAssignableFrom(data.getClass())) {
return (Serializer<T>) entry.getValue();
}
}
throw new SerializationException("No matching delegate for type: " + data.getClass().getName()
+ "; supported types: " + delegates.keySet().stream()
.map(Class::getName)
.toList());
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\DelegatingByTypeSerializer.java
| 1
|
请完成以下Java代码
|
private int getNext(int parent, int charPoint)
{
int startChar = charPoint + 1;
int baseParent = getBase(parent);
int from = parent;
for (int i = startChar; i < charMap.getCharsetSize(); i++)
{
int to = baseParent + i;
if (check.size() > to && check.get(to) == from)
{
path.append(i);
from = to;
path.append(from);
baseParent = base.get(from);
if (getCheck(baseParent + UNUSED_CHAR_VALUE) == from)
{
value = getLeafValue(getBase(baseParent + UNUSED_CHAR_VALUE));
int[] ids = new int[path.size() / 2];
for (int k = 0, j = 1; j < path.size(); ++k, j += 2)
{
ids[k] = path.get(j);
}
|
key = charMap.toString(ids);
path.append(UNUSED_CHAR_VALUE);
currentBase = baseParent;
return from;
}
else
{
return getNext(from, 0);
}
}
}
return -1;
}
@Override
public String toString()
{
return key + '=' + value;
}
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\MutableDoubleArrayTrieInteger.java
| 1
|
请完成以下Java代码
|
public java.lang.String getSMTPHost()
{
return get_ValueAsString(COLUMNNAME_SMTPHost);
}
@Override
public void setSMTPPort (final int SMTPPort)
{
set_Value (COLUMNNAME_SMTPPort, SMTPPort);
}
@Override
public int getSMTPPort()
{
return get_ValueAsInt(COLUMNNAME_SMTPPort);
}
/**
* Type AD_Reference_ID=541904
* Reference name: AD_MailBox_Type
*/
public static final int TYPE_AD_Reference_ID=541904;
/** SMTP = smtp */
public static final String TYPE_SMTP = "smtp";
/** MSGraph = msgraph */
public static final String TYPE_MSGraph = "msgraph";
@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 setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_MailBox.java
| 1
|
请完成以下Java代码
|
public Integer getLevel() {
return level;
}
public void setLevel(Integer level) {
this.level = level;
}
public Integer getSort() {
return sort;
}
public void setSort(Integer sort) {
this.sort = sort;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getIcon() {
return icon;
}
public void setIcon(String icon) {
this.icon = icon;
}
public Integer getHidden() {
|
return hidden;
}
public void setHidden(Integer hidden) {
this.hidden = hidden;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", parentId=").append(parentId);
sb.append(", createTime=").append(createTime);
sb.append(", title=").append(title);
sb.append(", level=").append(level);
sb.append(", sort=").append(sort);
sb.append(", name=").append(name);
sb.append(", icon=").append(icon);
sb.append(", hidden=").append(hidden);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
}
|
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMenu.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class UserId {
private final String id;
@JsonCreator
public UserId(@JsonProperty("id") String id) {
this.id = id;
}
public String getId() {
return id;
}
public static UserId from(String id) {
return new UserId(id);
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserId userId = (UserId) o;
return Objects.equals(id, userId.id);
|
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@Override
public String toString() {
return "UserId{" +
"id='" + id + '\'' +
'}';
}
}
|
repos\spring-examples-java-17\spring-security\src\main\java\itx\examples\springboot\security\springsecurity\services\dto\UserId.java
| 2
|
请完成以下Java代码
|
public static Set<DocStatus> completedOrClosedStatuses()
{
return COMPLETED_OR_CLOSED_STATUSES;
}
public boolean isCompletedOrClosedOrReversed()
{
return this == Completed
|| this == Closed
|| this == Reversed;
}
public boolean isCompletedOrClosedReversedOrVoided()
{
return this == Completed
|| this == Closed
|| this == Reversed
|| this == Voided;
}
public boolean isWaitingForPayment()
{
return this == WaitingPayment;
}
public boolean isInProgress()
{
return this == InProgress;
}
public boolean isInProgressCompletedOrClosed()
{
return this == InProgress
|| this == Completed
|| this == Closed;
}
public boolean isDraftedInProgressOrInvalid()
|
{
return this == Drafted
|| this == InProgress
|| this == Invalid;
}
@SuppressWarnings("BooleanMethodIsAlwaysInverted")
public boolean isDraftedInProgressOrCompleted()
{
return this == Drafted
|| this == InProgress
|| this == Completed;
}
public boolean isNotProcessed()
{
return isDraftedInProgressOrInvalid()
|| this == Approved
|| this == NotApproved;
}
public boolean isVoided() {return this == Voided;}
public boolean isAccountable()
{
return this == Completed
|| this == Reversed
|| this == Voided;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\engine\DocStatus.java
| 1
|
请完成以下Java代码
|
public void setGrandTotal (java.math.BigDecimal GrandTotal)
{
set_Value (COLUMNNAME_GrandTotal, GrandTotal);
}
/** Get Summe Gesamt.
@return Summe über Alles zu diesem Beleg
*/
@Override
public java.math.BigDecimal getGrandTotal ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrandTotal);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set In Dispute.
@param IsInDispute
Document is in dispute
*/
@Override
public void setIsInDispute (boolean IsInDispute)
{
set_Value (COLUMNNAME_IsInDispute, Boolean.valueOf(IsInDispute));
}
/** Get In Dispute.
@return Document is in dispute
*/
@Override
public boolean isInDispute ()
{
Object oo = get_Value(COLUMNNAME_IsInDispute);
if (oo != null)
{
|
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Offener Betrag.
@param OpenAmt Offener Betrag */
@Override
public void setOpenAmt (java.math.BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Offener Betrag.
@return Offener Betrag */
@Override
public java.math.BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java-gen\de\metas\dunning\model\X_C_Dunning_Candidate_Invoice_v1.java
| 1
|
请完成以下Java代码
|
public static String constructBaseUrl(HttpServletRequest request) {
return String.format("%s://%s:%d",
getScheme(request),
getDomainName(request),
getPort(request));
}
public static String getScheme(HttpServletRequest request){
String scheme = request.getScheme();
String forwardedProto = request.getHeader("x-forwarded-proto");
if (forwardedProto != null) {
scheme = forwardedProto;
}
return scheme;
}
public static String getDomainName(HttpServletRequest request){
return request.getServerName();
}
public static String getDomainNameAndPort(HttpServletRequest request){
String domainName = getDomainName(request);
String scheme = getScheme(request);
int port = MiscUtils.getPort(request);
if (needsPort(scheme, port)) {
domainName += ":" + port;
}
return domainName;
}
private static boolean needsPort(String scheme, int port) {
boolean isHttpDefault = "http".equals(scheme.toLowerCase()) && port == 80;
boolean isHttpsDefault = "https".equals(scheme.toLowerCase()) && port == 443;
return !isHttpDefault && !isHttpsDefault;
}
|
public static int getPort(HttpServletRequest request){
String forwardedProto = request.getHeader("x-forwarded-proto");
int serverPort = request.getServerPort();
if (request.getHeader("x-forwarded-port") != null) {
try {
serverPort = request.getIntHeader("x-forwarded-port");
} catch (NumberFormatException e) {
}
} else if (forwardedProto != null) {
switch (forwardedProto) {
case "http":
serverPort = 80;
break;
case "https":
serverPort = 443;
break;
}
}
return serverPort;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\utils\MiscUtils.java
| 1
|
请完成以下Java代码
|
public ImmutableList<I_M_ShipmentSchedule> getByReferences(@NonNull final ImmutableList<TableRecordReference> recordRefs)
{
final IQueryBuilder<I_M_ShipmentSchedule> queryBuilder = queryBL
.createQueryBuilder(I_M_ShipmentSchedule.class)
.setJoinOr()
.setOption(IQueryBuilder.OPTION_Explode_OR_Joins_To_SQL_Unions, true);
for (final TableRecordReference recordRef : recordRefs)
{
final ICompositeQueryFilter<I_M_ShipmentSchedule> filter = queryBL.createCompositeQueryFilter(I_M_ShipmentSchedule.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_ShipmentSchedule.COLUMNNAME_AD_Table_ID, recordRef.getAD_Table_ID())
.addEqualsFilter(I_M_ShipmentSchedule.COLUMN_Record_ID, recordRef.getRecord_ID());
queryBuilder.filter(filter);
}
return queryBuilder
.create()
.listImmutable(I_M_ShipmentSchedule.class);
}
@Override
public ImmutableSet<ShipmentScheduleId> retrieveScheduleIdsByOrderId(@NonNull final OrderId orderId)
{
return queryBL
|
.createQueryBuilder(I_M_ShipmentSchedule.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_M_ShipmentSchedule.COLUMN_C_Order_ID, orderId)
.create()
.idsAsSet(ShipmentScheduleId::ofRepoId);
}
@Override
public <T extends I_M_ShipmentSchedule> Map<ShipmentScheduleId, T> getByIds(@NonNull final Set<ShipmentScheduleId> ids, @NonNull final Class<T> clazz)
{
if (ids.isEmpty()) {return ImmutableMap.of();}
return queryBL.createQueryBuilder(I_M_ShipmentSchedule.class)
.addInArrayFilter(I_M_ShipmentSchedule.COLUMNNAME_M_ShipmentSchedule_ID, ids)
.create()
.mapByRepoIdAware(ShipmentScheduleId::ofRepoId, clazz);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\ShipmentSchedulePA.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getAssignee() {
return assignee;
}
@ApiModelProperty(value = "Required when completing a task with a form", example = "12345")
public String getFormDefinitionId() {
return formDefinitionId;
}
public void setFormDefinitionId(String formDefinitionId) {
this.formDefinitionId = formDefinitionId;
}
@ApiModelProperty(value = "Optional outcome value when completing a task with a form", example = "accepted/rejected")
public String getOutcome() {
return outcome;
}
public void setOutcome(String outcome) {
this.outcome = outcome;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
|
@ApiModelProperty(value = "If action is complete, you can use this parameter to set variables ")
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
public List<RestVariable> getVariables() {
return variables;
}
@ApiModelProperty(value = "If action is complete, you can use this parameter to set transient variables ")
public List<RestVariable> getTransientVariables() {
return transientVariables;
}
@JsonTypeInfo(use = Id.CLASS, defaultImpl = RestVariable.class)
public void setTransientVariables(List<RestVariable> transientVariables) {
this.transientVariables = transientVariables;
}
@Override
@ApiModelProperty(value = "Action to perform: Either complete, claim, delegate or resolve", example = "complete", required = true)
public String getAction() {
return super.getAction();
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskActionRequest.java
| 2
|
请完成以下Java代码
|
public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
final OrderId quotationId = OrderId.ofRepoIdOrNull(context.getSingleSelectedRecordId());
if (quotationId == null)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("no document selected");
}
return checkEligibleSalesQuotation(quotationId);
}
private ProcessPreconditionsResolution checkEligibleSalesQuotation(final OrderId quotationId)
{
final I_C_Order quotation = ordersRepo.getById(quotationId);
final DocStatus quotationDocStatus = DocStatus.ofNullableCodeOrUnknown(quotation.getDocStatus());
if (!quotationDocStatus.isCompleted())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not a completed quotation");
}
if (!quotation.isSOTrx())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not an sales quotation");
}
if (quotation.getRef_Order_ID() > 0)
{
return ProcessPreconditionsResolution.rejectWithInternalReason("a sales order was already generated");
}
final DocTypeId quotationDocTypeId = DocTypeId.ofRepoId(quotation.getC_DocType_ID());
if (!docTypeBL.isSalesProposalOrQuotation(quotationDocTypeId))
{
return ProcessPreconditionsResolution.rejectWithInternalReason("not a sales quotation doc type");
}
return ProcessPreconditionsResolution.accept();
}
@Override
|
@RunOutOfTrx
protected String doIt()
{
final OrderId quotationId = OrderId.ofRepoId(getRecord_ID());
checkEligibleSalesQuotation(quotationId)
.throwExceptionIfRejected();
final I_C_Order salesOrder = CreateSalesOrderAndBOMsFromQuotationCommand.builder()
.fromQuotationId(quotationId)
.docTypeId(DocTypeId.ofRepoIdOrNull(salesOrderDocTypeRepoId))
.dateOrdered(salesOrderDateOrdered)
.poReference(poReference)
.completeIt(completeIt)
.bomService(bomService)
.build()
.execute();
getResult().setRecordToOpen(
TableRecordReference.of(salesOrder),
orderWindowId.get().getRepoId(), // adWindowId
OpenTarget.SingleDocument,
ProcessExecutionResult.RecordsToOpen.TargetTab.NEW_TAB);
return MSG_OK;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\process\C_Order_CreateFromQuotation_Construction.java
| 1
|
请完成以下Java代码
|
public class TextAnnotationXMLConverter extends BaseBpmnXMLConverter {
protected Map<String, BaseChildElementParser> childParserMap = new HashMap<String, BaseChildElementParser>();
public TextAnnotationXMLConverter() {
TextAnnotationTextParser annotationTextParser = new TextAnnotationTextParser();
childParserMap.put(annotationTextParser.getElementName(), annotationTextParser);
}
public Class<? extends BaseElement> getBpmnElementType() {
return TextAnnotation.class;
}
@Override
protected String getXMLElementName() {
return ELEMENT_TEXT_ANNOTATION;
}
@Override
protected BaseElement convertXMLToElement(XMLStreamReader xtr, BpmnModel model) throws Exception {
TextAnnotation textAnnotation = new TextAnnotation();
BpmnXMLUtil.addXMLLocation(textAnnotation, xtr);
textAnnotation.setTextFormat(xtr.getAttributeValue(null, ATTRIBUTE_TEXTFORMAT));
parseChildElements(getXMLElementName(), textAnnotation, childParserMap, model, xtr);
return textAnnotation;
}
|
@Override
protected void writeAdditionalAttributes(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
TextAnnotation textAnnotation = (TextAnnotation) element;
writeDefaultAttribute(ATTRIBUTE_TEXTFORMAT, textAnnotation.getTextFormat(), xtw);
}
@Override
protected void writeAdditionalChildElements(BaseElement element, BpmnModel model, XMLStreamWriter xtw)
throws Exception {
TextAnnotation textAnnotation = (TextAnnotation) element;
if (StringUtils.isNotEmpty(textAnnotation.getText())) {
xtw.writeStartElement(BPMN2_PREFIX, ELEMENT_TEXT_ANNOTATION_TEXT, BPMN2_NAMESPACE);
xtw.writeCharacters(textAnnotation.getText());
xtw.writeEndElement();
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-bpmn-converter\src\main\java\org\activiti\bpmn\converter\TextAnnotationXMLConverter.java
| 1
|
请完成以下Java代码
|
public boolean matches(String ipAddress) {
// Do not match null or blank address
if (!StringUtils.hasText(ipAddress)) {
return false;
}
assertNotHostName(ipAddress);
InetAddress remoteAddress = parseAddress(ipAddress);
if (!this.requiredAddress.getClass().equals(remoteAddress.getClass())) {
return false;
}
if (this.nMaskBits < 0) {
return remoteAddress.equals(this.requiredAddress);
}
byte[] remAddr = remoteAddress.getAddress();
byte[] reqAddr = this.requiredAddress.getAddress();
int nMaskFullBytes = this.nMaskBits / 8;
for (int i = 0; i < nMaskFullBytes; i++) {
if (remAddr[i] != reqAddr[i]) {
return false;
}
}
byte finalByte = (byte) (0xFF00 >> (this.nMaskBits & 0x07));
if (finalByte != 0) {
return (remAddr[nMaskFullBytes] & finalByte) == (reqAddr[nMaskFullBytes] & finalByte);
}
return true;
}
private static void assertNotHostName(String ipAddress) {
Assert.isTrue(isIpAddress(ipAddress),
() -> String.format("ipAddress %s doesn't look like an IP Address. Is it a host name?", ipAddress));
}
private static boolean isIpAddress(String ipAddress) {
// @formatter:off
return IPV4.matcher(ipAddress).matches()
|| ipAddress.charAt(0) == '['
|| ipAddress.charAt(0) == ':'
|| Character.digit(ipAddress.charAt(0), 16) != -1
|
&& ipAddress.indexOf(':') > 0;
// @formatter:on
}
private InetAddress parseAddress(String address) {
try {
return InetAddress.getByName(address);
}
catch (UnknownHostException ex) {
throw new IllegalArgumentException("Failed to parse address '" + address + "'", ex);
}
}
@Override
public String toString() {
String hostAddress = this.requiredAddress.getHostAddress();
return (this.nMaskBits < 0) ? "IpAddress [" + hostAddress + "]"
: "IpAddress [" + hostAddress + "/" + this.nMaskBits + "]";
}
}
|
repos\spring-security-main\web\src\main\java\org\springframework\security\web\util\matcher\IpAddressMatcher.java
| 1
|
请完成以下Java代码
|
public final class GenericPermissions extends AbstractPermissions<Permission>
{
public static final Builder builder()
{
return new Builder();
}
private GenericPermissions(final Builder builder)
{
super(builder);
}
public Builder toBuilder()
{
return new Builder(this);
}
public static class Builder extends PermissionsBuilder<Permission, GenericPermissions>
{
private Builder()
{
super();
}
private Builder(final GenericPermissions from)
{
super(from.getPermissionsMap());
}
@Override
protected GenericPermissions createPermissionsInstance()
{
return new GenericPermissions(this);
}
/**
|
* Convenient method add a {@link Permission} only if the <code>condition</code> is evaluated as <code>true</code>.
*
* If condition is evaluated as <code>false</code> the permission won't be added.
*
* When adding the permission we use {@link CollisionPolicy#Override}.
*
* @param condition
* @param permission permission to be added.
*/
public Builder addPermissionIfCondition(final boolean condition, final Permission permission)
{
if (condition)
{
addPermission(permission, CollisionPolicy.Override);
}
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\GenericPermissions.java
| 1
|
请完成以下Java代码
|
public boolean containsPoint(Point point) {
// Consider left and top side to be inclusive for points on border
return point.getX() >= this.x1
&& point.getX() < this.x2
&& point.getY() >= this.y1
&& point.getY() < this.y2;
}
public boolean doesOverlap(Region testRegion) {
// Is test region completely to left of my region?
if (testRegion.getX2() < this.getX1()) {
return false;
}
// Is test region completely to right of my region?
if (testRegion.getX1() > this.getX2()) {
return false;
}
// Is test region completely above my region?
if (testRegion.getY1() > this.getY2()) {
return false;
}
// Is test region completely below my region?
if (testRegion.getY2() < this.getY1()) {
return false;
}
return true;
}
|
@Override
public String toString() {
return "[Region (x1=" + x1 + ", y1=" + y1 + "), (x2=" + x2 + ", y2=" + y2 + ")]";
}
public float getX1() {
return x1;
}
public float getY1() {
return y1;
}
public float getX2() {
return x2;
}
public float getY2() {
return y2;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\quadtree\Region.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public ZonedDateTimeFilter getLastTrade() {
return lastTrade;
}
public void setLastTrade(ZonedDateTimeFilter lastTrade) {
this.lastTrade = lastTrade;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
final QuoteCriteria that = (QuoteCriteria) o;
return
Objects.equals(id, that.id) &&
Objects.equals(symbol, that.symbol) &&
Objects.equals(price, that.price) &&
Objects.equals(lastTrade, that.lastTrade);
}
@Override
public int hashCode() {
return Objects.hash(
id,
|
symbol,
price,
lastTrade
);
}
@Override
public String toString() {
return "QuoteCriteria{" +
(id != null ? "id=" + id + ", " : "") +
(symbol != null ? "symbol=" + symbol + ", " : "") +
(price != null ? "price=" + price + ", " : "") +
(lastTrade != null ? "lastTrade=" + lastTrade + ", " : "") +
"}";
}
}
|
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\dto\QuoteCriteria.java
| 2
|
请完成以下Java代码
|
public static Collector<InvoicePayScheduleLine, ?, Optional<InvoicePaySchedule>> collect()
{
return GuavaCollectors.collectUsingListAccumulator(InvoicePaySchedule::optionalOfList);
}
public boolean isValid()
{
return lines.stream().allMatch(InvoicePayScheduleLine::isValid);
}
public boolean validate(@NonNull final Money invoiceGrandTotal)
{
final boolean isValid = computeIsValid(invoiceGrandTotal);
markAsValid(isValid);
return isValid;
}
private boolean computeIsValid(@NonNull final Money invoiceGrandTotal)
{
final Money totalDue = getTotalDueAmt();
return invoiceGrandTotal.isEqualByComparingTo(totalDue);
|
}
private void markAsValid(final boolean isValid)
{
lines.forEach(line -> line.setValid(isValid));
}
private Money getTotalDueAmt()
{
return getLines()
.stream()
.map(InvoicePayScheduleLine::getDueAmount)
.reduce(Money::add)
.orElseThrow(() -> new AdempiereException("No lines"));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\paymentschedule\InvoicePaySchedule.java
| 1
|
请完成以下Java代码
|
public String getName() {
return name;
}
public void setName(final String name) {
this.name = name;
}
public OPERATION getOperation() {
return OPERATION.parse(operation);
}
public void setOperation(final OPERATION operation) {
this.operation = operation.getValue();
}
public long getTimestamp() {
return timestamp;
}
public void setTimestamp(final long timestamp) {
this.timestamp = timestamp;
}
public long getCreatedDate() {
return createdDate;
}
public void setCreatedDate(final long createdDate) {
this.createdDate = createdDate;
}
public long getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(final long modifiedDate) {
this.modifiedDate = modifiedDate;
}
public String getCreatedBy() {
return createdBy;
}
public void setCreatedBy(final String createdBy) {
this.createdBy = createdBy;
}
public String getModifiedBy() {
return modifiedBy;
}
public void setModifiedBy(final String modifiedBy) {
this.modifiedBy = modifiedBy;
}
public void setOperation(final String operation) {
this.operation = operation;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
}
@Override
public boolean equals(final Object obj) {
if (this == obj)
return true;
if (obj == null)
|
return false;
if (getClass() != obj.getClass())
return false;
final Bar other = (Bar) obj;
if (name == null) {
return other.name == null;
} else
return name.equals(other.name);
}
@Override
public String toString() {
return "Bar [name=" + name + "]";
}
@PrePersist
public void onPrePersist() {
LOGGER.info("@PrePersist");
audit(OPERATION.INSERT);
}
@PreUpdate
public void onPreUpdate() {
LOGGER.info("@PreUpdate");
audit(OPERATION.UPDATE);
}
@PreRemove
public void onPreRemove() {
LOGGER.info("@PreRemove");
audit(OPERATION.DELETE);
}
private void audit(final OPERATION operation) {
setOperation(operation);
setTimestamp((new Date()).getTime());
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-query\src\main\java\com\baeldung\persistence\model\Bar.java
| 1
|
请完成以下Java代码
|
public static <T> boolean detectAndRemoveCycle(Node<T> head) {
CycleDetectionResult<T> result = CycleDetectionByFastAndSlowIterators.detectCycle(head);
if (result.cycleExists) {
removeCycle(result.node, head);
}
return result.cycleExists;
}
private static <T> void removeCycle(Node<T> loopNodeParam, Node<T> head) {
int cycleLength = calculateCycleLength(loopNodeParam);
Node<T> cycleLengthAdvancedIterator = head;
Node<T> it = head;
for (int i = 0; i < cycleLength; i++) {
cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next;
}
while (it.next != cycleLengthAdvancedIterator.next) {
it = it.next;
cycleLengthAdvancedIterator = cycleLengthAdvancedIterator.next;
}
cycleLengthAdvancedIterator.next = null;
|
}
private static <T> int calculateCycleLength(Node<T> loopNodeParam) {
Node<T> loopNode = loopNodeParam;
int length = 1;
while (loopNode.next != loopNodeParam) {
length++;
loopNode = loopNode.next;
}
return length;
}
}
|
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-2\src\main\java\com\baeldung\algorithms\linkedlist\CycleRemovalByCountingLoopNodes.java
| 1
|
请完成以下Spring Boot application配置
|
logging.level.root=INFO
# OracleDB connection settings
spring.datasource.url=jdbc:oracle:thin:@//localhost:11521/ORCLPDB1
spring.datasource.username=books
spring.datasource.password=books
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
# Comment this line for standard Spring Boot default choosing algorithm
#spring.datasource.type=org.apache.tomcat.jdbc.pool.DataSource
# HikariCP settings
spring.datasource.hikari.minimumIdle=5
spring.datasource.hikari.maximumPoolSize=20
spring.datasource.hikari.idleTimeout=30000
spring.datasource.hikari.maxLifetime=2000000
spring.datasource.hikari.connectionTimeout=30000
spring.datasource.hikari.poolName=HikariPoolBooks
# Tomcat settings
spring.datasource.tomcat.maxActive=15
spring.datasource.tomcat.minIdle=5
# UCP settings
#Note: These properties require JDBC version 21.0.0.0
spring.datasource.oracleucp.connection-factory-class-name=oracle.jdbc.pool.OracleDataSource
spring.datasource.oracleucp.sql-f
|
or-validate-connection=select * from dual
spring.datasource.oracleucp.connection-pool-name=UcpPoolBooks
spring.datasource.oracleucp.initial-pool-size=5
spring.datasource.oracleucp.min-pool-size=5
spring.datasource.oracleucp.max-pool-size=10
# JPA settings
spring.jpa.database-platform=org.hibernate.dialect.OracleDialect
spring.jpa.hibernate.use-new-id-generator-mappings=false
spring.jpa.hibernate.ddl-auto=create
|
repos\tutorials-master\persistence-modules\spring-boot-persistence\src\main\resources\application-oracle-pooling-basic.properties
| 2
|
请完成以下Java代码
|
private void enableConstraints(final String trxName)
{
final String sql = "SET CONSTRAINTS ALL IMMEDIATE";
DB.executeUpdateAndThrowExceptionOnFail(sql, trxName);
logger.info("Constraints immediate");
}
private void updateMigrationStatus()
{
Services.get(IMigrationBL.class).updateStatus(migration);
}
@Override
public String getStatusDescription()
{
final String statusCode = migration.getStatusCode();
if (action == Action.Apply)
{
if (X_AD_Migration.STATUSCODE_Applied.equals(statusCode))
{
return "Migration successful";
}
else if (X_AD_Migration.STATUSCODE_PartiallyApplied.equals(statusCode))
{
return "Migration partially applied. Please review migration steps for errors.";
}
else if (X_AD_Migration.STATUSCODE_Failed.equals(statusCode))
{
return "Migration failed. Please review migration steps for errors.";
}
}
else if (action == Action.Rollback)
{
if (X_AD_Migration.STATUSCODE_Unapplied.equals(statusCode))
{
return "Rollback successful.";
}
else if (X_AD_Migration.STATUSCODE_PartiallyApplied.equals(statusCode))
{
return "Migration partially rollback. Please review migration steps for errors.";
}
else
{
return "Rollback failed. Please review migration steps for errors.";
}
}
//
// Default
return "@Action@=" + action + ", @StatusCode@=" + statusCode;
}
@Override
public List<Exception> getExecutionErrors()
{
if (executionErrors == null)
{
return Collections.emptyList();
}
else
{
return new ArrayList<>(executionErrors);
}
}
private final void log(String msg, String resolution, boolean isError)
|
{
if (isError && !logger.isErrorEnabled())
{
return;
}
if (!isError && !logger.isInfoEnabled())
{
return;
}
final StringBuffer sb = new StringBuffer();
sb.append(Services.get(IMigrationBL.class).getSummary(migration));
if (!Check.isEmpty(msg, true))
{
sb.append(": ").append(msg.trim());
}
if (resolution != null)
{
sb.append(" [").append(resolution).append("]");
}
if (isError)
{
logger.error(sb.toString());
}
else
{
logger.info(sb.toString());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\MigrationExecutor.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class HUStockInfoRepository
{
public Stream<HUStockInfo> getByQuery(@NonNull final HUStockInfoQuery query)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_M_HU_Stock_Detail_V> queryBuilder = queryBL.createQueryBuilder(I_M_HU_Stock_Detail_V.class)
.setJoinOr()
.setOption(IQueryBuilder.OPTION_Explode_OR_Joins_To_SQL_Unions, true);
for (final HUStockInfoSingleQuery singleQuery : query.getSingleQueries())
{
final ICompositeQueryFilter<I_M_HU_Stock_Detail_V> filter = queryBL.createCompositeQueryFilter(I_M_HU_Stock_Detail_V.class)
.addOnlyActiveRecordsFilter();
if (singleQuery.getProductId() != null)
{
filter.addEqualsFilter(I_M_HU_Stock_Detail_V.COLUMNNAME_M_Product_ID, singleQuery.getProductId());
}
if (singleQuery.getAttributeId() != null)
{
filter.addEqualsFilter(I_M_HU_Stock_Detail_V.COLUMNNAME_M_Attribute_ID, singleQuery.getAttributeId());
}
if (AttributeValue.DONT_FILTER.equals(singleQuery.getAttributeValue()))
{
// nothing
}
else if (AttributeValue.NOT_EMPTY.equals(singleQuery.getAttributeValue()))
{
filter.addNotNull(I_M_HU_Stock_Detail_V.COLUMN_AttributeValue);
}
queryBuilder.filter(filter);
}
return queryBuilder
.create()
.iterateAndStream()
|
.map(this::ofRecord);
}
private HUStockInfo ofRecord(@NonNull final I_M_HU_Stock_Detail_V record)
{
final ADReferenceService adReferenceService = ADReferenceService.get();
final IUOMDAO uomsRepo = Services.get(IUOMDAO.class);
final ITranslatableString huStatus = adReferenceService.retrieveListNameTranslatableString(X_M_HU.HUSTATUS_AD_Reference_ID, record.getHUStatus());
return HUStockInfo.builder()
.attributeId(AttributeId.ofRepoIdOrNull(record.getM_Attribute_ID()))
.attributeValue(record.getAttributeValue())
.bPartnerId(BPartnerId.ofRepoIdOrNull(record.getC_BPartner_ID()))
.huAttributeRepoId(record.getM_HU_Attribute_ID())
.huId(HuId.ofRepoId(record.getM_HU_ID()))
.huStatus(huStatus)
.huStorageRepoId(record.getM_HU_Storage_ID())
.locatorId(extractLocatorId(record))
.productId(ProductId.ofRepoId(record.getM_Product_ID()))
.qty(Quantity.of(record.getQty(), uomsRepo.getById(record.getC_UOM_ID())))
.build();
}
private LocatorId extractLocatorId(final I_M_HU_Stock_Detail_V record)
{
final int locatorRepoId = record.getM_Locator_ID();
return Services.get(IWarehouseDAO.class).getLocatorIdByRepoIdOrNull(locatorRepoId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\stock\HUStockInfoRepository.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
protected CommandContext getCommandContext() {
return Context.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
// Engine scoped
protected IdentityLinkServiceConfiguration getIdentityLinkServiceConfiguration() {
return identityLinkServiceConfiguration;
}
protected Clock getClock() {
|
return getIdentityLinkServiceConfiguration().getClock();
}
protected FlowableEventDispatcher getEventDispatcher() {
return getIdentityLinkServiceConfiguration().getEventDispatcher();
}
protected IdentityLinkEntityManager getIdentityLinkEntityManager() {
return getIdentityLinkServiceConfiguration().getIdentityLinkEntityManager();
}
protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() {
return getIdentityLinkServiceConfiguration().getHistoricIdentityLinkEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\AbstractManager.java
| 2
|
请完成以下Java代码
|
private static ImmutableList<AnnotatedPoint> buildOrderedAnnotatedPointList(
@NonNull final List<InstantInterval> intervals,
@NonNull final List<InstantInterval> intervalsToRemove)
{
final List<AnnotatedPoint> annotatedPoints = new ArrayList<>();
intervals.forEach(interval -> {
annotatedPoints.add(AnnotatedPoint.of(interval.getFrom(), AnnotatedPoint.PointType.Start));
annotatedPoints.add(AnnotatedPoint.of(interval.getTo(), AnnotatedPoint.PointType.End));
});
intervalsToRemove.forEach(interval -> {
annotatedPoints.add(AnnotatedPoint.of(interval.getFrom(), AnnotatedPoint.PointType.GapStart));
annotatedPoints.add(AnnotatedPoint.of(interval.getTo(), AnnotatedPoint.PointType.GapEnd));
});
Collections.sort(annotatedPoints);
return ImmutableList.copyOf(annotatedPoints);
}
@NonNull
private static ImmutableList<InstantInterval> removeGaps(@NonNull final List<AnnotatedPoint> annotatedPointList)
{
final List<InstantInterval> result = new ArrayList<>();
// iterate over the annotatedPointList
boolean isInterval = false;
boolean isGap = false;
Instant intervalStart = null;
for (final AnnotatedPoint point : annotatedPointList)
{
switch (point.type)
{
case Start:
if (!isGap)
{
intervalStart = point.value;
}
isInterval = true;
break;
case End:
if (!isGap)
{
//ignore the null warning as we are on the End case branch
result.add(InstantInterval.of(intervalStart, point.value));
}
isInterval = false;
break;
case GapStart:
if (isInterval)
{
result.add(InstantInterval.of(intervalStart, point.value));
}
isGap = true;
break;
case GapEnd:
if (isInterval)
{
intervalStart = point.value;
}
isGap = false;
break;
}
}
return ImmutableList.copyOf(result);
}
@Value
@Builder
private static class AnnotatedPoint implements Comparable<AnnotatedPoint>
{
|
@NonNull
Instant value;
@NonNull
PointType type;
public static AnnotatedPoint of(@NonNull final Instant instant, @NonNull final PointType type)
{
return AnnotatedPoint.builder()
.value(instant)
.type(type)
.build();
}
@Override
public int compareTo(@NonNull final AnnotatedPoint other)
{
if (other.value.compareTo(this.value) == 0)
{
return this.type.ordinal() < other.type.ordinal() ? -1 : 1;
}
else
{
return this.value.compareTo(other.value);
}
}
// the order is important here, as if multiple points have the same value
// this is the order in which we deal with them
public enum PointType
{
End, GapEnd, GapStart, Start
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\time\IntervalUtils.java
| 1
|
请完成以下Java代码
|
public String getDeploymentId() {
return deploymentId;
}
public void setDeploymentId(String deploymentId) {
this.deploymentId = deploymentId;
}
public String getParentDeploymentId() {
return parentDeploymentId;
}
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
}
public String getInstanceId() {
return instanceId;
}
public void setInstanceId(String instanceId) {
this.instanceId = instanceId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public Map<String, Object> getVariables() {
return variables;
}
public void setVariables(Map<String, Object> variables) {
this.variables = variables;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public boolean isFallbackToDefaultTenant() {
return fallbackToDefaultTenant;
}
public void setFallbackToDefaultTenant(boolean fallbackToDefaultTenant) {
this.fallbackToDefaultTenant = fallbackToDefaultTenant;
}
|
public boolean isForceDMN11() {
return forceDMN11;
}
public void setForceDMN11(boolean forceDMN11) {
this.forceDMN11 = forceDMN11;
}
public boolean isDisableHistory() {
return disableHistory;
}
public void setDisableHistory(boolean disableHistory) {
this.disableHistory = disableHistory;
}
public DmnElement getDmnElement() {
return dmnElement;
}
public void setDmnElement(DmnElement dmnElement) {
this.dmnElement = dmnElement;
}
public DecisionExecutionAuditContainer getDecisionExecution() {
return decisionExecution;
}
public void setDecisionExecution(DecisionExecutionAuditContainer decisionExecution) {
this.decisionExecution = decisionExecution;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-api\src\main\java\org\flowable\dmn\api\ExecuteDecisionContext.java
| 1
|
请完成以下Java代码
|
protected boolean shouldFetchValue(VariableInstanceEntity entity) {
// do not fetch values for byte arrays eagerly (unless requested by the user)
return isByteArrayFetchingEnabled
|| !AbstractTypedValueSerializer.BINARY_VALUE_TYPES.contains(entity.getSerializer().getType().getName());
}
// getters ////////////////////////////////////////////////////
public String getVariableId() {
return variableId;
}
public String getVariableName() {
return variableName;
}
public String[] getVariableNames() {
return variableNames;
}
public String getVariableNameLike() {
return variableNameLike;
}
public String[] getExecutionIds() {
return executionIds;
}
public String[] getProcessInstanceIds() {
return processInstanceIds;
|
}
public String[] getCaseExecutionIds() {
return caseExecutionIds;
}
public String[] getCaseInstanceIds() {
return caseInstanceIds;
}
public String[] getTaskIds() {
return taskIds;
}
public String[] getBatchIds() {
return batchIds;
}
public String[] getVariableScopeIds() {
return variableScopeIds;
}
public String[] getActivityInstanceIds() {
return activityInstanceIds;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\VariableInstanceQueryImpl.java
| 1
|
请完成以下Java代码
|
protected String doIt()
{
ppOrderCandidateService.closeCandidates(getPinstanceId());
return MSG_OK;
}
@Override
@RunOutOfTrx
protected void prepare()
{
if (createSelection() <= 0)
{
throw new AdempiereException("@NoSelection@");
}
}
private int createSelection()
{
final IQueryBuilder<I_PP_Order_Candidate> queryBuilder = createOCQueryBuilder();
final PInstanceId adPInstanceId = getPinstanceId();
Check.assumeNotNull(adPInstanceId, "adPInstanceId is not null");
DB.deleteT_Selection(adPInstanceId, ITrx.TRXNAME_ThreadInherited);
|
return queryBuilder
.create()
.createSelection(adPInstanceId);
}
@NonNull
private IQueryBuilder<I_PP_Order_Candidate> createOCQueryBuilder()
{
final IQueryFilter<I_PP_Order_Candidate> userSelectionFilter = getProcessInfo().getQueryFilterOrElse(null);
if (userSelectionFilter == null)
{
throw new AdempiereException("@NoSelection@");
}
return queryBL
.createQueryBuilder(I_PP_Order_Candidate.class, getCtx(), ITrx.TRXNAME_None)
.addEqualsFilter(I_PP_Order_Candidate.COLUMNNAME_IsClosed, false)
.filter(userSelectionFilter)
.addOnlyActiveRecordsFilter();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\productioncandidate\process\PP_Order_Candidate_CloseSelection.java
| 1
|
请完成以下Java代码
|
public DocumentIdsSelection getDocumentIdsToInvalidate(final TableRecordReferenceSet recordRefs)
{
return DocumentIdsSelection.EMPTY;
}
@Override
public void invalidateAll() {}
@NonNull
Optional<ImmutableList<AttachmentLinksRequest>> createAttachmentLinksRequestList()
{
final ImmutableList<AttachmentLinksRequest> userChanges = aggregateRowsByAttachmentEntryId()
.stream()
.map(OrderAttachmentRow::toAttachmentLinksRequest)
.filter(Optional::isPresent)
.map(Optional::get)
.collect(ImmutableList.toImmutableList());
return !userChanges.isEmpty()
? Optional.of(userChanges)
: Optional.empty();
}
private void changeRow(
@NonNull final DocumentId rowId,
@NonNull final UnaryOperator<OrderAttachmentRow> mapper)
{
if (!rowIds.contains(rowId))
{
throw new EntityNotFoundException(rowId.toJson());
}
rowsById.compute(rowId, (key, oldRow) -> {
if (oldRow == null)
{
throw new EntityNotFoundException(rowId.toJson());
}
return mapper.apply(oldRow);
});
}
/**
* Aggregates the view rows by {@link OrderAttachmentRow#getAttachmentEntryId()}.
* The aggregation logic goes like this:
* 1. if there is at least one row marked by the user for attaching to the purchase order ({@link OrderAttachmentRow#getIsAttachToPurchaseOrder()})
* then, that row will be taken into account for the attachment entry in cause.
* 2. otherwise, take the first row of the group.
*
* @return an aggregated list of {@link OrderAttachmentRow} by {@link AttachmentEntryId}
*/
|
@NonNull
private List<OrderAttachmentRow> aggregateRowsByAttachmentEntryId()
{
final ArrayListMultimap<Integer, OrderAttachmentRow> rowsByAttachmentEntryId = rowsById.values()
.stream()
.collect(GuavaCollectors.toArrayListMultimapByKey(OrderAttachmentRow::getAttachmentEntryId));
final ImmutableList.Builder<OrderAttachmentRow> attachmentRowCollector = ImmutableList.builder();
for (final Integer attachmentEntryId : rowsByAttachmentEntryId.keySet())
{
final List<OrderAttachmentRow> attachmentRowsForEntryId = rowsByAttachmentEntryId.get(attachmentEntryId);
final OrderAttachmentRow firstRowAttach = attachmentRowsForEntryId.stream()
.filter(OrderAttachmentRow::getIsAttachToPurchaseOrder)
.findFirst()
.orElseGet(() -> attachmentRowsForEntryId.get(0));
attachmentRowCollector.add(firstRowAttach);
}
return attachmentRowCollector.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\attachmenteditor\OrderAttachmentRows.java
| 1
|
请完成以下Java代码
|
public void setDiscountAmt (java.math.BigDecimal DiscountAmt)
{
set_Value (COLUMNNAME_DiscountAmt, DiscountAmt);
}
/** Get Discount Amount.
@return Calculated amount of discount
*/
@Override
public java.math.BigDecimal getDiscountAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_DiscountAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Generated.
@param IsGenerated
This Line is generated
*/
@Override
public void setIsGenerated (boolean IsGenerated)
{
set_ValueNoCheck (COLUMNNAME_IsGenerated, Boolean.valueOf(IsGenerated));
}
/** Get Generated.
@return This Line is generated
*/
@Override
public boolean isGenerated ()
{
Object oo = get_Value(COLUMNNAME_IsGenerated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Zeile Nr..
@param Line
Unique line for this document
*/
@Override
public void setLine (int Line)
{
set_Value (COLUMNNAME_Line, Integer.valueOf(Line));
}
/** Get Zeile Nr..
@return Unique line for this document
*/
@Override
public int getLine ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Line);
|
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
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 Write-off Amount.
@param WriteOffAmt
Amount to write-off
*/
@Override
public void setWriteOffAmt (java.math.BigDecimal WriteOffAmt)
{
set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt);
}
/** Get Write-off Amount.
@return Amount to write-off
*/
@Override
public java.math.BigDecimal getWriteOffAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt);
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_C_CashLine.java
| 1
|
请完成以下Java代码
|
private LookupValuesList getTargetExportStatusLookupValues(final LookupDataSourceContext context)
{
final I_C_Doc_Outbound_Log docOutboundLog = ediDocOutBoundLogService.retreiveById(getSelectedDocOutboundLogIds().iterator().next());
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(docOutboundLog.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeTargetExportStatusLookupValues(fromExportStatus);
}
@Override
@Nullable
public Object getParameterDefaultValue(final IProcessDefaultParameter parameter)
{
final I_C_Doc_Outbound_Log docOutboundLog = ediDocOutBoundLogService.retreiveById(getSelectedDocOutboundLogIds().iterator().next());
final EDIExportStatus fromExportStatus = EDIExportStatus.ofCode(docOutboundLog.getEDI_ExportStatus());
return ChangeEDI_ExportStatusHelper.computeParameterDefaultValue(fromExportStatus);
}
@Override
protected String doIt() throws Exception
|
{
final EDIExportStatus targetExportStatus = EDIExportStatus.ofCode(p_TargetExportStatus);
for (final DocOutboundLogId logId : getSelectedDocOutboundLogIds())
{
ChangeEDI_ExportStatusHelper.C_DocOutbound_LogDoIt(targetExportStatus, logId);
}
return MSG_OK;
}
private ImmutableSet<DocOutboundLogId> getSelectedDocOutboundLogIds()
{
final DocumentIdsSelection selectedRowIds = getSelectedRowIds();
return selectedRowIds.toIds(DocOutboundLogId::ofRepoId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\edi_desadv\ChangeEDI_ExportStatus_C_Doc_Outbound_Log_GridView.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String getKeyColumn(MTable table)
{
String[] keyColumns = table.getKeyColumns();
if (keyColumns == null || keyColumns.length != 1)
{
throw new TableColumnPathException(null, "Table " + table.getTableName() + " should have one and only one key column");
}
String keyColumn = keyColumns[0];
return keyColumn;
}
public static Object getSQLValueObjectEx(String trxName, String sql, Object... params)
{
Object retValue = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, trxName);
DB.setParameters(pstmt, params);
rs = pstmt.executeQuery();
if (rs.next())
{
retValue = rs.getObject(1);
}
|
else
{
logger.info("No Value " + sql);
}
}
catch (SQLException e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
return retValue;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\service\impl\TableColumnPathBL.java
| 2
|
请完成以下Java代码
|
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set IP Address.
@param IP_Address
Defines the IP address to transfer data to
*/
public void setIP_Address (String IP_Address)
{
set_Value (COLUMNNAME_IP_Address, IP_Address);
}
/** Get IP Address.
@return Defines the IP address to transfer data to
*/
public String getIP_Address ()
{
return (String)get_Value(COLUMNNAME_IP_Address);
}
/** Set Transfer passive.
@param IsPassive
FTP passive transfer
*/
public void setIsPassive (boolean IsPassive)
{
set_Value (COLUMNNAME_IsPassive, Boolean.valueOf(IsPassive));
}
/** Get Transfer passive.
@return FTP passive transfer
*/
public boolean isPassive ()
{
Object oo = get_Value(COLUMNNAME_IsPassive);
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 Password.
@param Password
Password of any length (case sensitive)
*/
public void setPassword (String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
/** Get Password.
@return Password of any length (case sensitive)
*/
public String getPassword ()
{
return (String)get_Value(COLUMNNAME_Password);
}
/** Set URL.
@param URL
Full URL address - e.g. http://www.adempiere.org
*/
public void setURL (String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
public String getURL ()
{
return (String)get_Value(COLUMNNAME_URL);
}
/** Set Registered EMail.
@param UserName
Email of the responsible for the System
*/
public void setUserName (String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
/** Get Registered EMail.
@return Email of the responsible for the System
*/
public String getUserName ()
{
return (String)get_Value(COLUMNNAME_UserName);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_Media_Server.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private static Map<EncodeHintType, ErrorCorrectionLevel> extractHints(final String eclStr, final BarcodeFormat format)
{
// Hints
final Map<EncodeHintType, ErrorCorrectionLevel> hints = new HashMap<>();
// get error correction level
if (format == BarcodeFormat.QR_CODE)
{
if (!Check.isEmpty(eclStr, true))
{
ErrorCorrectionLevel ecl = null;
for (int i = 0; i <= 3; i++)
{
ecl = ErrorCorrectionLevel.forBits(i);
if (ecl.toString().equals(eclStr))
{
break;
}
}
hints.put(EncodeHintType.ERROR_CORRECTION, ecl);
}
}
|
return hints;
}
private static byte[] toByteArray(final BitMatrix matrix, final String imageFormat)
{
//
// Create image from BitMatrix
final BufferedImage image = MatrixToImageWriter.toBufferedImage(matrix);
// Convert BufferedImage to imageFormat and write it into the stream
try
{
final ByteArrayOutputStream out = new ByteArrayOutputStream();
ImageIO.write(image, imageFormat, out);
return out.toByteArray();
}
catch (final IOException ex)
{
throw new AdempiereException("Failed creating " + imageFormat + " image", ex);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\rest\BarcodeRestController.java
| 2
|
请完成以下Java代码
|
public NewRecordDescriptor getNewRecordDescriptor(final DocumentEntityDescriptor entityDescriptor)
{
final WindowId newRecordWindowId = entityDescriptor.getWindowId();
return newRecordDescriptorsByTableName.values()
.stream()
.filter(descriptor -> WindowId.equals(newRecordWindowId, descriptor.getNewRecordWindowId()))
.findFirst()
.orElseThrow(() -> new AdempiereException("No new record quick input defined windowId=" + newRecordWindowId));
}
@Nullable
public DocumentEntityDescriptor getNewRecordEntityDescriptorIfAvailable(@NonNull final String tableName)
{
final NewRecordDescriptor newRecordDescriptor = getNewRecordDescriptorOrNull(tableName);
|
if (newRecordDescriptor == null)
{
return null;
}
try
{
return documentDescriptors.getDocumentEntityDescriptor(newRecordDescriptor.getNewRecordWindowId());
}
catch (final Exception ex)
{
logger.warn("Failed fetching document entity descriptor for {}. Ignored", newRecordDescriptor, ex);
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\NewRecordDescriptorsProvider.java
| 1
|
请完成以下Java代码
|
public BigDecimal getQueuingTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QueuingTime);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setS_Resource_ID (final int S_Resource_ID)
{
if (S_Resource_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_Resource_ID, S_Resource_ID);
}
@Override
public int getS_Resource_ID()
{
return get_ValueAsInt(COLUMNNAME_S_Resource_ID);
}
@Override
public org.compiere.model.I_S_ResourceType getS_ResourceType()
{
return get_ValueAsPO(COLUMNNAME_S_ResourceType_ID, org.compiere.model.I_S_ResourceType.class);
}
@Override
public void setS_ResourceType(final org.compiere.model.I_S_ResourceType S_ResourceType)
{
set_ValueFromPO(COLUMNNAME_S_ResourceType_ID, org.compiere.model.I_S_ResourceType.class, S_ResourceType);
}
@Override
public void setS_ResourceType_ID (final int S_ResourceType_ID)
{
if (S_ResourceType_ID < 1)
set_Value (COLUMNNAME_S_ResourceType_ID, null);
else
set_Value (COLUMNNAME_S_ResourceType_ID, S_ResourceType_ID);
}
@Override
public int getS_ResourceType_ID()
{
return get_ValueAsInt(COLUMNNAME_S_ResourceType_ID);
}
|
@Override
public void setValue (final java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
@Override
public void setWaitingTime (final @Nullable BigDecimal WaitingTime)
{
set_Value (COLUMNNAME_WaitingTime, WaitingTime);
}
@Override
public BigDecimal getWaitingTime()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WaitingTime);
return bd != null ? bd : BigDecimal.ZERO;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_Resource.java
| 1
|
请完成以下Java代码
|
public boolean isAsyncBefore() {
return !isAsyncAfter();
}
protected void updateAsyncBeforeTargetConfiguration() {
AsyncContinuationConfiguration targetConfiguration = new AsyncContinuationConfiguration();
AsyncContinuationConfiguration currentConfiguration = (AsyncContinuationConfiguration) jobEntity.getJobHandlerConfiguration();
if (PvmAtomicOperation.PROCESS_START.getCanonicalName().equals(currentConfiguration.getAtomicOperation())) {
// process start always stays process start
targetConfiguration.setAtomicOperation(PvmAtomicOperation.PROCESS_START.getCanonicalName());
}
else {
if (((ActivityImpl) targetScope).getIncomingTransitions().isEmpty()) {
targetConfiguration.setAtomicOperation(PvmAtomicOperation.ACTIVITY_START_CREATE_SCOPE.getCanonicalName());
}
else {
targetConfiguration.setAtomicOperation(PvmAtomicOperation.TRANSITION_CREATE_SCOPE.getCanonicalName());
}
}
jobEntity.setJobHandlerConfiguration(targetConfiguration);
}
protected void updateAsyncAfterTargetConfiguration(AsyncContinuationConfiguration currentConfiguration) {
ActivityImpl targetActivity = (ActivityImpl) targetScope;
List<PvmTransition> outgoingTransitions = targetActivity.getOutgoingTransitions();
AsyncContinuationConfiguration targetConfiguration = new AsyncContinuationConfiguration();
|
if (outgoingTransitions.isEmpty()) {
targetConfiguration.setAtomicOperation(PvmAtomicOperation.ACTIVITY_END.getCanonicalName());
}
else {
targetConfiguration.setAtomicOperation(PvmAtomicOperation.TRANSITION_NOTIFY_LISTENER_TAKE.getCanonicalName());
if (outgoingTransitions.size() == 1) {
targetConfiguration.setTransitionId(outgoingTransitions.get(0).getId());
}
else {
TransitionImpl matchingTargetTransition = null;
String currentTransitionId = currentConfiguration.getTransitionId();
if (currentTransitionId != null) {
matchingTargetTransition = targetActivity.findOutgoingTransition(currentTransitionId);
}
if (matchingTargetTransition != null) {
targetConfiguration.setTransitionId(matchingTargetTransition.getId());
}
else {
// should not happen since it is avoided by validation
throw new ProcessEngineException("Cannot determine matching outgoing sequence flow");
}
}
}
jobEntity.setJobHandlerConfiguration(targetConfiguration);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingAsyncJobInstance.java
| 1
|
请完成以下Java代码
|
private static void run() throws Exception {
HttpRequestFactory requestFactory = HTTP_TRANSPORT.createRequestFactory((HttpRequest request) -> {
request.setParser(new JsonObjectParser(JSON_FACTORY));
});
GitHubUrl url = new GitHubUrl("https://api.github.com/users");
url.per_page = 10;
url.page = 1;
HttpRequest request = requestFactory.buildGetRequest(url);
ExponentialBackOff backoff = new ExponentialBackOff.Builder().setInitialIntervalMillis(500).setMaxElapsedTimeMillis(900000).setMaxIntervalMillis(6000).setMultiplier(1.5).setRandomizationFactor(0.5).build();
request.setUnsuccessfulResponseHandler(new HttpBackOffUnsuccessfulResponseHandler(backoff));
Type type = new TypeToken<List<User>>() {
}.getType();
List<User> users = (List<User>) request.execute().parseAs(type);
System.out.println(users);
url.appendRawPath("/eugenp");
|
request = requestFactory.buildGetRequest(url);
ExecutorService executor = Executors.newSingleThreadExecutor();
Future<HttpResponse> responseFuture = request.executeAsync(executor);
User eugen = responseFuture.get().parseAs(User.class);
System.out.println(eugen);
executor.shutdown();
}
public static void main(String[] args) {
try {
run();
} catch (Exception e) {
System.err.println(e.getMessage());
}
}
}
|
repos\tutorials-master\libraries-http-2\src\main\java\com\baeldung\googlehttpclientguide\GitHubExample.java
| 1
|
请完成以下Java代码
|
public class AtomicOperationDeleteCascadeFireActivityEnd extends AbstractEventAtomicOperation {
@Override
protected ScopeImpl getScope(InterpretableExecution execution) {
ActivityImpl activity = (ActivityImpl) execution.getActivity();
if (activity != null) {
return activity;
} else {
InterpretableExecution parent = (InterpretableExecution) execution.getParent();
if (parent != null) {
return getScope((InterpretableExecution) execution.getParent());
}
return execution.getProcessDefinition();
}
}
@Override
protected String getEventName() {
return org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_END;
}
@Override
|
protected void eventNotificationsCompleted(InterpretableExecution execution) {
ActivityImpl activity = (ActivityImpl) execution.getActivity();
if ((execution.isScope())
&& (activity != null)) {
execution.setActivity(activity.getParentActivity());
execution.performOperation(AtomicOperation.DELETE_CASCADE_FIRE_ACTIVITY_END);
} else {
if (execution.isScope()) {
execution.destroy();
}
execution.remove();
if (!execution.isDeleteRoot()) {
InterpretableExecution parent = (InterpretableExecution) execution.getParent();
if (parent != null) {
parent.performOperation(AtomicOperation.DELETE_CASCADE);
}
}
}
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\runtime\AtomicOperationDeleteCascadeFireActivityEnd.java
| 1
|
请完成以下Java代码
|
public class JodaDateTimeType implements VariableType {
public String getTypeName() {
return "jodadatetime";
}
public boolean isCachable() {
return true;
}
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return DateTime.class.isAssignableFrom(value.getClass());
}
public Object getValue(ValueFields valueFields) {
|
Long longValue = valueFields.getLongValue();
if (longValue != null) {
return new DateTime(longValue);
}
return null;
}
public void setValue(Object value, ValueFields valueFields) {
if (value != null) {
valueFields.setLongValue(((DateTime) value).getMillis());
} else {
valueFields.setLongValue(null);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\JodaDateTimeType.java
| 1
|
请完成以下Java代码
|
public class DefaultTableColorProvider extends TableColorProviderAdapter
{
/** Color Column Index of Model */
private int colorColumnIndex = -1;
/** Color Column compare data */
private Object colorDataCompare = Env.ZERO;
@Override
public Color getForegroundColor(ITable table, int rowIndexModel)
{
final int cCode = getRelativeForegroundColor(table, rowIndexModel);
if (cCode == 0)
{
return COLOR_NONE; // Black
}
else if (cCode < 0)
{
return AdempierePLAF.getTextColor_Issue(); // Red
}
else
{
return AdempierePLAF.getTextColor_OK(); // Blue
}
}
/**
* Get ColorCode for Row.
*
* <pre>
* If numerical value in compare column is
* negative = -1,
* positive = 1,
* otherwise = 0
* If Timestamp
* </pre>
*
* @param table
* @param rowIndexModel
* @return color code
*/
private int getRelativeForegroundColor(final ITable table, final int rowIndexModel)
{
if (colorColumnIndex < 0)
{
return 0;
}
Object data = table.getModelValueAt(rowIndexModel, colorColumnIndex);
int cmp = 0;
// We need to have a Number
if (data == null)
{
return 0;
}
try
{
if (data instanceof Timestamp)
{
if (colorDataCompare == null || !(colorDataCompare instanceof Timestamp))
colorDataCompare = new Timestamp(System.currentTimeMillis());
cmp = ((Timestamp)colorDataCompare).compareTo((Timestamp)data);
}
else
{
if (colorDataCompare == null || !(colorDataCompare instanceof BigDecimal))
colorDataCompare = Env.ZERO;
|
if (!(data instanceof BigDecimal))
data = new BigDecimal(data.toString());
cmp = ((BigDecimal)colorDataCompare).compareTo((BigDecimal)data);
}
}
catch (Exception e)
{
return 0;
}
if (cmp > 0)
{
return -1;
}
if (cmp < 0)
{
return 1;
}
return 0;
}
public int getColorColumnIndex()
{
return colorColumnIndex;
}
public void setColorColumnIndex(int colorColumnIndexModel)
{
this.colorColumnIndex = colorColumnIndexModel;
}
public Object getColorDataCompare()
{
return colorDataCompare;
}
public void setColorDataCompare(Object colorDataCompare)
{
this.colorDataCompare = colorDataCompare;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\ui\DefaultTableColorProvider.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class JsonFileItemWriterDemo {
@Autowired
private JobBuilderFactory jobBuilderFactory;
@Autowired
private StepBuilderFactory stepBuilderFactory;
@Autowired
private ListItemReader<TestData> simpleReader;
@Bean
public Job jsonFileItemWriterJob() throws Exception {
return jobBuilderFactory.get("jsonFileItemWriterJob")
.start(step())
.build();
}
private Step step() throws Exception {
return stepBuilderFactory.get("step")
.<TestData, TestData>chunk(2)
.reader(simpleReader)
.writer(jsonFileItemWriter())
.build();
|
}
private JsonFileItemWriter<TestData> jsonFileItemWriter() throws IOException {
// 文件输出目标地址
FileSystemResource file = new FileSystemResource("/Users/mrbird/Desktop/file.json");
Path path = Paths.get(file.getPath());
if (!Files.exists(path)) {
Files.createFile(path);
}
// 将对象转换为json
JacksonJsonObjectMarshaller<TestData> marshaller = new JacksonJsonObjectMarshaller<>();
JsonFileItemWriter<TestData> writer = new JsonFileItemWriter<>(file, marshaller);
// 设置别名
writer.setName("testDatasonFileItemWriter");
return writer;
}
}
|
repos\SpringAll-master\69.spring-batch-itemwriter\src\main\java\cc\mrbird\batch\job\JsonFileItemWriterDemo.java
| 2
|
请完成以下Java代码
|
public Set<ErrorPage> getErrorPages() {
return this.errorPages;
}
@Override
public void setErrorPages(Set<? extends ErrorPage> errorPages) {
Assert.notNull(errorPages, "'errorPages' must not be null");
this.errorPages = new LinkedHashSet<>(errorPages);
}
@Override
public void addErrorPages(ErrorPage... errorPages) {
Assert.notNull(errorPages, "'errorPages' must not be null");
this.errorPages.addAll(Arrays.asList(errorPages));
}
public @Nullable Ssl getSsl() {
return this.ssl;
}
@Override
public void setSsl(@Nullable Ssl ssl) {
this.ssl = ssl;
}
/**
* Return the configured {@link SslBundles}.
* @return the {@link SslBundles} or {@code null}
* @since 3.2.0
*/
public @Nullable SslBundles getSslBundles() {
return this.sslBundles;
}
@Override
public void setSslBundles(@Nullable SslBundles sslBundles) {
this.sslBundles = sslBundles;
}
public @Nullable Http2 getHttp2() {
return this.http2;
}
@Override
public void setHttp2(@Nullable Http2 http2) {
this.http2 = http2;
}
public @Nullable Compression getCompression() {
return this.compression;
}
@Override
public void setCompression(@Nullable Compression compression) {
this.compression = compression;
}
public @Nullable String getServerHeader() {
return this.serverHeader;
}
@Override
public void setServerHeader(@Nullable String serverHeader) {
this.serverHeader = serverHeader;
}
@Override
|
public void setShutdown(Shutdown shutdown) {
this.shutdown = shutdown;
}
/**
* Returns the shutdown configuration that will be applied to the server.
* @return the shutdown configuration
* @since 2.3.0
*/
public Shutdown getShutdown() {
return this.shutdown;
}
/**
* Return the {@link SslBundle} that should be used with this server.
* @return the SSL bundle
*/
protected final SslBundle getSslBundle() {
return WebServerSslBundle.get(this.ssl, this.sslBundles);
}
protected final Map<String, SslBundle> getServerNameSslBundles() {
Assert.state(this.ssl != null, "'ssl' must not be null");
return this.ssl.getServerNameBundles()
.stream()
.collect(Collectors.toMap(ServerNameSslBundle::serverName, (serverNameSslBundle) -> {
Assert.state(this.sslBundles != null, "'sslBundles' must not be null");
return this.sslBundles.getBundle(serverNameSslBundle.bundle());
}));
}
/**
* Return the absolute temp dir for given web server.
* @param prefix server name
* @return the temp dir for given server.
*/
protected final File createTempDir(String prefix) {
try {
File tempDir = Files.createTempDirectory(prefix + "." + getPort() + ".").toFile();
tempDir.deleteOnExit();
return tempDir;
}
catch (IOException ex) {
throw new WebServerException(
"Unable to create tempDir. java.io.tmpdir is set to " + System.getProperty("java.io.tmpdir"), ex);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\AbstractConfigurableWebServerFactory.java
| 1
|
请完成以下Java代码
|
public static class AdaptiveCard {
@JsonProperty("$schema")
private final String schema = "http://adaptivecards.io/schemas/adaptive-card.json";
private final String type = "AdaptiveCard";
private BackgroundImage backgroundImage;
@JsonProperty("body")
private List<TextBlock> textBlocks = new ArrayList<>();
private List<ActionOpenUrl> actions = new ArrayList<>();
}
@Data
@NoArgsConstructor
public static class BackgroundImage {
private String url;
private final String fillMode = "repeat";
public BackgroundImage(String color) {
// This is the only one way how to specify color the custom color for the card
url = ImageUtils.getEmbeddedBase64EncodedImg(color);
}
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class TextBlock {
|
private final String type = "TextBlock";
private String text;
private String weight = "Normal";
private String size = "Medium";
private String spacing = "None";
private String color = "#FFFFFF";
private final boolean wrap = true;
}
@Data
@NoArgsConstructor
@AllArgsConstructor
public static class ActionOpenUrl {
private final String type = "Action.OpenUrl";
private String title;
private String url;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\channels\TeamsAdaptiveCard.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
class ZipkinHttpClientSender extends HttpSender {
private final HttpClient httpClient;
private final Duration readTimeout;
ZipkinHttpClientSender(Encoding encoding, Factory endpointSupplierFactory, String endpoint, HttpClient httpClient,
Duration readTimeout) {
super(encoding, endpointSupplierFactory, endpoint);
this.httpClient = httpClient;
this.readTimeout = readTimeout;
}
@Override
void postSpans(URI endpoint, Map<String, String> headers, byte[] body) throws IOException {
Builder request = HttpRequest.newBuilder()
.POST(BodyPublishers.ofByteArray(body))
.uri(endpoint)
|
.timeout(this.readTimeout);
headers.forEach((name, value) -> request.header(name, value));
try {
HttpResponse<Void> response = this.httpClient.send(request.build(), BodyHandlers.discarding());
if (response.statusCode() / 100 != 2) {
throw new IOException("Expected HTTP status 2xx, got %d".formatted(response.statusCode()));
}
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
throw new IOException("Got interrupted while sending spans", ex);
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-zipkin\src\main\java\org\springframework\boot\zipkin\autoconfigure\ZipkinHttpClientSender.java
| 2
|
请完成以下Java代码
|
public static boolean isEmpty(Map<?, ?> obj) {
return null == obj || obj.isEmpty();
}
/**
* 函数功能说明 : 获得文件名的后缀名. 修改者名字: 修改日期: 修改内容:
*
* @参数: @param fileName
* @参数: @return
* @return String
* @throws
*/
public static String getExt(String fileName) {
return fileName.substring(fileName.lastIndexOf(".") + 1);
}
/**
* 获取去掉横线的长度为32的UUID串.
*
* @author WuShuicheng.
* @return uuid.
*/
public static String get32UUID() {
return UUID.randomUUID().toString().replace("-", "");
}
/**
* 获取带横线的长度为36的UUID串.
*
* @author WuShuicheng.
* @return uuid.
*/
public static String get36UUID() {
return UUID.randomUUID().toString();
}
/**
* 验证一个字符串是否完全由纯数字组成的字符串,当字符串为空时也返回false.
*
* @author WuShuicheng .
* @param str
* 要判断的字符串 .
* @return true or false .
*/
public static boolean isNumeric(String str) {
if (StringUtils.isBlank(str)) {
return false;
} else {
return str.matches("\\d*");
}
}
/**
* 计算采用utf-8编码方式时字符串所占字节数
|
*
* @param content
* @return
*/
public static int getByteSize(String content) {
int size = 0;
if (null != content) {
try {
// 汉字采用utf-8编码时占3个字节
size = content.getBytes("utf-8").length;
} catch (UnsupportedEncodingException e) {
LOG.error(e);
}
}
return size;
}
/**
* 函数功能说明 : 截取字符串拼接in查询参数. 修改者名字: 修改日期: 修改内容:
*
* @参数: @param ids
* @参数: @return
* @return String
* @throws
*/
public static List<String> getInParam(String param) {
boolean flag = param.contains(",");
List<String> list = new ArrayList<String>();
if (flag) {
list = Arrays.asList(param.split(","));
} else {
list.add(param);
}
return list;
}
/**
* 判断对象是否为空
*
* @param obj
* @return
*/
public static boolean isNotNull(Object obj) {
if (obj != null && obj.toString() != null && !"".equals(obj.toString().trim())) {
return true;
} else {
return false;
}
}
}
|
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\StringUtil.java
| 1
|
请完成以下Java代码
|
public boolean isStarted() {
return true;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.util.component.LifeCycle#isStarting()
*/
@Override
public boolean isStarting() {
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.util.component.LifeCycle#isStopped()
*/
@Override
public boolean isStopped() {
return false;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.util.component.LifeCycle#isStopping()
*/
@Override
public boolean isStopping() {
return false;
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.jetty.util.component.LifeCycle#removeLifeCycleListener(org.
* eclipse.jetty.util.component.LifeCycle.Listener)
*/
@Override
public void removeLifeCycleListener(Listener arg0) {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.util.component.LifeCycle#start()
*/
@Override
public void start() throws Exception {
}
|
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.util.component.LifeCycle#stop()
*/
@Override
public void stop() throws Exception {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#destroy()
*/
@Override
public void destroy() {
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#getServer()
*/
@Override
public Server getServer() {
return null;
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#handle(java.lang.String,
* org.eclipse.jetty.server.Request, javax.servlet.http.HttpServletRequest,
* javax.servlet.http.HttpServletResponse)
*/
@Override
public void handle(String arg0, Request arg1, HttpServletRequest arg2, HttpServletResponse arg3) throws IOException, ServletException {
LOG.info("Received a new request");
}
/*
* (non-Javadoc)
*
* @see org.eclipse.jetty.server.Handler#setServer(org.eclipse.jetty.server.
* Server)
*/
@Override
public void setServer(Server server) {
}
}
|
repos\tutorials-master\libraries-server-2\src\main\java\com\baeldung\jetty\programmatic\LoggingRequestHandler.java
| 1
|
请完成以下Java代码
|
public final class POCacheLocal extends AbstractPOCacheLocal
{
private final Reference<PO> parentPORef;
public static POCacheLocal newInstance(@NonNull final PO parent, @NonNull final String parentColumnName, @NonNull final String tableName)
{
return new POCacheLocal(parent, parentColumnName, tableName);
}
private POCacheLocal(
@NonNull final PO parent,
@NonNull final String parentColumnName,
@NonNull final String tableName)
{
super(parentColumnName, tableName);
Check.assumeNotEmpty(parentColumnName, "parentColumnName is null");
Check.assumeNotEmpty(tableName, "tableName");
this.parentPORef = new WeakReference<>(parent);
}
private PO getParentPO()
{
final PO parentPO = parentPORef.get();
if (parentPO == null)
{
// cleanup
this.poRef = null;
// throw exception
throw new AdempiereException("Parent PO reference expired");
}
return parentPO;
}
@Override
protected Properties getParentCtx()
{
return getParentPO().getCtx();
}
|
@Override
protected String getParentTrxName()
{
return getParentPO().get_TrxName();
}
@Override
protected int getId()
{
final PO parentPO = getParentPO();
final String parentColumnName = getParentColumnName();
return parentPO.get_ValueAsInt(parentColumnName);
}
@Override
protected boolean setId(final int id)
{
final PO parentPO = getParentPO();
final Integer value = id < 0 ? null : id;
final String parentColumnName = getParentColumnName();
final boolean ok = parentPO.set_ValueOfColumn(parentColumnName, value);
if (!ok)
{
logger.warn("Cannot set " + parentColumnName + "=" + id + " to " + parentPO);
}
return ok;
}
public POCacheLocal copy(@NonNull final PO parentPO)
{
final POCacheLocal poCacheLocalNew = newInstance(parentPO, getParentColumnName(), getTableName());
poCacheLocalNew.poRef = this.poRef;
return poCacheLocalNew;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\POCacheLocal.java
| 1
|
请完成以下Java代码
|
public class PaymentTypeInformationSDD {
@XmlElement(name = "SvcLvl", required = true)
protected ServiceLevelSEPA svcLvl;
@XmlElement(name = "LclInstrm", required = true)
protected LocalInstrumentSEPA lclInstrm;
@XmlElement(name = "SeqTp", required = true)
@XmlSchemaType(name = "string")
protected SequenceType1Code seqTp;
@XmlElement(name = "CtgyPurp")
protected CategoryPurposeSEPA ctgyPurp;
/**
* Gets the value of the svcLvl property.
*
* @return
* possible object is
* {@link ServiceLevelSEPA }
*
*/
public ServiceLevelSEPA getSvcLvl() {
return svcLvl;
}
/**
* Sets the value of the svcLvl property.
*
* @param value
* allowed object is
* {@link ServiceLevelSEPA }
*
*/
public void setSvcLvl(ServiceLevelSEPA value) {
this.svcLvl = value;
}
/**
* Gets the value of the lclInstrm property.
*
* @return
* possible object is
* {@link LocalInstrumentSEPA }
*
*/
public LocalInstrumentSEPA getLclInstrm() {
return lclInstrm;
}
/**
* Sets the value of the lclInstrm property.
*
* @param value
* allowed object is
* {@link LocalInstrumentSEPA }
*
*/
public void setLclInstrm(LocalInstrumentSEPA value) {
this.lclInstrm = value;
}
/**
* Gets the value of the seqTp property.
*
* @return
* possible object is
* {@link SequenceType1Code }
*
*/
public SequenceType1Code getSeqTp() {
return seqTp;
}
/**
* Sets the value of the seqTp property.
|
*
* @param value
* allowed object is
* {@link SequenceType1Code }
*
*/
public void setSeqTp(SequenceType1Code value) {
this.seqTp = value;
}
/**
* Gets the value of the ctgyPurp property.
*
* @return
* possible object is
* {@link CategoryPurposeSEPA }
*
*/
public CategoryPurposeSEPA getCtgyPurp() {
return ctgyPurp;
}
/**
* Sets the value of the ctgyPurp property.
*
* @param value
* allowed object is
* {@link CategoryPurposeSEPA }
*
*/
public void setCtgyPurp(CategoryPurposeSEPA value) {
this.ctgyPurp = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PaymentTypeInformationSDD.java
| 1
|
请完成以下Java代码
|
public ManagedConnection createManagedConnection(Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
return new JcaExecutorServiceManagedConnection(this);
}
@SuppressWarnings("rawtypes")
public ManagedConnection matchManagedConnections(Set connectionSet, Subject subject, ConnectionRequestInfo cxRequestInfo) throws ResourceException {
ManagedConnection result = null;
Iterator it = connectionSet.iterator();
while (result == null && it.hasNext()) {
ManagedConnection mc = (ManagedConnection) it.next();
if (mc instanceof JcaExecutorServiceManagedConnection) {
result = mc;
}
}
return result;
}
public PrintWriter getLogWriter() throws ResourceException {
return logwriter;
}
public void setLogWriter(PrintWriter out) throws ResourceException {
logwriter = out;
}
|
public ResourceAdapter getResourceAdapter() {
return ra;
}
public void setResourceAdapter(ResourceAdapter ra) {
this.ra = ra;
}
@Override
public int hashCode() {
return 31;
}
@Override
public boolean equals(Object other) {
if (other == null)
return false;
if (other == this)
return true;
if (!(other instanceof JcaExecutorServiceManagedConnectionFactory))
return false;
return true;
}
}
|
repos\camunda-bpm-platform-master\javaee\jobexecutor-ra\src\main\java\org\camunda\bpm\container\impl\threading\ra\outbound\JcaExecutorServiceManagedConnectionFactory.java
| 1
|
请完成以下Java代码
|
public String toString() {
return "Consult{" +
"id=" + id +
", products=" + products +
", orderDate=" + orderDate +
", customer=" + customer +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CustomerOrder co = (CustomerOrder) o;
return Objects.equals(id, co.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name="customer_id", nullable = false)
private Customer customer;
|
public Long getId() {
return id;
}
public LocalDate getOrderDate() {
return orderDate;
}
public void setOrderDate(LocalDate orderDate) {
this.orderDate = orderDate;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
}
|
repos\tutorials-master\persistence-modules\spring-data-jpa-repo-3\src\main\java\com\baeldung\spring\data\jpa\joinquery\entities\CustomerOrder.java
| 1
|
请完成以下Java代码
|
public ImmutableList<ITranslatableString> validate()
{
if (!isActive())
{
return ImmutableList.of();
}
final ImmutableList.Builder<ITranslatableString> result = ImmutableList.builder();
if (!isAddressSpecifiedByExistingLocationIdOnly())
{
if (isBlank(countryCode))
{
result.add(TranslatableStrings.constant("Missing location.countryCode"));
}
if (!isBlank(district) && isBlank(postal))
{
result.add(TranslatableStrings.constant("Missing location.postal (required if location.district is set)"));
}
}
return result.build();
}
@JsonIgnore
public boolean isAddressSpecifiedByExistingLocationIdOnly()
{
return toAddress().isOnlyExistingLocationIdSet();
}
public void addHandle(@NonNull final String handle)
{
handles.add(handle);
}
public boolean containsHandle(@NonNull final String handle)
{
return handles.contains(handle);
}
public BPartnerLocationAddressPart toAddress()
{
return BPartnerLocationAddressPart.builder()
|
.existingLocationId(getExistingLocationId())
.address1(getAddress1())
.address2(getAddress2())
.address3(getAddress3())
.address4(getAddress4())
.poBox(getPoBox())
.postal(getPostal())
.city(getCity())
.region(getRegion())
.district(getDistrict())
.countryCode(getCountryCode())
.build();
}
public void setFromAddress(@NonNull final BPartnerLocationAddressPart address)
{
setExistingLocationId(address.getExistingLocationId());
setAddress1(address.getAddress1());
setAddress2(address.getAddress2());
setAddress3(address.getAddress3());
setAddress4(address.getAddress4());
setCity(address.getCity());
setCountryCode(address.getCountryCode());
setPoBox(address.getPoBox());
setPostal(address.getPostal());
setRegion(address.getRegion());
setDistrict(address.getDistrict());
}
@Nullable
public LocationId getExistingLocationIdNotNull()
{
return Check.assumeNotNull(getExistingLocationId(), "existingLocationId not null: {}", this);
}
/**
* Can be used if this instance's ID is known to be not null.
*/
@NonNull
public BPartnerLocationId getIdNotNull()
{
return Check.assumeNotNull(id, "id may not be null at this point");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\BPartnerLocation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class PayPalConfig
{
public static final String DEFAULT_orderApproveCallbackUrl = "/paypal_confirm";
String clientId;
String clientSecret;
MailTemplateId orderApproveMailTemplateId;
@Getter(AccessLevel.NONE)
String orderApproveCallbackUrl;
boolean sandbox;
String baseUrl;
String webUrl;
@Builder
private PayPalConfig(
@NonNull final String clientId,
@NonNull final String clientSecret,
@NonNull final MailTemplateId orderApproveMailTemplateId,
@Nullable final String orderApproveCallbackUrl,
final boolean sandbox,
@Nullable final String baseUrl,
@Nullable final String webUrl)
{
this.clientId = clientId;
this.clientSecret = clientSecret;
this.orderApproveMailTemplateId = orderApproveMailTemplateId;
this.orderApproveCallbackUrl = !Check.isEmpty(orderApproveCallbackUrl, true)
? orderApproveCallbackUrl.trim()
: DEFAULT_orderApproveCallbackUrl;
if (sandbox)
{
this.sandbox = true;
this.baseUrl = null;
this.webUrl = null;
}
else
{
Check.assumeNotEmpty(baseUrl, "baseUrl is not empty");
Check.assumeNotEmpty(webUrl, "webUrl is not empty");
this.sandbox = true;
this.baseUrl = baseUrl;
this.webUrl = webUrl;
}
}
|
public String getOrderApproveCallbackUrl(final String defaultBaseUrl)
{
if (orderApproveCallbackUrl.startsWith("http"))
{
return orderApproveCallbackUrl;
}
else
{
if (defaultBaseUrl == null)
{
throw new AdempiereException("Config error: Order approve URL is just a path and no base url was provided: " + orderApproveCallbackUrl);
}
String url = defaultBaseUrl;
if (!url.endsWith("/") && !orderApproveCallbackUrl.startsWith("/"))
{
url += "/";
}
url += orderApproveCallbackUrl;
return url;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.paypal\src\main\java\de\metas\payment\paypal\config\PayPalConfig.java
| 2
|
请完成以下Java代码
|
public void saveAuthorizedClient(OAuth2AuthorizedClient authorizedClient, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
Assert.notNull(authorizedClient, "authorizedClient cannot be null");
Assert.notNull(request, "request cannot be null");
Assert.notNull(response, "response cannot be null");
Map<String, OAuth2AuthorizedClient> authorizedClients = this.getAuthorizedClients(request);
authorizedClients.put(authorizedClient.getClientRegistration().getRegistrationId(), authorizedClient);
request.getSession().setAttribute(this.sessionAttributeName, authorizedClients);
}
@Override
public void removeAuthorizedClient(String clientRegistrationId, Authentication principal,
HttpServletRequest request, HttpServletResponse response) {
Assert.hasText(clientRegistrationId, "clientRegistrationId cannot be empty");
Assert.notNull(request, "request cannot be null");
Map<String, OAuth2AuthorizedClient> authorizedClients = this.getAuthorizedClients(request);
if (!authorizedClients.isEmpty()) {
if (authorizedClients.remove(clientRegistrationId) != null) {
if (!authorizedClients.isEmpty()) {
request.getSession().setAttribute(this.sessionAttributeName, authorizedClients);
}
else {
request.getSession().removeAttribute(this.sessionAttributeName);
|
}
}
}
}
@SuppressWarnings("unchecked")
private Map<String, OAuth2AuthorizedClient> getAuthorizedClients(HttpServletRequest request) {
HttpSession session = request.getSession(false);
Map<String, OAuth2AuthorizedClient> authorizedClients = (session != null)
? (Map<String, OAuth2AuthorizedClient>) session.getAttribute(this.sessionAttributeName) : null;
if (authorizedClients == null) {
authorizedClients = new HashMap<>();
}
return authorizedClients;
}
}
|
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\HttpSessionOAuth2AuthorizedClientRepository.java
| 1
|
请完成以下Java代码
|
public class ApiKey extends ApiKeyInfo {
@Serial
private static final long serialVersionUID = -2313196723950490263L;
@NoXss
@Schema(description = "API key value", requiredMode = Schema.RequiredMode.REQUIRED)
private String value;
public ApiKey() {
super();
}
public ApiKey(ApiKeyId id) {
super(id);
}
public ApiKey(ApiKey apiKey) {
|
super(apiKey);
this.value = apiKey.getValue();
}
public ApiKey(ApiKeyInfo apiKeyInfo) {
super(apiKeyInfo);
this.value = null;
}
public ApiKey(ApiKeyInfo apiKeyInfo, String value) {
super(apiKeyInfo);
this.value = value;
}
}
|
repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\pat\ApiKey.java
| 1
|
请完成以下Java代码
|
public int size() {
return inputVariableContainer.getVariableNames().size();
}
@Override
public Collection<Object> values() {
Set<String> variableNames = inputVariableContainer.getVariableNames();
List<Object> values = new ArrayList<>(variableNames.size());
for (String key : variableNames) {
values.add(inputVariableContainer.getVariable(key));
}
return values;
}
@Override
public void putAll(Map<? extends String, ? extends Object> toMerge) {
throw new UnsupportedOperationException();
}
@Override
public Object remove(Object key) {
if (UNSTORED_KEYS.contains(key)) {
return null;
}
return defaultBindings.remove(key);
}
@Override
public void clear() {
throw new UnsupportedOperationException();
}
@Override
public boolean containsValue(Object value) {
throw new UnsupportedOperationException();
}
|
@Override
public boolean isEmpty() {
throw new UnsupportedOperationException();
}
public void addUnstoredKey(String unstoredKey) {
UNSTORED_KEYS.add(unstoredKey);
}
protected Map<String, Object> getVariables() {
if (this.scopeContainer instanceof VariableScope) {
return ((VariableScope) this.scopeContainer).getVariables();
}
return Collections.emptyMap();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\ScriptBindings.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private void prepareExternalStatusCreateRequest(@NonNull final Exchange exchange, @NonNull final JsonExternalStatus externalStatus)
{
final GRSRestAPIContext context = ProcessorHelper.getPropertyOrThrowError(exchange, GRSSignumConstants.ROUTE_PROPERTY_GRS_REST_API_CONTEXT, GRSRestAPIContext.class);
final JsonExternalSystemRequest request = context.getRequest();
final JsonStatusRequest jsonStatusRequest = JsonStatusRequest.builder()
.status(externalStatus)
.pInstanceId(request.getAdPInstanceId())
.build();
final ExternalStatusCreateCamelRequest camelRequest = ExternalStatusCreateCamelRequest.builder()
.jsonStatusRequest(jsonStatusRequest)
.externalSystemConfigType(getExternalSystemTypeCode())
.externalSystemChildConfigValue(request.getExternalSystemChildConfigValue())
.serviceValue(getServiceValue())
.build();
exchange.getIn().setBody(camelRequest, JsonExternalSystemRequest.class);
}
private void prepareHttpErrorResponse(@NonNull final Exchange exchange)
{
final JsonError jsonError = ErrorProcessor.processHttpErrorEncounteredResponse(exchange);
exchange.getIn().setBody(jsonError);
}
|
@Override
public String getServiceValue()
{
return "defaultRestAPIGRS";
}
@Override
public String getExternalSystemTypeCode()
{
return GRSSIGNUM_SYSTEM_NAME;
}
@Override
public String getEnableCommand()
{
return ENABLE_RESOURCE_ROUTE;
}
@Override
public String getDisableCommand()
{
return DISABLE_RESOURCE_ROUTE;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-grssignum\src\main\java\de\metas\camel\externalsystems\grssignum\from_grs\restapi\GRSRestAPIRouteBuilder.java
| 2
|
请完成以下Java代码
|
private final BigDecimal getOrderLineQtyEnteredTU(final I_C_Invoice_Candidate ic, final Set<Integer> seenIOLs)
{
BigDecimal qtyEnteredTU = BigDecimal.ZERO;
final List<I_M_InOutLine> iols = Services.get(IInvoiceCandDAO.class).retrieveInOutLinesForCandidate(ic, I_M_InOutLine.class);
if (iols.isEmpty()) // if no IOLs, fall back to the order line's qty
{
final I_C_OrderLine ol = InterfaceWrapperHelper.create(ic.getC_OrderLine(), I_C_OrderLine.class);
final BigDecimal olQtyEnteredTU = ol.getQtyEnteredTU();
if (olQtyEnteredTU != null) // safety
{
qtyEnteredTU = olQtyEnteredTU;
}
}
for (final I_M_InOutLine iol : iols)
{
//
// Just to be safe and prevent a possible bug, make sure the IOL IDs are unique
final int iolId = iol.getM_InOutLine_ID();
if (!seenIOLs.add(iolId))
{
continue;
}
if (!Services.get(IDocumentBL.class).isDocumentCompletedOrClosed(iol.getM_InOut()))
{
continue; // skip not-completed shipments
}
final BigDecimal iolQtyEnteredTU;
|
if (iol.isPackagingMaterial())
{
iolQtyEnteredTU = iol.getQtyEntered(); // the bound line is the PM line
}
else
{
iolQtyEnteredTU = iol.getQtyEnteredTU();
}
if (iolQtyEnteredTU != null) // safety
{
qtyEnteredTU = qtyEnteredTU.add(iolQtyEnteredTU);
}
}
return qtyEnteredTU;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\model\validator\C_Invoice_Candidate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public BigDecimal getNetWeight() {
return netWeight;
}
/**
* Sets the value of the netWeight property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setNetWeight(BigDecimal value) {
this.netWeight = value;
}
/**
* Gets the value of the factor property.
*
*/
public int getFactor() {
return factor;
}
/**
* Sets the value of the factor property.
*
*/
public void setFactor(int value) {
this.factor = value;
}
/**
* Gets the value of the notOtherwiseSpecified property.
*
* @return
* possible object is
* {@link String }
|
*
*/
public String getNotOtherwiseSpecified() {
return notOtherwiseSpecified;
}
/**
* Sets the value of the notOtherwiseSpecified property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNotOtherwiseSpecified(String value) {
this.notOtherwiseSpecified = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Hazardous.java
| 2
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setIsAllowOverdelivery (final boolean IsAllowOverdelivery)
{
set_Value (COLUMNNAME_IsAllowOverdelivery, IsAllowOverdelivery);
}
@Override
public boolean isAllowOverdelivery()
{
return get_ValueAsBoolean(COLUMNNAME_IsAllowOverdelivery);
}
@Override
public void setIsAutoProcess (final boolean IsAutoProcess)
{
set_Value (COLUMNNAME_IsAutoProcess, IsAutoProcess);
}
@Override
public boolean isAutoProcess()
{
return get_ValueAsBoolean(COLUMNNAME_IsAutoProcess);
}
@Override
public void setIsForbidAggCUsForDifferentOrders (final boolean IsForbidAggCUsForDifferentOrders)
{
set_Value (COLUMNNAME_IsForbidAggCUsForDifferentOrders, IsForbidAggCUsForDifferentOrders);
}
@Override
public boolean isForbidAggCUsForDifferentOrders()
{
return get_ValueAsBoolean(COLUMNNAME_IsForbidAggCUsForDifferentOrders);
}
@Override
public void setM_Picking_Config_ID (final int M_Picking_Config_ID)
{
if (M_Picking_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Picking_Config_ID, M_Picking_Config_ID);
|
}
@Override
public int getM_Picking_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Picking_Config_ID);
}
/**
* WEBUI_PickingTerminal_ViewProfile AD_Reference_ID=540772
* Reference name: WEBUI_PickingTerminal_ViewProfile
*/
public static final int WEBUI_PICKINGTERMINAL_VIEWPROFILE_AD_Reference_ID=540772;
/** groupByProduct = groupByProduct */
public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByProduct = "groupByProduct";
/** Group by Order = groupByOrder */
public static final String WEBUI_PICKINGTERMINAL_VIEWPROFILE_GroupByOrder = "groupByOrder";
@Override
public void setWEBUI_PickingTerminal_ViewProfile (final java.lang.String WEBUI_PickingTerminal_ViewProfile)
{
set_Value (COLUMNNAME_WEBUI_PickingTerminal_ViewProfile, WEBUI_PickingTerminal_ViewProfile);
}
@Override
public java.lang.String getWEBUI_PickingTerminal_ViewProfile()
{
return get_ValueAsString(COLUMNNAME_WEBUI_PickingTerminal_ViewProfile);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\picking\model\X_M_Picking_Config.java
| 1
|
请完成以下Java代码
|
protected Set<String> getTableNamesToSkipOnMigrationScriptsLogging()
{
return ImmutableSet.of(
I_C_Queue_WorkPackage.Table_Name,
I_C_Queue_WorkPackage_Log.Table_Name,
I_C_Queue_WorkPackage_Param.Table_Name
);
}
private void startQueueProcessors()
{
// task 04585: start queue processors only if we are running on the backend server.
// =>why not always run them?
// if we start it on clients without having a central monitoring-gathering point we never know what's going on
// => it can all be solved, but as of now isn't
if (!SpringContextHolder.instance.isSpringProfileActive(Profiles.PROFILE_App))
{
return;
}
if (StringUtils.toBoolean(System.getProperty(SYSTEM_PROPERTY_ASYNC_DISABLE)))
{
logger.warn("\n----------------------------------------------------------------------------------------------"
+ "\n Avoid starting asynchronous queue processors because " + SYSTEM_PROPERTY_ASYNC_DISABLE + "=true."
+ "\n----------------------------------------------------------------------------------------------");
return;
}
final int initDelayMillis = getInitDelayMillis();
Services.get(IQueueProcessorExecutorService.class).init(initDelayMillis);
}
/**
* Gets how many milliseconds to wait until to actually initialize the {@link IQueueProcessorExecutorService}.
* <p>
* Mainly we use this delay to make sure everything else is started before the queue processors will start to process.
*
* @return how many milliseconds to wait until to actually initialize the {@link IQueueProcessorExecutorService}.
*/
private int getInitDelayMillis()
{
// I will leave the default value of 3 minutes, which was the common time until #2894
return Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_ASYNC_INIT_DELAY_MILLIS, THREE_MINUTES);
}
@Override
protected void registerInterceptors(@NonNull final IModelValidationEngine engine)
{
engine.addModelValidator(new C_Queue_PackageProcessor());
engine.addModelValidator(new C_Queue_Processor());
engine.addModelValidator(new de.metas.lock.model.validator.Main());
engine.addModelValidator(new C_Async_Batch());
}
/**
* Init the async queue processor service on user login.
|
*/
@Override
public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
if (!Ini.isSwingClient())
{
return;
}
final int delayMillis = getInitDelayMillis();
Services.get(IQueueProcessorExecutorService.class).init(delayMillis);
}
/**
* Destroy all queueud processors on user logout.
*/
@Override
public void beforeLogout(final MFSession session)
{
if (!Ini.isSwingClient())
{
return;
}
Services.get(IQueueProcessorExecutorService.class).removeAllQueueProcessors();
}
@Override
protected List<Topic> getAvailableUserNotificationsTopics()
{
return ImmutableList.of(
Async_Constants.WORKPACKAGE_ERROR_USER_NOTIFICATIONS_TOPIC,
DataImportService.USER_NOTIFICATIONS_TOPIC);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\model\validator\Main.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private JsonMetasfreshId getSourceLocationMFIdByIdentifier(
@NonNull final String locationIdentifier,
@NonNull final JsonResponseBPartnerCompositeUpsertItem bpartnerUpsertResponseItem)
{
if (bpartnerUpsertResponseItem.getResponseLocationItems() == null || bpartnerUpsertResponseItem.getResponseLocationItems().isEmpty())
{
throw new RuntimeCamelException("Empty JsonResponseBPartnerCompositeUpsertItem.getResponseLocationItems! Location identifier: " + locationIdentifier);
}
return bpartnerUpsertResponseItem.getResponseLocationItems()
.stream()
.filter(locationRespItem -> locationIdentifier.equals(locationRespItem.getIdentifier()))
.map(JsonResponseUpsertItem::getMetasfreshId)
.filter(Objects::nonNull)
.findFirst()
.orElseThrow(() -> new RuntimeCamelException("No JsonMetasfreshId found for locationIdentifier: " + locationIdentifier));
}
@NonNull
private JsonMetasfreshId getFirstLocationMFId(@NonNull final JsonResponseBPartnerCompositeUpsertItem bpartnerUpsertResponseItem)
{
if (bpartnerUpsertResponseItem.getResponseLocationItems() == null || bpartnerUpsertResponseItem.getResponseLocationItems().isEmpty())
{
throw new RuntimeCamelException("The given JsonResponseBPartnerCompositeUpsertItem has no responseLocationItems!; bpartnerUpsertResponseItem=" + bpartnerUpsertResponseItem);
}
|
return bpartnerUpsertResponseItem.getResponseLocationItems()
.stream()
.map(JsonResponseUpsertItem::getMetasfreshId)
.filter(Objects::nonNull)
.findFirst()
.orElseThrow(() -> new RuntimeCamelException("No location JsonResponseUpsertItem found!"));
}
@NonNull
private JsonMetasfreshId getBPartnerMetasfreshId(@NonNull final JsonResponseBPartnerCompositeUpsertItem bpUpsertItem)
{
if (bpUpsertItem.getResponseBPartnerItem() == null || bpUpsertItem.getResponseBPartnerItem().getMetasfreshId() == null)
{
throw new RuntimeCamelException("ResponseBPartnerItem.JsonMetasfreshId is missing for bpUpsertItem: " + bpUpsertItem);
}
return bpUpsertItem.getResponseBPartnerItem().getMetasfreshId();
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\patient\processor\CreateBPRelationReqProcessor.java
| 2
|
请完成以下Java代码
|
public void store(MultipartFile file) {
try {
if (file.isEmpty()) {
throw new StorageException("Failed to store empty file " + file.getOriginalFilename());
}
Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
} catch (IOException e) {
throw new StorageException("Failed to store file " + file.getOriginalFilename(), e);
}
}
@Override
public Stream<Path> loadAll() {
try {
return Files.walk(this.rootLocation, 1)
.filter(path -> !path.equals(this.rootLocation))
.map(path -> this.rootLocation.relativize(path));
} catch (IOException e) {
throw new StorageException("Failed to read stored files", e);
}
}
@Override
public Path load(String filename) {
return rootLocation.resolve(filename);
}
@Override
public Resource loadAsResource(String filename) {
try {
Path file = load(filename);
Resource resource = new UrlResource(file.toUri());
if(resource.exists() || resource.isReadable()) {
return resource;
|
}
else {
throw new StorageFileNotFoundException("Could not read file: " + filename);
}
} catch (MalformedURLException e) {
throw new StorageFileNotFoundException("Could not read file: " + filename, e);
}
}
@Override
public void deleteAll() {
FileSystemUtils.deleteRecursively(rootLocation.toFile());
}
@Override
public void init() {
try {
Files.createDirectory(rootLocation);
} catch (IOException e) {
throw new StorageException("Could not initialize storage", e);
}
}
}
|
repos\SpringBootLearning-master\springboot-upload-file\src\main\java\com\forezp\storage\FileSystemStorageService.java
| 1
|
请完成以下Java代码
|
public static OrgMappingId ofRepoId(final int repoId)
{
return new OrgMappingId(repoId);
}
@Nullable
public static OrgMappingId ofRepoIdOrNull(@Nullable final Integer repoId)
{
return repoId != null && repoId > 0 ? new OrgMappingId(repoId) : null;
}
@Nullable
public static OrgMappingId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new OrgMappingId(repoId) : null;
}
public static Optional<OrgMappingId> optionalOfRepoId(final int repoId)
{
return Optional.ofNullable(ofRepoIdOrNull(repoId));
}
public static int toRepoId(@Nullable final OrgMappingId orgMappingId)
{
return toRepoIdOr(orgMappingId, -1);
}
|
public static int toRepoIdOr(@Nullable final OrgMappingId orgMappingId, final int defaultValue)
{
return orgMappingId != null ? orgMappingId.getRepoId() : defaultValue;
}
private OrgMappingId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_Org_Mapping_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(@Nullable final OrgMappingId o1, @Nullable final OrgMappingId o2)
{
return Objects.equals(o1, o2);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\OrgMappingId.java
| 1
|
请完成以下Java代码
|
public static final class ReadLines {
}
@Override
public void preStart() {
log.info("Starting ReadingActor {}", this);
}
@Override
public void postStop() {
log.info("Stopping ReadingActor {}", this);
}
@Override
public Receive createReceive() {
return receiveBuilder()
.match(ReadLines.class, r -> {
log.info("Received ReadLines message from " + getSender());
String[] lines = text.split("\n");
List<CompletableFuture> futures = new ArrayList<>();
for (int i = 0; i < lines.length; i++) {
String line = lines[i];
ActorRef wordCounterActorRef = getContext().actorOf(Props.create(WordCounterActor.class), "word-counter-" + i);
|
CompletableFuture<Object> future =
ask(wordCounterActorRef, new WordCounterActor.CountWords(line), 1000).toCompletableFuture();
futures.add(future);
}
Integer totalNumberOfWords = futures.stream()
.map(CompletableFuture::join)
.mapToInt(n -> (Integer) n)
.sum();
ActorRef printerActorRef = getContext().actorOf(Props.create(PrinterActor.class), "Printer-Actor");
printerActorRef.forward(new PrinterActor.PrintFinalResult(totalNumberOfWords), getContext());
// printerActorRef.tell(new PrinterActor.PrintFinalResult(totalNumberOfWords), getSelf());
})
.build();
}
}
|
repos\tutorials-master\akka-modules\akka-actors\src\main\java\com\baeldung\akkaactors\ReadingActor.java
| 1
|
请完成以下Java代码
|
public Entry<String, Object> next() {
Entry<String, Object> entry = delegate.next();
return new AbstractMap.SimpleEntry<>(entry.getKey(), cachingResolver.resolveProperty(entry.getKey()));
}
}
@Override
public void forEach(BiConsumer<? super String, ? super Object> action) {
delegate.forEach((k, v) -> action.accept(k, cachingResolver.resolveProperty(k)));
}
private class DecoratingEntryValueIterator implements Iterator<Object> {
private final Iterator<Entry<String, Object>> entryIterator;
DecoratingEntryValueIterator(Iterator<Entry<String, Object>> entryIterator) {
this.entryIterator = entryIterator;
|
}
@Override
public boolean hasNext() {
return entryIterator.hasNext();
}
@Override
public Object next() {
Entry<String, Object> entry = entryIterator.next();
return cachingResolver.resolveProperty(entry.getKey());
}
}
}
|
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\caching\EncryptableMapWrapper.java
| 1
|
请完成以下Java代码
|
private Step childJobOneStep() {
return new JobStepBuilder(new StepBuilder("childJobOneStep"))
.job(childJobOne())
.launcher(jobLauncher)
.repository(jobRepository)
.transactionManager(platformTransactionManager)
.build();
}
// 将任务转换为特殊的步骤
private Step childJobTwoStep() {
return new JobStepBuilder(new StepBuilder("childJobTwoStep"))
.job(childJobTwo())
.launcher(jobLauncher)
.repository(jobRepository)
.transactionManager(platformTransactionManager)
.build();
}
private Job childJobOne() {
return jobBuilderFactory.get("childJobOne")
.start(
stepBuilderFactory.get("childJobOneStep")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("subtask1。。。");
return RepeatStatus.FINISHED;
|
}).build()
).build();
}
private Job childJobTwo() {
return jobBuilderFactory.get("childJobTwo")
.start(
stepBuilderFactory.get("childJobTwoStep")
.tasklet((stepContribution, chunkContext) -> {
System.out.println("subtask2。。。");
return RepeatStatus.FINISHED;
}).build()
).build();
}
}
|
repos\springboot-demo-master\SpringBatch\src\main\java\com\et\batch\job\NestedJobDemo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SetTimerJobRetriesCmd implements Command<Void>, Serializable {
private static final long serialVersionUID = 1L;
protected final String jobId;
protected final int retries;
protected JobServiceConfiguration jobServiceConfiguration;
public SetTimerJobRetriesCmd(String jobId, int retries, JobServiceConfiguration jobServiceConfiguration) {
if (jobId == null || jobId.length() < 1) {
throw new FlowableIllegalArgumentException("The job id is mandatory, but '" + jobId + "' has been provided.");
}
if (retries < 0) {
throw new FlowableIllegalArgumentException("The number of job retries must be a non-negative Integer, but '" + retries + "' has been provided.");
}
this.jobId = jobId;
this.retries = retries;
this.jobServiceConfiguration = jobServiceConfiguration;
}
@Override
public Void execute(CommandContext commandContext) {
TimerJobEntity job = jobServiceConfiguration.getTimerJobEntityManager().findById(jobId);
|
if (job != null) {
job.setRetries(retries);
FlowableEventDispatcher eventDispatcher = jobServiceConfiguration.getEventDispatcher();
if (eventDispatcher != null && eventDispatcher.isEnabled()) {
eventDispatcher.dispatchEvent(FlowableJobEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, job),
jobServiceConfiguration.getEngineName());
}
} else {
throw new FlowableObjectNotFoundException("No timer job found with id '" + jobId + "'.", Job.class);
}
return null;
}
}
|
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\SetTimerJobRetriesCmd.java
| 2
|
请完成以下Java代码
|
public HistoricProcessInstanceReport createHistoricProcessInstanceReport() {
return new HistoricProcessInstanceReportImpl(commandExecutor);
}
public HistoricTaskInstanceReport createHistoricTaskInstanceReport() {
return new HistoricTaskInstanceReportImpl(commandExecutor);
}
public CleanableHistoricProcessInstanceReport createCleanableHistoricProcessInstanceReport() {
return new CleanableHistoricProcessInstanceReportImpl(commandExecutor);
}
public CleanableHistoricDecisionInstanceReport createCleanableHistoricDecisionInstanceReport() {
return new CleanableHistoricDecisionInstanceReportImpl(commandExecutor);
}
public CleanableHistoricCaseInstanceReport createCleanableHistoricCaseInstanceReport() {
return new CleanableHistoricCaseInstanceReportImpl(commandExecutor);
}
public CleanableHistoricBatchReport createCleanableHistoricBatchReport() {
return new CleanableHistoricBatchReportImpl(commandExecutor);
}
public HistoricBatchQuery createHistoricBatchQuery() {
return new HistoricBatchQueryImpl(commandExecutor);
}
public void deleteHistoricBatch(String batchId) {
commandExecutor.execute(new DeleteHistoricBatchCmd(batchId));
}
@Override
public HistoricDecisionInstanceStatisticsQuery createHistoricDecisionInstanceStatisticsQuery(String decisionRequirementsDefinitionId) {
|
return new HistoricDecisionInstanceStatisticsQueryImpl(decisionRequirementsDefinitionId, commandExecutor);
}
@Override
public HistoricExternalTaskLogQuery createHistoricExternalTaskLogQuery() {
return new HistoricExternalTaskLogQueryImpl(commandExecutor);
}
@Override
public String getHistoricExternalTaskLogErrorDetails(String historicExternalTaskLogId) {
return commandExecutor.execute(new GetHistoricExternalTaskLogErrorDetailsCmd(historicExternalTaskLogId));
}
public SetRemovalTimeSelectModeForHistoricProcessInstancesBuilder setRemovalTimeToHistoricProcessInstances() {
return new SetRemovalTimeToHistoricProcessInstancesBuilderImpl(commandExecutor);
}
public SetRemovalTimeSelectModeForHistoricDecisionInstancesBuilder setRemovalTimeToHistoricDecisionInstances() {
return new SetRemovalTimeToHistoricDecisionInstancesBuilderImpl(commandExecutor);
}
public SetRemovalTimeSelectModeForHistoricBatchesBuilder setRemovalTimeToHistoricBatches() {
return new SetRemovalTimeToHistoricBatchesBuilderImpl(commandExecutor);
}
public void setAnnotationForOperationLogById(String operationId, String annotation) {
commandExecutor.execute(new SetAnnotationForOperationLog(operationId, annotation));
}
public void clearAnnotationForOperationLogById(String operationId) {
commandExecutor.execute(new SetAnnotationForOperationLog(operationId, null));
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoryServiceImpl.java
| 1
|
请完成以下Java代码
|
static class RabbitDockerComposeConnectionDetails extends DockerComposeConnectionDetails
implements RabbitConnectionDetails {
private final RabbitEnvironment environment;
private final List<Address> addresses;
protected RabbitDockerComposeConnectionDetails(RunningService service) {
super(service);
this.environment = new RabbitEnvironment(service.env());
this.addresses = List.of(new Address(service.host(), service.ports().get(RABBITMQ_PORT)));
}
@Override
public @Nullable String getUsername() {
return this.environment.getUsername();
}
@Override
public @Nullable String getPassword() {
return this.environment.getPassword();
|
}
@Override
public String getVirtualHost() {
return "/";
}
@Override
public List<Address> getAddresses() {
return this.addresses;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\docker\compose\RabbitDockerComposeConnectionDetailsFactory.java
| 1
|
请完成以下Java代码
|
public int getProductId()
{
return shipmentSchedule.getM_Product_ID();
}
public TableRecordReference getReferenced()
{
return TableRecordReference.ofReferenced(shipmentSchedule);
}
public BigDecimal getQtyToDeliverOverride()
{
return shipmentSchedule.getQtyToDeliver_Override();
}
public int getBillBPartnerId()
{
return shipmentSchedule.getBill_BPartner_ID();
}
|
public DeliveryRule getDeliveryRule()
{
final IShipmentScheduleEffectiveBL shipmentScheduleBL = Services.get(IShipmentScheduleEffectiveBL.class);
return shipmentScheduleBL.getDeliveryRule(shipmentSchedule);
}
public void setDiscarded()
{
this.discarded = true;
}
public void removeFromGroup()
{
group.removeLine(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\inout\util\DeliveryLineCandidate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
protected void configure(HttpSecurity http) throws Exception {
http
// 配置请求地址的权限
.authorizeRequests()
.antMatchers("/test/demo").permitAll() // 所有用户可访问
.antMatchers("/test/admin").hasRole("ADMIN") // 需要 ADMIN 角色
.antMatchers("/test/normal").access("hasRole('ROLE_NORMAL')") // 需要 NORMAL 角色。
// 任何请求,访问的用户都需要经过认证
.anyRequest().authenticated()
.and()
// 设置 Form 表单登陆
.formLogin()
// .loginPage("/login") // 登陆 URL 地址
.permitAll() // 所有用户可访问
.and()
// 配置退出相关
.logout()
|
// .logoutUrl("/logout") // 退出 URL 地址
.permitAll(); // 所有用户可访问
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.
// 使用内存中的 InMemoryUserDetailsManager
inMemoryAuthentication()
// 不使用 PasswordEncoder 密码编码器
.passwordEncoder(NoOpPasswordEncoder.getInstance())
// 配置 admin 用户
.withUser("admin").password("admin").roles("ADMIN")
// 配置 normal 用户
.and().withUser("normal").password("normal").roles("NORMAL");
}
}
|
repos\SpringBoot-Labs-master\lab-01-spring-security\lab-01-springsecurity-demo-role\src\main\java\cn\iocoder\springboot\lab01\springsecurity\config\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public abstract class AbstractManager {
protected IdmEngineConfiguration idmEngineConfiguration;
public AbstractManager(IdmEngineConfiguration idmEngineConfiguration) {
this.idmEngineConfiguration = idmEngineConfiguration;
}
// Command scoped
protected CommandContext getCommandContext() {
return CommandContextUtil.getCommandContext();
}
protected <T> T getSession(Class<T> sessionClass) {
return getCommandContext().getSession(sessionClass);
}
// Engine scoped
protected IdmEngineConfiguration getIdmEngineConfiguration() {
return idmEngineConfiguration;
}
protected CommandExecutor getCommandExecutor() {
return getIdmEngineConfiguration().getCommandExecutor();
}
|
protected FlowableEventDispatcher getEventDispatcher() {
return getIdmEngineConfiguration().getEventDispatcher();
}
protected GroupEntityManager getGroupEntityManager() {
return getIdmEngineConfiguration().getGroupEntityManager();
}
protected MembershipEntityManager getMembershipEntityManager() {
return getIdmEngineConfiguration().getMembershipEntityManager();
}
protected IdentityInfoEntityManager getIdentityInfoEntityManager() {
return getIdmEngineConfiguration().getIdentityInfoEntityManager();
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\AbstractManager.java
| 1
|
请完成以下Java代码
|
public class ServiceException extends RuntimeException {
@Getter
private int errcode;
@Getter
private String errmsg;
public ServiceException(ResultCode resultCode) {
this(resultCode.getCode(), resultCode.getMsg());
}
public ServiceException(String message) {
super(message);
}
public ServiceException(Integer errcode, String errmsg) {
|
super(errmsg);
this.errcode = errcode;
this.errmsg = errmsg;
}
public ServiceException(String message, Throwable cause) {
super(message, cause);
}
public ServiceException(Throwable cause) {
super(cause);
}
public ServiceException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
|
repos\spring-boot-demo-master\demo-ldap\src\main\java\com\xkcoding\ldap\exception\ServiceException.java
| 1
|
请完成以下Java代码
|
public void cleanContainerTree(String ID) {
runURLRequest("ContainerTree", ID);
}
/**
* Clean Container Element for this ID
* @param ID for container element to clean
*/
public void cleanContainerElement(Integer ID) {
cleanContainerElement("" + ID);
}
/**
* Clean Container Element for this ID
* @param ID for container element to clean
*/
public void cleanContainerElement(String ID) {
runURLRequest("ContainerElement", ID);
}
private void runURLRequest(String cache, String ID) {
String thisURL = null;
for(int i=0; i<cacheURLs.length; i++) {
try {
thisURL = "http://" + cacheURLs[i] + "/cache/Service?Cache=" + cache + "&ID=" + ID;
URL url = new URL(thisURL);
Proxy thisProxy = Proxy.NO_PROXY;
URLConnection urlConn = url.openConnection(thisProxy);
urlConn.setUseCaches(false);
urlConn.connect();
Reader stream = new java.io.InputStreamReader(
urlConn.getInputStream());
StringBuffer srvOutput = new StringBuffer();
|
try {
int c;
while ( (c=stream.read()) != -1 )
srvOutput.append( (char)c );
} catch (Exception E2) {
E2.printStackTrace();
}
} catch (IOException E) {
if (log!=null)
log.warn("Can't clean cache at:" + thisURL + " be carefull, your deployment server may use invalid or old cache data!");
}
}
}
/**
* Converts JNP URL to http URL for cache cleanup
* @param JNPURL String with JNP URL from Context
* @return clean servername
*/
public static String convertJNPURLToCacheURL(String JNPURL) {
if (JNPURL.indexOf("jnp://")>=0) {
JNPURL = JNPURL.substring(JNPURL.indexOf("jnp://")+6);
}
if (JNPURL.indexOf(':')>=0) {
JNPURL = JNPURL.substring(0,JNPURL.indexOf(':'));
}
if (JNPURL.length()>0) {
return JNPURL;
} else {
return null;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\cm\CacheHandler.java
| 1
|
请完成以下Java代码
|
public Object getValue(ELContext context) {
return converter.convert(object, type);
}
/**
* Answer <code>null</code>.
*/
@Override
public String getExpressionString() {
return null;
}
/**
* Answer <code>false</code>.
*/
@Override
public boolean isLiteralText() {
return false;
}
/**
* Answer <code>null</code>.
*/
@Override
public Class<?> getType(ELContext context) {
return null;
}
/**
* Answer <code>true</code>.
*/
@Override
public boolean isReadOnly(ELContext context) {
return true;
|
}
/**
* Throw an exception.
*/
@Override
public void setValue(ELContext context, Object value) {
throw new ELException(LocalMessages.get("error.value.set.rvalue", "<object value expression>"));
}
@Override
public String toString() {
return "ValueExpression(" + object + ")";
}
@Override
public Class<?> getExpectedType() {
return type;
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\ObjectValueExpression.java
| 1
|
请完成以下Java代码
|
public void setM_CostElement(final org.compiere.model.I_M_CostElement M_CostElement)
{
set_ValueFromPO(COLUMNNAME_M_CostElement_ID, org.compiere.model.I_M_CostElement.class, M_CostElement);
}
@Override
public void setM_CostElement_ID (final int M_CostElement_ID)
{
if (M_CostElement_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_CostElement_ID, M_CostElement_ID);
}
@Override
public int getM_CostElement_ID()
{
return get_ValueAsInt(COLUMNNAME_M_CostElement_ID);
}
@Override
public org.compiere.model.I_C_ValidCombination getP_CostClearing_A()
{
|
return get_ValueAsPO(COLUMNNAME_P_CostClearing_Acct, org.compiere.model.I_C_ValidCombination.class);
}
@Override
public void setP_CostClearing_A(final org.compiere.model.I_C_ValidCombination P_CostClearing_A)
{
set_ValueFromPO(COLUMNNAME_P_CostClearing_Acct, org.compiere.model.I_C_ValidCombination.class, P_CostClearing_A);
}
@Override
public void setP_CostClearing_Acct (final int P_CostClearing_Acct)
{
set_Value (COLUMNNAME_P_CostClearing_Acct, P_CostClearing_Acct);
}
@Override
public int getP_CostClearing_Acct()
{
return get_ValueAsInt(COLUMNNAME_P_CostClearing_Acct);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostElement_Acct.java
| 1
|
请完成以下Java代码
|
public Response handleParamsInvalidException(SystemException e) {
log.error("系统错误:{}", e.getMessage());
return new Response().message(e.getMessage());
}
/**
* 统一处理请求参数校验(实体对象传参)
*
* @param e BindException
* @return FebsResponse
*/
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Response validExceptionHandler(BindException e) {
StringBuilder message = new StringBuilder();
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
for (FieldError error : fieldErrors) {
message.append(error.getField()).append(error.getDefaultMessage()).append(",");
}
message = new StringBuilder(message.substring(0, message.length() - 1));
return new Response().message(message.toString());
}
/**
* 统一处理请求参数校验(普通传参)
*
* @param e ConstraintViolationException
|
* @return FebsResponse
*/
@ExceptionHandler(value = ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Response handleConstraintViolationException(ConstraintViolationException e) {
StringBuilder message = new StringBuilder();
Set<ConstraintViolation<?>> violations = e.getConstraintViolations();
for (ConstraintViolation<?> violation : violations) {
Path path = violation.getPropertyPath();
String[] pathArr = StringUtils.splitByWholeSeparatorPreserveAllTokens(path.toString(), ".");
message.append(pathArr[1]).append(violation.getMessage()).append(",");
}
message = new StringBuilder(message.substring(0, message.length() - 1));
return new Response().message(message.toString());
}
@ExceptionHandler(value = UnauthorizedException.class)
@ResponseStatus(HttpStatus.FORBIDDEN)
public void handleUnauthorizedException(Exception e) {
log.error("权限不足,{}", e.getMessage());
}
}
|
repos\SpringAll-master\62.Spring-Boot-Shiro-JWT\src\main\java\com\example\demo\handler\GlobalExceptionHandler.java
| 1
|
请完成以下Java代码
|
public void setPercent (final int Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
@Override
public int getPercent()
{
return get_ValueAsInt(COLUMNNAME_Percent);
}
/**
* ReferenceDateType AD_Reference_ID=541989
* Reference name: ReferenceDateType
*/
public static final int REFERENCEDATETYPE_AD_Reference_ID=541989;
/** InvoiceDate = IV */
public static final String REFERENCEDATETYPE_InvoiceDate = "IV";
/** BLDate = BL */
public static final String REFERENCEDATETYPE_BLDate = "BL";
/** OrderDate = OD */
public static final String REFERENCEDATETYPE_OrderDate = "OD";
/** LCDate = LC */
public static final String REFERENCEDATETYPE_LCDate = "LC";
/** ETADate = ET */
public static final String REFERENCEDATETYPE_ETADate = "ET";
@Override
public void setReferenceDateType (final java.lang.String ReferenceDateType)
{
set_Value (COLUMNNAME_ReferenceDateType, ReferenceDateType);
}
@Override
public java.lang.String getReferenceDateType()
{
return get_ValueAsString(COLUMNNAME_ReferenceDateType);
|
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
/**
* Status AD_Reference_ID=541993
* Reference name: C_OrderPaySchedule_Status
*/
public static final int STATUS_AD_Reference_ID=541993;
/** Pending_Ref = PR */
public static final String STATUS_Pending_Ref = "PR";
/** Awaiting_Pay = WP */
public static final String STATUS_Awaiting_Pay = "WP";
/** Paid = P */
public static final String STATUS_Paid = "P";
@Override
public void setStatus (final java.lang.String Status)
{
set_Value (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderPaySchedule.java
| 1
|
请完成以下Java代码
|
public class AttributesKeyPatternsUtil
{
public static Set<AttributesKeyPattern> parseCommaSeparatedString(final String string)
{
return Splitter.on(",")
.trimResults()
.omitEmptyStrings()
.splitToList(string)
.stream()
.map(attributesKeyStr -> parseSinglePartPattern(attributesKeyStr))
.collect(ImmutableSet.toImmutableSet());
}
private static AttributesKeyPattern parseSinglePartPattern(final String string)
{
if ("<ALL_STORAGE_ATTRIBUTES_KEYS>".equals(string))
{
return AttributesKeyPattern.ALL;
}
else if ("<OTHER_STORAGE_ATTRIBUTES_KEYS>".equals(string))
{
return AttributesKeyPattern.OTHER;
}
else
{
final AttributesKeyPartPattern partPattern = AttributesKeyPartPattern.parseString(string);
return AttributesKeyPattern.ofPart(partPattern);
}
}
public static AttributesKeyPattern ofAttributeKey(@NonNull final AttributesKey attributesKey)
{
if (attributesKey.isAll())
{
return AttributesKeyPattern.ALL;
}
else if (attributesKey.isOther())
{
return AttributesKeyPattern.OTHER;
}
else if (attributesKey.isNone())
{
return AttributesKeyPattern.NONE;
}
else
{
final ImmutableList<AttributesKeyPartPattern> partPatterns = attributesKey.getParts()
.stream()
.map(AttributesKeyPartPattern::ofAttributesKeyPart)
.collect(ImmutableList.toImmutableList());
return AttributesKeyPattern.ofParts(partPatterns);
}
|
}
public static List<AttributesKeyMatcher> extractAttributesKeyMatchers(@NonNull final List<AttributesKeyPattern> patterns)
{
if (patterns.isEmpty())
{
return ImmutableList.of(matchingAll());
}
else if (!patterns.contains(AttributesKeyPattern.OTHER))
{
return patterns.stream()
.map(AttributesKeyPatternsUtil::matching)
.collect(ImmutableList.toImmutableList());
}
else
{
final ImmutableSet<AttributesKeyMatcher> otherMatchers = patterns.stream()
.filter(AttributesKeyPattern::isSpecific)
.map(AttributesKeyPatternsUtil::matching)
.collect(ImmutableSet.toImmutableSet());
final AttributesKeyMatcher othersMatcher = ExcludeAttributesKeyMatcher.of(otherMatchers);
return patterns.stream()
.map(pattern -> pattern.isOther() ? othersMatcher : matching(pattern))
.collect(ImmutableList.toImmutableList());
}
}
public static AttributesKeyMatcher matchingAll()
{
return AcceptAllAttributesKeyMatcher.instance;
}
public static AttributesKeyMatcher matching(@NonNull final AttributesKeyPattern pattern)
{
if (pattern.isAll())
{
return AcceptAllAttributesKeyMatcher.instance;
}
return StandardAttributesKeyPatternMatcher.of(pattern);
}
public static AttributesKeyMatcher matching(@NonNull final AttributesKey attributesKey)
{
return matching(ofAttributeKey(attributesKey));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\keys\AttributesKeyPatternsUtil.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public org.compiere.model.I_AD_Process getAD_Process_CustomQuery()
{
return get_ValueAsPO(COLUMNNAME_AD_Process_CustomQuery_ID, org.compiere.model.I_AD_Process.class);
}
@Override
public void setAD_Process_CustomQuery(final org.compiere.model.I_AD_Process AD_Process_CustomQuery)
{
set_ValueFromPO(COLUMNNAME_AD_Process_CustomQuery_ID, org.compiere.model.I_AD_Process.class, AD_Process_CustomQuery);
}
@Override
public void setAD_Process_CustomQuery_ID (final int AD_Process_CustomQuery_ID)
{
if (AD_Process_CustomQuery_ID < 1)
set_Value (COLUMNNAME_AD_Process_CustomQuery_ID, null);
else
set_Value (COLUMNNAME_AD_Process_CustomQuery_ID, AD_Process_CustomQuery_ID);
}
@Override
public int getAD_Process_CustomQuery_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Process_CustomQuery_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsAdditionalCustomQuery (final boolean IsAdditionalCustomQuery)
{
set_Value (COLUMNNAME_IsAdditionalCustomQuery, IsAdditionalCustomQuery);
}
@Override
public boolean isAdditionalCustomQuery()
{
|
return get_ValueAsBoolean(COLUMNNAME_IsAdditionalCustomQuery);
}
@Override
public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID)
{
if (LeichMehl_PluFile_ConfigGroup_ID < 1)
set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null);
else
set_ValueNoCheck (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID);
}
@Override
public int getLeichMehl_PluFile_ConfigGroup_ID()
{
return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID);
}
@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);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_LeichMehl_PluFile_ConfigGroup.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.