instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public AttachmentEntryDataResource retrieveDataResource(@NonNull final AttachmentEntryId attachmentEntryId)
{
return attachmentEntryRepository.retrieveAttachmentEntryDataResource(attachmentEntryId);
}
@Nullable
public AttachmentEntry getByFilenameOrNull(
@NonNull final Object referencedRecord,
@NonNull final String fileName)
{
final TableRecordReference recordReference = TableRecordReference.of(referencedRecord);
return attachmentEntryRepository
.getByReferencedRecord(recordReference)
.stream()
.filter(entry -> fileName.equals(entry.getFilename()))
.findFirst()
.orElse(null);
}
public void updateData(
@NonNull final AttachmentEntryId attachmentEntryId,
final byte[] data)
{
attachmentEntryRepository.updateAttachmentEntryData(attachmentEntryId, data);
}
@NonNull
public Stream<EmailAttachment> streamEmailAttachments(@NonNull final TableRecordReference recordRef, @Nullable final String tagName)
{
return attachmentEntryRepository.getByReferencedRecord(recordRef)
.stream()
.filter(attachmentEntry -> Check.isBlank(tagName) || attachmentEntry.getTags().hasTag(tagName))
.map(attachmentEntry -> EmailAttachment.builder()
.filename(attachmentEntry.getFilename())
.attachmentDataSupplier(() -> retrieveData(attachmentEntry.getId()))
.build());
}
/**
* Persist the given {@code attachmentEntry} as-is.
* Warning: e.g. tags or referenced records that are persisted before this method is called, but are not part of the given {@code attachmentEntry} are dropped.
*/
public void save(@NonNull final AttachmentEntry attachmentEntry)
{
attachmentEntryRepository.save(attachmentEntry);
}
@Value
public static class AttachmentEntryQuery
{
List<String> tagsSetToTrue;
|
List<String> tagsSetToAnyValue;
Object referencedRecord;
String mimeType;
@Builder
private AttachmentEntryQuery(
@Singular("tagSetToTrue") final List<String> tagsSetToTrue,
@Singular("tagSetToAnyValue") final List<String> tagsSetToAnyValue,
@Nullable final String mimeType,
@NonNull final Object referencedRecord)
{
this.referencedRecord = referencedRecord;
this.mimeType = mimeType;
this.tagsSetToTrue = tagsSetToTrue;
this.tagsSetToAnyValue = tagsSetToAnyValue;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryService.java
| 1
|
请完成以下Java代码
|
public void setPostingType (java.lang.String PostingType)
{
set_ValueNoCheck (COLUMNNAME_PostingType, PostingType);
}
/** Get Buchungsart.
@return Die Art des gebuchten Betrages dieser Transaktion
*/
@Override
public java.lang.String getPostingType ()
{
return (java.lang.String)get_Value(COLUMNNAME_PostingType);
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_ValueNoCheck (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** 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();
}
/** Set SubLine ID.
@param SubLine_ID
Transaction sub line ID (internal)
*/
@Override
public void setSubLine_ID (int SubLine_ID)
{
if (SubLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_SubLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_SubLine_ID, Integer.valueOf(SubLine_ID));
}
/** Get SubLine ID.
@return Transaction sub line ID (internal)
*/
@Override
public int getSubLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SubLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-gen\de\metas\acct\model\X_Fact_Acct_ActivityChangeRequest_Source_v.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DubboConfigsMetadata extends AbstractDubboMetadata {
public Map<String, Map<String, Map<String, Object>>> configs() {
Map<String, Map<String, Map<String, Object>>> configsMap = new LinkedHashMap<>();
addDubboConfigBeans(ApplicationConfig.class, configsMap);
addDubboConfigBeans(ConsumerConfig.class, configsMap);
addDubboConfigBeans(MethodConfig.class, configsMap);
addDubboConfigBeans(ModuleConfig.class, configsMap);
addDubboConfigBeans(MonitorConfig.class, configsMap);
addDubboConfigBeans(ProtocolConfig.class, configsMap);
addDubboConfigBeans(ProviderConfig.class, configsMap);
addDubboConfigBeans(ReferenceConfig.class, configsMap);
addDubboConfigBeans(RegistryConfig.class, configsMap);
addDubboConfigBeans(ServiceConfig.class, configsMap);
return configsMap;
}
private void addDubboConfigBeans(Class<? extends AbstractConfig> dubboConfigClass,
Map<String, Map<String, Map<String, Object>>> configsMap) {
|
Map<String, ? extends AbstractConfig> dubboConfigBeans = beansOfTypeIncludingAncestors(applicationContext, dubboConfigClass);
String name = dubboConfigClass.getSimpleName();
Map<String, Map<String, Object>> beansMetadata = new TreeMap<>();
for (Map.Entry<String, ? extends AbstractConfig> entry : dubboConfigBeans.entrySet()) {
String beanName = entry.getKey();
AbstractConfig configBean = entry.getValue();
Map<String, Object> configBeanMeta = resolveBeanMetadata(configBean);
beansMetadata.put(beanName, configBeanMeta);
}
configsMap.put(name, beansMetadata);
}
}
|
repos\dubbo-spring-boot-project-master\dubbo-spring-boot-compatible\actuator\src\main\java\org\apache\dubbo\spring\boot\actuate\endpoint\metadata\DubboConfigsMetadata.java
| 2
|
请完成以下Java代码
|
protected void validateType(Class<?> type, DeserializationTypeValidator validator) {
if (validator != null) {
// validate the outer class
if (!type.isPrimitive()) {
Class<?> typeToValidate = type;
if (type.isArray()) {
typeToValidate = type.getComponentType();
}
String className = typeToValidate.getName();
if (!validator.validate(className)) {
throw new SpinRuntimeException("The class '" + className + "' is not whitelisted for deserialization.");
}
}
}
}
@Override
public <T> T mapInternalToJava(Object parameter, String classIdentifier) {
return mapInternalToJava(parameter, classIdentifier, null);
}
@SuppressWarnings("unchecked")
@Override
public <T> T mapInternalToJava(Object parameter, String classIdentifier, DeserializationTypeValidator validator) {
ensureNotNull("Parameter", parameter);
ensureNotNull("classIdentifier", classIdentifier);
try {
Class<?> javaClass = SpinReflectUtil.loadClass(classIdentifier, dataFormat);
|
return (T) mapInternalToJava(parameter, javaClass, validator);
}
catch (Exception e) {
throw LOG.unableToDeserialize(parameter, classIdentifier, e);
}
}
protected Marshaller getMarshaller(Class<?> parameter) throws JAXBException {
JaxBContextProvider jaxBContextProvider = dataFormat.getJaxBContextProvider();
return jaxBContextProvider.createMarshaller(parameter);
}
protected Unmarshaller getUnmarshaller(Class<?> parameter) throws JAXBException {
JaxBContextProvider jaxBContextProvider = dataFormat.getJaxBContextProvider();
return jaxBContextProvider.createUnmarshaller(parameter);
}
}
|
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\format\DomXmlDataFormatMapper.java
| 1
|
请完成以下Java代码
|
public boolean isOrdered ()
{
Object oo = get_Value(COLUMNNAME_IsOrdered);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Telefon.
@param Phone
Beschreibt eine Telefon Nummer
*/
@Override
public void setPhone (java.lang.String Phone)
{
throw new IllegalArgumentException ("Phone is virtual column"); }
/** Get Telefon.
@return Beschreibt eine Telefon Nummer
*/
@Override
public java.lang.String getPhone ()
{
return (java.lang.String)get_Value(COLUMNNAME_Phone);
}
/** Set Anrufdatum.
@param PhonecallDate Anrufdatum */
@Override
public void setPhonecallDate (java.sql.Timestamp PhonecallDate)
{
set_Value (COLUMNNAME_PhonecallDate, PhonecallDate);
}
/** Get Anrufdatum.
@return Anrufdatum */
@Override
public java.sql.Timestamp getPhonecallDate ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallDate);
}
/** Set Erreichbar bis.
@param PhonecallTimeMax Erreichbar bis */
@Override
public void setPhonecallTimeMax (java.sql.Timestamp PhonecallTimeMax)
{
|
set_Value (COLUMNNAME_PhonecallTimeMax, PhonecallTimeMax);
}
/** Get Erreichbar bis.
@return Erreichbar bis */
@Override
public java.sql.Timestamp getPhonecallTimeMax ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMax);
}
/** Set Erreichbar von.
@param PhonecallTimeMin Erreichbar von */
@Override
public void setPhonecallTimeMin (java.sql.Timestamp PhonecallTimeMin)
{
set_Value (COLUMNNAME_PhonecallTimeMin, PhonecallTimeMin);
}
/** Get Erreichbar von.
@return Erreichbar von */
@Override
public java.sql.Timestamp getPhonecallTimeMin ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_PhonecallTimeMin);
}
/** Set Kundenbetreuer.
@param SalesRep_ID Kundenbetreuer */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Kundenbetreuer.
@return Kundenbetreuer */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Phonecall_Schedule.java
| 1
|
请完成以下Java代码
|
public abstract class MigratingProcessElementInstance implements MigratingInstance {
protected MigrationInstruction migrationInstruction;
protected ScopeImpl sourceScope;
protected ScopeImpl targetScope;
// changes from source to target scope during migration
protected ScopeImpl currentScope;
protected MigratingScopeInstance parentInstance;
public ScopeImpl getSourceScope() {
return sourceScope;
}
public ScopeImpl getTargetScope() {
return targetScope;
}
public ScopeImpl getCurrentScope() {
return currentScope;
}
public MigrationInstruction getMigrationInstruction() {
return migrationInstruction;
}
public MigratingScopeInstance getParent() {
return parentInstance;
}
|
public boolean migratesTo(ScopeImpl other) {
return other == targetScope;
}
public abstract void setParent(MigratingScopeInstance parentInstance);
public abstract void addMigratingDependentInstance(MigratingInstance migratingInstance);
public abstract ExecutionEntity resolveRepresentativeExecution();
public MigratingActivityInstance getClosestAncestorActivityInstance() {
MigratingScopeInstance ancestorInstance = parentInstance;
while (!(ancestorInstance instanceof MigratingActivityInstance)) {
ancestorInstance = ancestorInstance.getParent();
}
return (MigratingActivityInstance) ancestorInstance;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\MigratingProcessElementInstance.java
| 1
|
请完成以下Java代码
|
public <T extends RepoIdAware> T getParameterAsRepoId(@NonNull final Class<T> type)
{
return RepoIdAwares.ofRepoIdOrNull(getParameterAsInt(-1), type);
}
public int getParameter_ToAsInt()
{
return getParameter_ToAsInt(0);
}
public int getParameter_ToAsInt(final int defaultValueWhenNull)
{
return toInt(m_Parameter_To, defaultValueWhenNull);
}
private static int toInt(@Nullable final Object value, final int defaultValueWhenNull)
{
if (value == null)
{
return defaultValueWhenNull;
}
else if (value instanceof Number)
{
return ((Number)value).intValue();
}
else if (value instanceof RepoIdAware)
{
return ((RepoIdAware)value).getRepoId();
}
else
{
final BigDecimal bd = new BigDecimal(value.toString());
return bd.intValue();
}
}
public boolean getParameterAsBoolean()
{
return StringUtils.toBoolean(m_Parameter);
}
@Nullable
public Boolean getParameterAsBooleanOrNull()
{
return StringUtils.toBoolean(m_Parameter, null);
}
@Nullable
public Boolean getParameterAsBoolean(@Nullable Boolean defaultValue)
{
return StringUtils.toBoolean(m_Parameter, defaultValue);
}
public boolean getParameter_ToAsBoolean()
{
return StringUtils.toBoolean(m_Parameter_To);
}
@Nullable
public Timestamp getParameterAsTimestamp()
{
return TimeUtil.asTimestamp(m_Parameter);
}
@Nullable
public Timestamp getParameter_ToAsTimestamp()
{
return TimeUtil.asTimestamp(m_Parameter_To);
}
@Nullable
public LocalDate getParameterAsLocalDate()
{
return TimeUtil.asLocalDate(m_Parameter);
}
@Nullable
public LocalDate getParameter_ToAsLocalDate()
{
return TimeUtil.asLocalDate(m_Parameter_To);
}
@Nullable
public ZonedDateTime getParameterAsZonedDateTime()
{
return TimeUtil.asZonedDateTime(m_Parameter);
}
@Nullable
public Instant getParameterAsInstant()
{
return TimeUtil.asInstant(m_Parameter);
}
|
@Nullable
public ZonedDateTime getParameter_ToAsZonedDateTime()
{
return TimeUtil.asZonedDateTime(m_Parameter_To);
}
@Nullable
public BigDecimal getParameterAsBigDecimal()
{
return toBigDecimal(m_Parameter);
}
@Nullable
public BigDecimal getParameter_ToAsBigDecimal()
{
return toBigDecimal(m_Parameter_To);
}
@Nullable
private static BigDecimal toBigDecimal(@Nullable final Object value)
{
if (value == null)
{
return null;
}
else if (value instanceof BigDecimal)
{
return (BigDecimal)value;
}
else if (value instanceof Integer)
{
return BigDecimal.valueOf((Integer)value);
}
else
{
return new BigDecimal(value.toString());
}
}
} // ProcessInfoParameter
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessInfoParameter.java
| 1
|
请完成以下Java代码
|
protected void logInternalServerAndOtherStatusCodes(Throwable throwable, int statusCode) {
if (isPersistenceConnectionError(throwable)) {
logError(String.valueOf(statusCode), getExceptionStacktrace(throwable));
return;
}
logWarn(String.valueOf(statusCode), getExceptionStacktrace(throwable));
}
protected boolean isPersistenceConnectionError(Throwable throwable) {
boolean isPersistenceException = (throwable instanceof ProcessEnginePersistenceException);
if (!isPersistenceException) {
return false;
}
SQLException sqlException = getSqlException((ProcessEnginePersistenceException) throwable);
if (sqlException == null) {
return false;
}
|
String sqlState = sqlException.getSQLState();
return sqlState != null && sqlState.startsWith(PERSISTENCE_CONNECTION_ERROR_CLASS);
}
protected SQLException getSqlException(ProcessEnginePersistenceException e) {
boolean hasTwoCauses = e.getCause() != null && e.getCause().getCause() != null;
if (!hasTwoCauses) {
return null;
}
Throwable cause = e.getCause().getCause();
return cause instanceof SQLException ? (SQLException) cause : null;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\exception\ExceptionLogger.java
| 1
|
请完成以下Java代码
|
private static boolean computeIsHighVolume(@NonNull final ReferenceId diplayType)
{
final int displayTypeInt = diplayType.getRepoId();
return DisplayType.TableDir != displayTypeInt && DisplayType.Table != displayTypeInt && DisplayType.List != displayTypeInt && DisplayType.Button != displayTypeInt;
}
/**
* Advice the lookup to show all records on which current user has at least read only access
*/
public SqlLookupDescriptorFactory setReadOnlyAccess()
{
this.requiredAccess = Access.READ;
return this;
}
private Access getRequiredAccess(@NonNull final TableName tableName)
{
if (requiredAccess != null)
{
return requiredAccess;
}
// AD_Client_ID/AD_Org_ID (security fields): shall display only those entries on which current user has read-write access
if (I_AD_Client.Table_Name.equals(tableName.getAsString())
|| I_AD_Org.Table_Name.equals(tableName.getAsString()))
{
return Access.WRITE;
|
}
// Default: all entries on which current user has at least readonly access
return Access.READ;
}
SqlLookupDescriptorFactory addValidationRules(final Collection<IValidationRule> validationRules)
{
this.filtersBuilder.addFilter(validationRules, null);
return this;
}
SqlLookupDescriptorFactory setPageLength(final Integer pageLength)
{
this.pageLength = pageLength;
return this;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlLookupDescriptorFactory.java
| 1
|
请完成以下Java代码
|
public int getM_Attribute_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Attribute_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_M_AttributeSetExclude getM_AttributeSetExclude() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_AttributeSetExclude_ID, org.compiere.model.I_M_AttributeSetExclude.class);
}
@Override
public void setM_AttributeSetExclude(org.compiere.model.I_M_AttributeSetExclude M_AttributeSetExclude)
{
set_ValueFromPO(COLUMNNAME_M_AttributeSetExclude_ID, org.compiere.model.I_M_AttributeSetExclude.class, M_AttributeSetExclude);
}
/** Set Exclude Attribute Set.
@param M_AttributeSetExclude_ID
Exclude the ability to enter Attribute Sets
*/
@Override
public void setM_AttributeSetExclude_ID (int M_AttributeSetExclude_ID)
{
if (M_AttributeSetExclude_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExclude_ID, Integer.valueOf(M_AttributeSetExclude_ID));
}
/** Get Exclude Attribute Set.
@return Exclude the ability to enter Attribute Sets
*/
@Override
public int getM_AttributeSetExclude_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExclude_ID);
if (ii == null)
return 0;
return ii.intValue();
|
}
/** Set Exclude attribute.
@param M_AttributeSetExcludeLine_ID
Only excludes selected attributes from the attribute set
*/
@Override
public void setM_AttributeSetExcludeLine_ID (int M_AttributeSetExcludeLine_ID)
{
if (M_AttributeSetExcludeLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExcludeLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_AttributeSetExcludeLine_ID, Integer.valueOf(M_AttributeSetExcludeLine_ID));
}
/** Get Exclude attribute.
@return Only excludes selected attributes from the attribute set
*/
@Override
public int getM_AttributeSetExcludeLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_AttributeSetExcludeLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_M_AttributeSetExcludeLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getBatchType() {
return batchType;
}
public void setBatchType(String batchType) {
this.batchType = batchType;
}
@ApiModelProperty(example = "1:22:MP")
public String getSearchKey() {
return searchKey;
}
public void setSearchKey(String searchKey) {
this.searchKey = searchKey;
}
@ApiModelProperty(example = "1:24:MP")
public String getSearchKey2() {
return searchKey2;
}
public void setSearchKey2(String searchKey2) {
this.searchKey2 = searchKey2;
}
@ApiModelProperty(example = "2020-06-03T22:05:05.474+0000")
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@ApiModelProperty(example = "2020-06-03T22:05:05.474+0000")
public Date getCompleteTime() {
return completeTime;
}
|
public void setCompleteTime(Date completeTime) {
this.completeTime = completeTime;
}
@ApiModelProperty(example = "completed")
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "null")
public String getTenantId() {
return tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\management\BatchResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class DesadvParser
{
@NonNull
public static DesadvLines getDesadvLinesEnforcingSinglePacks(@NonNull final EDIExpDesadvType desadvType)
{
return DesadvLines.builder()
.lineId2LineWithPacks(getLinesWithPacks(desadvType.getEDIExpDesadvPack()))
.lineId2LineWithNoPacks(getLinesWithNoPacks(desadvType.getEDIExpDesadvLineWithNoPack()))
.build();
}
@NonNull
private static Map<Integer, DesadvLineWithPacks> getLinesWithPacks(@NonNull final List<EDIExpDesadvPackType> packs)
{
final Map<Integer, List<SinglePack>> lineIdToPacksCollector = new HashMap<>();
final Map<Integer, EDIExpDesadvLineType> lineIdToLine = new HashMap<>();
packs.forEach(pack -> {
final SinglePack singlePack = SinglePack.of(pack);
final List<SinglePack> packsForLine = new ArrayList<>();
packsForLine.add(singlePack);
lineIdToPacksCollector.merge(singlePack.getDesadvLineID(), packsForLine, (old, newList) -> {
old.addAll(newList);
return old;
});
lineIdToLine.put(singlePack.getDesadvLineID(), singlePack.getDesadvLine());
|
});
final ImmutableMap.Builder<Integer, DesadvLineWithPacks> lineWithPacksCollector = ImmutableMap.builder();
lineIdToLine.forEach((desadvLineID, desadvLine) -> {
final DesadvLineWithPacks lineWithPacks = DesadvLineWithPacks.builder()
.desadvLine(desadvLine)
.singlePacks(lineIdToPacksCollector.get(desadvLineID))
.build();
lineWithPacksCollector.put(desadvLineID, lineWithPacks);
});
return lineWithPacksCollector.build();
}
@NonNull
private static Map<Integer, EDIExpDesadvLineType> getLinesWithNoPacks(@NonNull final List<EDIExpDesadvLineWithNoPackType> lineWithNoPacks)
{
return lineWithNoPacks.stream()
.map(EDIExpDesadvLineWithNoPackType::getEDIDesadvLineID)
.collect(ImmutableMap.toImmutableMap(desadvLine -> desadvLine.getEDIDesadvLineID().intValue(), Function.identity()));
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\desadvexport\helper\DesadvParser.java
| 2
|
请完成以下Java代码
|
public void setEmail(String userEmail) {
this.email = userEmail;
}
@CamundaQueryParam("emailLike")
public void setEmailLike(String userEmailLike) {
this.emailLike = userEmailLike;
}
@CamundaQueryParam("memberOfGroup")
public void setMemberOfGroup(String memberOfGroup) {
this.memberOfGroup = memberOfGroup;
}
@CamundaQueryParam("potentialStarter")
public void setPotentialStarter(String potentialStarter) {
this.potentialStarter = potentialStarter;
}
@CamundaQueryParam("memberOfTenant")
public void setMemberOfTenant(String tenantId) {
this.tenantId = tenantId;
}
@Override
protected boolean isValidSortByValue(String value) {
return VALID_SORT_BY_VALUES.contains(value);
}
@Override
protected UserQuery createNewQuery(ProcessEngine engine) {
return engine.getIdentityService().createUserQuery();
}
@Override
protected void applyFilters(UserQuery query) {
if (id != null) {
query.userId(id);
}
if(idIn != null) {
query.userIdIn(idIn);
}
if (firstName != null) {
query.userFirstName(firstName);
}
if (firstNameLike != null) {
query.userFirstNameLike(firstNameLike);
}
|
if (lastName != null) {
query.userLastName(lastName);
}
if (lastNameLike != null) {
query.userLastNameLike(lastNameLike);
}
if (email != null) {
query.userEmail(email);
}
if (emailLike != null) {
query.userEmailLike(emailLike);
}
if (memberOfGroup != null) {
query.memberOfGroup(memberOfGroup);
}
if (potentialStarter != null) {
query.potentialStarter(potentialStarter);
}
if (tenantId != null) {
query.memberOfTenant(tenantId);
}
}
@Override
protected void applySortBy(UserQuery query, String sortBy, Map<String, Object> parameters, ProcessEngine engine) {
if (sortBy.equals(SORT_BY_USER_ID_VALUE)) {
query.orderByUserId();
} else if (sortBy.equals(SORT_BY_USER_FIRSTNAME_VALUE)) {
query.orderByUserFirstName();
} else if (sortBy.equals(SORT_BY_USER_LASTNAME_VALUE)) {
query.orderByUserLastName();
} else if (sortBy.equals(SORT_BY_USER_EMAIL_VALUE)) {
query.orderByUserEmail();
}
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\identity\UserQueryDto.java
| 1
|
请完成以下Java代码
|
public Optional<String> getCorrelationKey() {
return correlationKey;
}
/**
* Creates builder to build {@link ThrowMessage}.
* @return created builder
*/
public static INameStage builder() {
return new ThrowMessagBuilder();
}
/**
* Definition of a stage for staged builder.
*/
public interface INameStage {
/**
* Builder method for name parameter.
* @param name field to set
* @return builder
*/
public IBuildStage name(String name);
}
/**
* Definition of a stage for staged builder.
*/
public interface IBuildStage {
/**
* Builder method for payload parameter.
* @param payload field to set
* @return builder
*/
public IBuildStage payload(Optional<Map<String, Object>> payload);
/**
* Builder method for businessKey parameter.
* @param businessKey field to set
* @return builder
*/
public IBuildStage businessKey(Optional<String> businessKey);
/**
* Builder method for correlationKey parameter.
* @param correlationKey field to set
* @return builder
*/
public IBuildStage correlationKey(Optional<String> correlationKey);
/**
* Builder method of the builder.
* @return built class
*/
public ThrowMessage build();
}
/**
* Builder to build {@link ThrowMessage}.
*/
public static final class ThrowMessagBuilder implements INameStage, IBuildStage {
private String name;
private Optional<Map<String, Object>> payload = Optional.empty();
private Optional<String> businessKey = Optional.empty();
|
private Optional<String> correlationKey = Optional.empty();
private ThrowMessagBuilder() {}
@Override
public IBuildStage name(String name) {
this.name = name;
return this;
}
@Override
public IBuildStage payload(Optional<Map<String, Object>> payload) {
this.payload = payload;
return this;
}
@Override
public IBuildStage businessKey(Optional<String> businessKey) {
this.businessKey = businessKey;
return this;
}
@Override
public IBuildStage correlationKey(Optional<String> correlationKey) {
this.correlationKey = correlationKey;
return this;
}
@Override
public ThrowMessage build() {
return new ThrowMessage(this);
}
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\delegate\ThrowMessage.java
| 1
|
请完成以下Java代码
|
protected String doIt() throws IOException
{
final String fileNameSuffix = getDateAcctFrom() + "_" + getDateAcctTo();
final List<ElementValueId> accountIds = factAcctDAO.retrieveAccountsForTimeFrame(p_C_AcctSchema_ID, p_DateAcctFrom, p_DateAcctTo);
final List<File> files = new ArrayList<>();
for (final ElementValueId accountId : accountIds)
{
final String sql = getSql(accountId);
final ElementValue ev = elementValueService.getById(accountId);
final String fileName = ev.getValue() + "_" + fileNameSuffix;
final JdbcExcelExporter jdbcExcelExporter = JdbcExcelExporter.builder()
.ctx(getCtx())
.translateHeaders(true)
.applyFormatting(true)
.fileNamePrefix(fileName)
.build();
spreadsheetExporterService.processDataFromSQL(sql, Evaluatees.empty(), jdbcExcelExporter);
final File resultFile = jdbcExcelExporter.getResultFile();
files.add(resultFile);
}
final String zipFileName = getDateAcctFrom() + "_" + getDateAcctTo() + ".zip";
final File zipFile = FileUtil.zip(files);
getResult().setReportData(zipFile, zipFileName);
return MSG_OK;
}
private String getSql(final ElementValueId accountId)
{
return "SELECT * FROM "
+ p_Function
+ "("
+ "p_Account_ID := " + accountId.getRepoId()
|
+ ", "
+ "p_C_AcctSchema_ID := " + p_C_AcctSchema_ID.getRepoId()
+ ", "
+ "p_DateAcctFrom := '" + getDateAcctFrom()
+ "', "
+ "p_DateAcctTo := '" + getDateAcctTo()
+ "')";
}
@Nullable
private LocalDate getDateAcctFrom()
{
final ZoneId zoneId = orgDAO.getTimeZone(Env.getOrgId());
return asLocalDate(p_DateAcctFrom, zoneId);
}
@Nullable
private LocalDate getDateAcctTo()
{
final ZoneId zoneId = orgDAO.getTimeZone(Env.getOrgId());
return asLocalDate(p_DateAcctTo, zoneId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\ExportAccountInfos.java
| 1
|
请完成以下Java代码
|
public Integer getConcurrency() {
return this.concurrency;
}
static class TopicCreation {
private final boolean shouldCreateTopics;
private final int numPartitions;
private final short replicationFactor;
TopicCreation(@Nullable Boolean shouldCreate, @Nullable Integer numPartitions, @Nullable Short replicationFactor) {
this.shouldCreateTopics = shouldCreate == null || shouldCreate;
this.numPartitions = numPartitions == null ? 1 : numPartitions;
this.replicationFactor = replicationFactor == null ? -1 : replicationFactor;
}
TopicCreation() {
this.shouldCreateTopics = true;
this.numPartitions = 1;
this.replicationFactor = -1;
}
TopicCreation(boolean shouldCreateTopics) {
this.shouldCreateTopics = shouldCreateTopics;
this.numPartitions = 1;
|
this.replicationFactor = -1;
}
public int getNumPartitions() {
return this.numPartitions;
}
public short getReplicationFactor() {
return this.replicationFactor;
}
public boolean shouldCreateTopics() {
return this.shouldCreateTopics;
}
}
}
|
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicConfiguration.java
| 1
|
请完成以下Java代码
|
private static final class MenuResultItem extends ResultItemWrapper<MTreeNode>
{
public MenuResultItem(final MTreeNode node)
{
super(node);
}
@Override
public String getText()
{
return getValue().getName();
}
public Icon getIcon()
{
final String iconName = getValue().getIconName();
return Images.getImageIcon2(iconName);
}
}
/**
* Source of {@link MenuResultItem}s.
*/
private static final class MenuResultItemSource implements org.compiere.swing.autocomplete.ResultItemSource
{
public static MenuResultItemSource forRootNode(final MTreeNode root)
{
final Enumeration<?> nodesEnum = root.preorderEnumeration();
final List<MenuResultItem> items = new ArrayList<>();
while (nodesEnum.hasMoreElements())
{
final MTreeNode node = (MTreeNode)nodesEnum.nextElement();
if (node == root)
{
continue;
}
if (node.isSummary())
{
continue;
}
final MenuResultItem item = new MenuResultItem(node);
items.add(item);
}
return new MenuResultItemSource(items);
}
private final ImmutableList<MenuResultItem> items;
private MenuResultItemSource(final List<MenuResultItem> items)
{
super();
this.items = ImmutableList.copyOf(items);
}
@Override
public List<MenuResultItem> query(final String searchText, final int limit)
{
return items;
}
}
/**
* {@link MenuResultItem} renderer.
*/
private static final class ResultItemRenderer implements ListCellRenderer<ResultItem>
{
private final DefaultListCellRenderer defaultRenderer = new DefaultListCellRenderer();
|
@Override
public Component getListCellRendererComponent(final JList<? extends ResultItem> list, final ResultItem value, final int index, final boolean isSelected, final boolean cellHasFocus)
{
final String valueAsText;
final Icon icon;
boolean enabled = true;
if (value == null)
{
// shall not happen
valueAsText = "";
icon = null;
}
else if (value == MORE_Marker)
{
valueAsText = "...";
icon = null;
enabled = false;
}
else if (value instanceof MenuResultItem)
{
final MenuResultItem menuItem = (MenuResultItem)value;
valueAsText = menuItem.getText();
icon = menuItem.getIcon();
}
else
{
valueAsText = value.toString();
icon = null;
}
defaultRenderer.getListCellRendererComponent(list, valueAsText, index, isSelected, cellHasFocus);
defaultRenderer.setIcon(icon);
defaultRenderer.setEnabled(enabled);
return defaultRenderer;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\tree\TreeSearchAutoCompleter.java
| 1
|
请完成以下Java代码
|
public void setDocumentNo (final @Nullable java.lang.String DocumentNo)
{
set_Value (COLUMNNAME_DocumentNo, DocumentNo);
}
@Override
public java.lang.String getDocumentNo()
{
return get_ValueAsString(COLUMNNAME_DocumentNo);
}
@Override
public void setDR_Account (final @Nullable java.lang.String DR_Account)
{
set_Value (COLUMNNAME_DR_Account, DR_Account);
}
@Override
public java.lang.String getDR_Account()
{
return get_ValueAsString(COLUMNNAME_DR_Account);
}
@Override
public void setDueDate (final @Nullable java.sql.Timestamp DueDate)
{
set_ValueNoCheck (COLUMNNAME_DueDate, DueDate);
}
@Override
public java.sql.Timestamp getDueDate()
{
return get_ValueAsTimestamp(COLUMNNAME_DueDate);
}
@Override
public void setIsSOTrx (final @Nullable java.lang.String IsSOTrx)
{
set_ValueNoCheck (COLUMNNAME_IsSOTrx, IsSOTrx);
}
@Override
public java.lang.String getIsSOTrx()
{
return get_ValueAsString(COLUMNNAME_IsSOTrx);
}
@Override
public void setPOReference (final @Nullable java.lang.String POReference)
{
set_ValueNoCheck (COLUMNNAME_POReference, POReference);
}
@Override
public java.lang.String getPOReference()
{
return get_ValueAsString(COLUMNNAME_POReference);
}
@Override
public void setPostingType (final @Nullable java.lang.String PostingType)
{
set_ValueNoCheck (COLUMNNAME_PostingType, PostingType);
}
|
@Override
public java.lang.String getPostingType()
{
return get_ValueAsString(COLUMNNAME_PostingType);
}
@Override
public void setTaxAmtSource (final @Nullable BigDecimal TaxAmtSource)
{
set_ValueNoCheck (COLUMNNAME_TaxAmtSource, TaxAmtSource);
}
@Override
public BigDecimal getTaxAmtSource()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtSource);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVATCode (final @Nullable java.lang.String VATCode)
{
set_ValueNoCheck (COLUMNNAME_VATCode, VATCode);
}
@Override
public java.lang.String getVATCode()
{
return get_ValueAsString(COLUMNNAME_VATCode);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.datev\src\main\java-gen\de\metas\datev\model\X_DATEV_ExportLine.java
| 1
|
请完成以下Java代码
|
protected class OverviewElement {
protected String id;
protected String name;
protected Integer displayOrder;
protected String includeInStageOverview;
protected PlanItemDefinition planItemDefinition;
public OverviewElement(String id, String name, Integer displayOrder, String includeInStageOverview, PlanItemDefinition planItemDefinition) {
this.id = id;
this.name = name;
this.displayOrder = displayOrder;
this.includeInStageOverview = includeInStageOverview;
this.planItemDefinition = planItemDefinition;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getDisplayOrder() {
return displayOrder;
|
}
public void setDisplayOrder(Integer displayOrder) {
this.displayOrder = displayOrder;
}
public String getIncludeInStageOverview() {
return includeInStageOverview;
}
public void setIncludeInStageOverview(String includeInStageOverview) {
this.includeInStageOverview = includeInStageOverview;
}
public PlanItemDefinition getPlanItemDefinition() {
return planItemDefinition;
}
public void setPlanItemDefinition(PlanItemDefinition planItemDefinition) {
this.planItemDefinition = planItemDefinition;
}
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\GetHistoricStageOverviewCmd.java
| 1
|
请完成以下Java代码
|
public int getAD_Client_ID()
{
return m_AD_Client_ID;
}
@Override
public String login(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID)
{
// nothing
return null;
}
@Override
public String modelChange(final PO po, final int type) throws Exception
{
// nothing
return null;
}
@Override
public String docValidate(final PO po, final int timing)
{
// nothing
return null;
}
private void registerInstanceValidator(final I_C_ReferenceNo_Type type)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(type);
final IReferenceNoGeneratorInstance instance = Services.get(IReferenceNoBL.class).getReferenceNoGeneratorInstance(ctx, type);
if (instance == null)
{
|
return;
}
final ReferenceNoGeneratorInstanceValidator validator = new ReferenceNoGeneratorInstanceValidator(instance);
engine.addModelValidator(validator);
docValidators.add(validator);
}
private void unregisterInstanceValidator(final I_C_ReferenceNo_Type type)
{
final Iterator<ReferenceNoGeneratorInstanceValidator> it = docValidators.iterator();
while (it.hasNext())
{
final ReferenceNoGeneratorInstanceValidator validator = it.next();
if (validator.getInstance().getType().getC_ReferenceNo_Type_ID() == type.getC_ReferenceNo_Type_ID())
{
validator.unregister();
it.remove();
}
}
}
public void updateInstanceValidator(final I_C_ReferenceNo_Type type)
{
unregisterInstanceValidator(type);
registerInstanceValidator(type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.document.refid\src\main\java\de\metas\document\refid\modelvalidator\Main.java
| 1
|
请完成以下Java代码
|
public class ErroneousController {
@Get("/not-found-error")
public HttpResponse<String> endpoint1() {
log.info("endpoint1");
return HttpResponse.notFound();
}
@Get("/internal-server-error")
public HttpResponse<String> endpoint2(@Nullable @Header("skip-error") String isErrorSkipped) {
log.info("endpoint2");
if (isErrorSkipped == null) {
throw new RuntimeException("something went wrong");
}
return HttpResponse.ok("Endpoint 2");
}
@Get("/custom-error")
public HttpResponse<String> endpoint3(@Nullable @Header("skip-error") String isErrorSkipped) {
log.info("endpoint3");
if (isErrorSkipped == null) {
throw new CustomException("something else went wrong");
}
return HttpResponse.ok("Endpoint 3");
}
@Get("/custom-child-error")
public HttpResponse<String> endpoint4(@Nullable @Header("skip-error") String isErrorSkipped) {
log.info("endpoint4");
if (isErrorSkipped == null) {
throw new CustomChildException("something else went wrong");
}
|
return HttpResponse.ok("Endpoint 4");
}
@Error(exception = UnsupportedOperationException.class)
public HttpResponse<JsonError> unsupportedOperationExceptions(HttpRequest<?> request) {
log.info("Unsupported Operation Exception handled");
JsonError error = new JsonError("Unsupported Operation").link(Link.SELF, Link.of(request.getUri()));
return HttpResponse.<JsonError> notFound()
.body(error);
}
@Get("/unsupported-operation")
public HttpResponse<String> endpoint5() {
log.info("endpoint5");
throw new UnsupportedOperationException();
}
}
|
repos\tutorials-master\microservices-modules\micronaut-configuration\src\main\java\com\baeldung\micronaut\globalexceptionhandler\controller\ErroneousController.java
| 1
|
请完成以下Spring Boot application配置
|
server.port=8081
google.clientId=475873350264-g1opb20lf2fc60h0o84rrkn972krgkvo.apps.googleusercontent.com
google.clientSecret=GiA1Agf_aSt-bhTrnXjre-5Z
google.accessTokenUri=https://www.googleapis.com/oauth2/v3/token
google.userAuthorizationUri=https://accounts.google.com/o/oauth2/auth
google.redirect
|
Uri=http://localhost:8081/google-login
google.issuer=accounts.google.com
google.jwkUrl=https://www.googleapis.com/oauth2/v2/certs
|
repos\tutorials-master\spring-security-modules\spring-security-legacy-oidc\src\main\resources\application.properties
| 2
|
请完成以下Java代码
|
public Long getReviewsId() {
return reviewsId;
}
public void setReviewsId(Long reviewsId) {
this.reviewsId = reviewsId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getIsbn() {
return isbn;
}
public void setIsbn(String isbn) {
|
this.isbn = isbn;
}
public String getBookRating() {
return bookRating;
}
public void setBookRating(String bookRating) {
this.bookRating = bookRating;
}
@Override
public String toString() {
return "BookReview{" + "reviewsId=" + reviewsId + ", userId='" + userId + '\'' + ", isbn='" + isbn + '\'' + ", bookRating='" + bookRating + '\'' + '}';
}
}
|
repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\scrollapi\entity\BookReview.java
| 1
|
请完成以下Java代码
|
public int getTrxTimeoutSecs()
{
return trxTimeoutSecs;
}
@Override
public boolean isTrxTimeoutLogOnly()
{
return trxTimeoutLogOnly;
}
@Override
public ITrxConstraints setMaxTrx(final int max)
{
this.maxTrx = max;
return this;
}
@Override
public ITrxConstraints incMaxTrx(final int num)
{
this.maxTrx += num;
return this;
}
@Override
public ITrxConstraints setAllowTrxAfterThreadEnd(boolean allow)
{
this.allowTrxAfterThreadEnd = allow;
return this;
}
@Override
public int getMaxTrx()
{
return maxTrx;
}
@Override
public ITrxConstraints setMaxSavepoints(int maxSavepoints)
{
this.maxSavepoints = maxSavepoints;
return this;
}
@Override
public int getMaxSavepoints()
{
return maxSavepoints;
}
@Override
public ITrxConstraints setActive(boolean active)
{
this.active = active;
return this;
}
@Override
public boolean isActive()
{
return active;
}
@Override
public boolean isOnlyAllowedTrxNamePrefixes()
{
return onlyAllowedTrxNamePrefixes;
}
|
@Override
public ITrxConstraints setOnlyAllowedTrxNamePrefixes(boolean onlyAllowedTrxNamePrefixes)
{
this.onlyAllowedTrxNamePrefixes = onlyAllowedTrxNamePrefixes;
return this;
}
@Override
public ITrxConstraints addAllowedTrxNamePrefix(final String trxNamePrefix)
{
allowedTrxNamePrefixes.add(trxNamePrefix);
return this;
}
@Override
public ITrxConstraints removeAllowedTrxNamePrefix(final String trxNamePrefix)
{
allowedTrxNamePrefixes.remove(trxNamePrefix);
return this;
}
@Override
public Set<String> getAllowedTrxNamePrefixes()
{
return allowedTrxNamePrefixesRO;
}
@Override
public boolean isAllowTrxAfterThreadEnd()
{
return allowTrxAfterThreadEnd;
}
@Override
public void reset()
{
setActive(DEFAULT_ACTIVE);
setAllowTrxAfterThreadEnd(DEFAULT_ALLOW_TRX_AFTER_TREAD_END);
setMaxSavepoints(DEFAULT_MAX_SAVEPOINTS);
setMaxTrx(DEFAULT_MAX_TRX);
setTrxTimeoutSecs(DEFAULT_TRX_TIMEOUT_SECS, DEFAULT_TRX_TIMEOUT_LOG_ONLY);
setOnlyAllowedTrxNamePrefixes(DEFAULT_ONLY_ALLOWED_TRXNAME_PREFIXES);
allowedTrxNamePrefixes.clear();
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("TrxConstraints[");
sb.append("active=" + this.active);
sb.append(", allowedTrxNamePrefixes=" + getAllowedTrxNamePrefixes());
sb.append(", allowTrxAfterThreadEnd=" + isAllowTrxAfterThreadEnd());
sb.append(", maxSavepoints=" + getMaxSavepoints());
sb.append(", maxTrx=" + getMaxTrx());
sb.append(", onlyAllowedTrxNamePrefixes=" + isOnlyAllowedTrxNamePrefixes());
sb.append(", trxTimeoutLogOnly=" + isTrxTimeoutLogOnly());
sb.append(", trxTimeoutSecs=" + getTrxTimeoutSecs());
sb.append("]");
return sb.toString();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\util\trxConstraints\api\impl\TrxConstraints.java
| 1
|
请完成以下Java代码
|
public class OutputClause extends DmnElement {
protected UnaryTests outputValues;
protected LiteralExpression defaultOutputEntry;
protected String name;
protected String typeRef;
protected int outputNumber;
public UnaryTests getOutputValues() {
return outputValues;
}
public void setOutputValues(UnaryTests outputValues) {
this.outputValues = outputValues;
}
public LiteralExpression getDefaultOutputEntry() {
return defaultOutputEntry;
}
public void setDefaultOutputEntry(LiteralExpression defaultOutputEntry) {
this.defaultOutputEntry = defaultOutputEntry;
}
public String getName() {
return name;
}
|
public void setName(String name) {
this.name = name;
}
public String getTypeRef() {
return typeRef;
}
public void setTypeRef(String typeRef) {
this.typeRef = typeRef;
}
public int getOutputNumber() {
return outputNumber;
}
public void setOutputNumber(int outputNumber) {
this.outputNumber = outputNumber;
}
}
|
repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\OutputClause.java
| 1
|
请完成以下Java代码
|
public I_M_PriceList_Version getM_PriceList_Version()
{
return _priceListVersion;
}
@Override
public PricingSystemId getPricingSystemId()
{
PricingSystemId pricingSystemId = _pricingSystemId;
if (pricingSystemId == null)
{
pricingSystemId = _pricingSystemId = PricingSystemId.ofRepoId(getC_Flatrate_Term().getM_PricingSystem_ID());
}
return pricingSystemId;
}
@Override
public I_C_Flatrate_Term getC_Flatrate_Term()
{
if (_flatrateTerm == null)
{
_flatrateTerm = Services.get(IFlatrateDAO.class).getById(materialTracking.getC_Flatrate_Term_ID());
// shouldn't be null because we prevent even material-tracking purchase orders without a flatrate term.
Check.errorIf(_flatrateTerm == null, "M_Material_Tracking {} has no flatrate term", materialTracking);
}
return _flatrateTerm;
}
@Override
public String getInvoiceRule()
{
if (!_invoiceRuleSet)
|
{
//
// Try getting the InvoiceRule from Flatrate Term
final I_C_Flatrate_Term flatrateTerm = getC_Flatrate_Term();
final String invoiceRule = flatrateTerm
.getC_Flatrate_Conditions()
.getInvoiceRule();
Check.assumeNotEmpty(invoiceRule, "Unable to retrieve invoiceRule from materialTracking {}", materialTracking);
_invoiceRule = invoiceRule;
_invoiceRuleSet = true;
}
return _invoiceRule;
}
/* package */void setM_PriceList_Version(final I_M_PriceList_Version priceListVersion)
{
_priceListVersion = priceListVersion;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\MaterialTrackingAsVendorInvoicingInfo.java
| 1
|
请完成以下Java代码
|
public class GroupEntityImpl extends AbstractIdmEngineEntity implements GroupEntity, Serializable {
private static final long serialVersionUID = 1L;
protected String name;
protected String type;
public GroupEntityImpl() {
}
@Override
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<>();
persistentState.put("name", name);
persistentState.put("type", type);
return persistentState;
}
@Override
public String getName() {
|
return name;
}
@Override
public void setName(String name) {
this.name = name;
}
@Override
public String getType() {
return type;
}
@Override
public void setType(String type) {
this.type = type;
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\GroupEntityImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private Map<String, String> getIdentityProviderUrlMap(Element element) {
Map<String, String> idps = new LinkedHashMap<>();
Element relyingPartyRegistrationsElt = DomUtils.getChildElementByTagName(
element.getOwnerDocument().getDocumentElement(), Elements.RELYING_PARTY_REGISTRATIONS);
String authenticationRequestProcessingUrl = DEFAULT_AUTHENTICATION_REQUEST_PROCESSING_URL;
if (relyingPartyRegistrationsElt != null) {
List<Element> relyingPartyRegList = DomUtils.getChildElementsByTagName(relyingPartyRegistrationsElt,
ELT_RELYING_PARTY_REGISTRATION);
for (Element relyingPartyReg : relyingPartyRegList) {
String registrationId = relyingPartyReg.getAttribute(ELT_REGISTRATION_ID);
idps.put(authenticationRequestProcessingUrl.replace("{registrationId}", registrationId),
registrationId);
}
}
return idps;
}
BeanDefinition getSaml2WebSsoAuthenticationRequestFilter() {
return this.saml2WebSsoAuthenticationRequestFilter;
}
BeanDefinition getSaml2AuthenticationUrlToProviderName() {
return this.saml2AuthenticationUrlToProviderName;
}
/**
* Wrapper bean class to provide configuration from applicationContext
*/
public static class Saml2LoginBeanConfig implements ApplicationContextAware {
private ApplicationContext context;
@SuppressWarnings({ "unchecked", "unused" })
Map<String, String> getAuthenticationUrlToProviderName() {
Iterable<RelyingPartyRegistration> relyingPartyRegistrations = null;
RelyingPartyRegistrationRepository relyingPartyRegistrationRepository = this.context
.getBean(RelyingPartyRegistrationRepository.class);
ResolvableType type = ResolvableType.forInstance(relyingPartyRegistrationRepository).as(Iterable.class);
if (type != ResolvableType.NONE
&& RelyingPartyRegistration.class.isAssignableFrom(type.resolveGenerics()[0])) {
relyingPartyRegistrations = (Iterable<RelyingPartyRegistration>) relyingPartyRegistrationRepository;
|
}
if (relyingPartyRegistrations == null) {
return Collections.emptyMap();
}
String authenticationRequestProcessingUrl = DEFAULT_AUTHENTICATION_REQUEST_PROCESSING_URL;
Map<String, String> saml2AuthenticationUrlToProviderName = new HashMap<>();
relyingPartyRegistrations.forEach((registration) -> saml2AuthenticationUrlToProviderName.put(
authenticationRequestProcessingUrl.replace("{registrationId}", registration.getRegistrationId()),
registration.getRegistrationId()));
return saml2AuthenticationUrlToProviderName;
}
@Override
public void setApplicationContext(ApplicationContext context) throws BeansException {
this.context = context;
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\Saml2LoginBeanDefinitionParser.java
| 2
|
请完成以下Java代码
|
public void setDeviceCodeGenerator(OAuth2TokenGenerator<OAuth2DeviceCode> deviceCodeGenerator) {
Assert.notNull(deviceCodeGenerator, "deviceCodeGenerator cannot be null");
this.deviceCodeGenerator = deviceCodeGenerator;
}
/**
* Sets the {@link OAuth2TokenGenerator} that generates the {@link OAuth2UserCode}.
* @param userCodeGenerator the {@link OAuth2TokenGenerator} that generates the
* {@link OAuth2UserCode}
*/
public void setUserCodeGenerator(OAuth2TokenGenerator<OAuth2UserCode> userCodeGenerator) {
Assert.notNull(userCodeGenerator, "userCodeGenerator cannot be null");
this.userCodeGenerator = userCodeGenerator;
}
private static void throwError(String errorCode, String parameterName) {
OAuth2Error error = new OAuth2Error(errorCode, "OAuth 2.0 Parameter: " + parameterName, ERROR_URI);
throw new OAuth2AuthenticationException(error);
}
private static final class OAuth2DeviceCodeGenerator implements OAuth2TokenGenerator<OAuth2DeviceCode> {
private final StringKeyGenerator deviceCodeGenerator = new Base64StringKeyGenerator(
Base64.getUrlEncoder().withoutPadding(), 96);
@Nullable
@Override
public OAuth2DeviceCode generate(OAuth2TokenContext context) {
if (context.getTokenType() == null
|| !OAuth2ParameterNames.DEVICE_CODE.equals(context.getTokenType().getValue())) {
return null;
}
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt
.plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive());
return new OAuth2DeviceCode(this.deviceCodeGenerator.generateKey(), issuedAt, expiresAt);
}
}
private static final class UserCodeStringKeyGenerator implements StringKeyGenerator {
// @formatter:off
private static final char[] VALID_CHARS = {
'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'M',
'N', 'P', 'Q', 'R', 'S', 'T', 'V', 'W', 'X', 'Z'
};
// @formatter:on
private final BytesKeyGenerator keyGenerator = KeyGenerators.secureRandom(8);
|
@Override
public String generateKey() {
byte[] bytes = this.keyGenerator.generateKey();
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
int offset = Math.abs(b % 20);
sb.append(VALID_CHARS[offset]);
}
sb.insert(4, '-');
return sb.toString();
}
}
private static final class OAuth2UserCodeGenerator implements OAuth2TokenGenerator<OAuth2UserCode> {
private final StringKeyGenerator userCodeGenerator = new UserCodeStringKeyGenerator();
@Nullable
@Override
public OAuth2UserCode generate(OAuth2TokenContext context) {
if (context.getTokenType() == null
|| !OAuth2ParameterNames.USER_CODE.equals(context.getTokenType().getValue())) {
return null;
}
Instant issuedAt = Instant.now();
Instant expiresAt = issuedAt
.plus(context.getRegisteredClient().getTokenSettings().getDeviceCodeTimeToLive());
return new OAuth2UserCode(this.userCodeGenerator.generateKey(), issuedAt, expiresAt);
}
}
}
|
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\authentication\OAuth2DeviceAuthorizationRequestAuthenticationProvider.java
| 1
|
请完成以下Java代码
|
public void setGranularity (final @Nullable java.lang.String Granularity)
{
set_Value (COLUMNNAME_Granularity, Granularity);
}
@Override
public java.lang.String getGranularity()
{
return get_ValueAsString(COLUMNNAME_Granularity);
}
@Override
public void setGroupBy (final boolean GroupBy)
{
set_Value (COLUMNNAME_GroupBy, GroupBy);
}
@Override
public boolean isGroupBy()
{
return get_ValueAsBoolean(COLUMNNAME_GroupBy);
}
|
@Override
public void setOrderBySeqNo (final int OrderBySeqNo)
{
set_Value (COLUMNNAME_OrderBySeqNo, OrderBySeqNo);
}
@Override
public int getOrderBySeqNo()
{
return get_ValueAsInt(COLUMNNAME_OrderBySeqNo);
}
@Override
public void setSplitOrder (final boolean SplitOrder)
{
set_Value (COLUMNNAME_SplitOrder, SplitOrder);
}
@Override
public boolean isSplitOrder()
{
return get_ValueAsBoolean(COLUMNNAME_SplitOrder);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_OLCandAggAndOrder.java
| 1
|
请完成以下Java代码
|
public class TokenEntityManagerImpl
extends AbstractIdmEngineEntityManager<TokenEntity, TokenDataManager>
implements TokenEntityManager {
public TokenEntityManagerImpl(IdmEngineConfiguration idmEngineConfiguration, TokenDataManager tokenDataManager) {
super(idmEngineConfiguration, tokenDataManager);
}
@Override
public Token createNewToken(String tokenId) {
TokenEntity tokenEntity = create();
tokenEntity.setId(tokenId);
tokenEntity.setRevision(0); // needed as tokens can be transient
return tokenEntity;
}
@Override
public void updateToken(Token updatedToken) {
super.update((TokenEntity) updatedToken);
}
@Override
public boolean isNewToken(Token token) {
return ((TokenEntity) token).getRevision() == 0;
}
@Override
public List<Token> findTokenByQueryCriteria(TokenQueryImpl query) {
return dataManager.findTokenByQueryCriteria(query);
}
|
@Override
public long findTokenCountByQueryCriteria(TokenQueryImpl query) {
return dataManager.findTokenCountByQueryCriteria(query);
}
@Override
public TokenQuery createNewTokenQuery() {
return new TokenQueryImpl(getCommandExecutor());
}
@Override
public List<Token> findTokensByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findTokensByNativeQuery(parameterMap);
}
@Override
public long findTokenCountByNativeQuery(Map<String, Object> parameterMap) {
return dataManager.findTokenCountByNativeQuery(parameterMap);
}
}
|
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\TokenEntityManagerImpl.java
| 1
|
请完成以下Java代码
|
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** 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 Profile.
@param ProfileInfo
Information to help profiling the system for solving support issues
*/
public void setProfileInfo (String ProfileInfo)
{
set_Value (COLUMNNAME_ProfileInfo, ProfileInfo);
}
/** Get Profile.
@return Information to help profiling the system for solving support issues
*/
public String getProfileInfo ()
{
return (String)get_Value(COLUMNNAME_ProfileInfo);
}
/** Set Issue Project.
@param R_IssueProject_ID
Implementation Projects
*/
public void setR_IssueProject_ID (int R_IssueProject_ID)
{
if (R_IssueProject_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_IssueProject_ID, null);
else
|
set_ValueNoCheck (COLUMNNAME_R_IssueProject_ID, Integer.valueOf(R_IssueProject_ID));
}
/** Get Issue Project.
@return Implementation Projects
*/
public int getR_IssueProject_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_R_IssueProject_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Statistics.
@param StatisticsInfo
Information to help profiling the system for solving support issues
*/
public void setStatisticsInfo (String StatisticsInfo)
{
set_Value (COLUMNNAME_StatisticsInfo, StatisticsInfo);
}
/** Get Statistics.
@return Information to help profiling the system for solving support issues
*/
public String getStatisticsInfo ()
{
return (String)get_Value(COLUMNNAME_StatisticsInfo);
}
/** SystemStatus AD_Reference_ID=374 */
public static final int SYSTEMSTATUS_AD_Reference_ID=374;
/** Evaluation = E */
public static final String SYSTEMSTATUS_Evaluation = "E";
/** Implementation = I */
public static final String SYSTEMSTATUS_Implementation = "I";
/** Production = P */
public static final String SYSTEMSTATUS_Production = "P";
/** Set System Status.
@param SystemStatus
Status of the system - Support priority depends on system status
*/
public void setSystemStatus (String SystemStatus)
{
set_Value (COLUMNNAME_SystemStatus, SystemStatus);
}
/** Get System Status.
@return Status of the system - Support priority depends on system status
*/
public String getSystemStatus ()
{
return (String)get_Value(COLUMNNAME_SystemStatus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_IssueProject.java
| 1
|
请完成以下Java代码
|
public ListenableFuture<Void> saveAsync(EdgeEvent edgeEvent) {
log.debug("Saving EdgeEvent [{}] ", edgeEvent);
if (edgeEvent.getId() == null) {
UUID timeBased = Uuids.timeBased();
edgeEvent.setId(new EdgeEventId(timeBased));
edgeEvent.setCreatedTime(Uuids.unixTimestamp(timeBased));
} else if (edgeEvent.getCreatedTime() == 0L) {
UUID eventId = edgeEvent.getId().getId();
if (eventId.version() == 1) {
edgeEvent.setCreatedTime(Uuids.unixTimestamp(eventId));
} else {
edgeEvent.setCreatedTime(System.currentTimeMillis());
}
}
if (StringUtils.isEmpty(edgeEvent.getUid())) {
edgeEvent.setUid(edgeEvent.getId().toString());
}
EdgeEventEntity entity = new EdgeEventEntity(edgeEvent);
createPartition(entity);
return save(entity);
}
private ListenableFuture<Void> save(EdgeEventEntity entity) {
log.debug("Saving EdgeEventEntity [{}] ", entity);
if (entity.getTenantId() == null) {
log.trace("Save system edge event with predefined id {}", systemTenantId);
entity.setTenantId(systemTenantId);
}
if (entity.getUuid() == null) {
entity.setUuid(Uuids.timeBased());
}
return addToQueue(entity);
}
private ListenableFuture<Void> addToQueue(EdgeEventEntity entity) {
return queue.add(entity);
}
@Override
public PageData<EdgeEvent> findEdgeEvents(UUID tenantId, EdgeId edgeId, Long seqIdStart, Long seqIdEnd, TimePageLink pageLink) {
return DaoUtil.toPageData(
edgeEventRepository
.findEdgeEventsByTenantIdAndEdgeId(
tenantId,
|
edgeId.getId(),
pageLink.getTextSearch(),
pageLink.getStartTime(),
pageLink.getEndTime(),
seqIdStart,
seqIdEnd,
DaoUtil.toPageable(pageLink, SORT_ORDERS)));
}
@Override
public void cleanupEvents(long ttl) {
partitioningRepository.dropPartitionsBefore(TABLE_NAME, ttl, TimeUnit.HOURS.toMillis(partitionSizeInHours));
}
@Override
public void createPartition(EdgeEventEntity entity) {
partitioningRepository.createPartitionIfNotExists(TABLE_NAME, entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours));
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\edge\JpaBaseEdgeEventDao.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class DeploymentResourceLoader<T> {
public static final String DEPLOYMENT_RESOURCES_CACHE_NAME = "deploymentResourcesById";
private RepositoryService repositoryService;
@Cacheable(key = "#deploymentId")
public List<T> loadResourcesForDeployment(String deploymentId, ResourceReader<T> resourceLoaderDescriptor) {
List<T> resources;
List<String> resourceNames = repositoryService.getDeploymentResourceNames(deploymentId);
if (resourceNames != null && !resourceNames.isEmpty()) {
List<String> selectedResources = resourceNames
.stream()
.filter(resourceLoaderDescriptor.getResourceNameSelector())
.collect(Collectors.toList());
resources = loadResources(deploymentId, resourceLoaderDescriptor, selectedResources);
} else {
resources = new ArrayList<>();
}
return resources;
}
private List<T> loadResources(
String deploymentId,
ResourceReader<T> resourceReader,
List<String> selectedResources
|
) {
List<T> resources = new ArrayList<>();
for (String name : selectedResources) {
try (InputStream resourceAsStream = repositoryService.getResourceAsStream(deploymentId, name)) {
T resource = resourceReader.read(resourceAsStream);
if (resource != null) {
resources.add(resource);
}
} catch (IOException e) {
throw new IllegalStateException("Unable to read process extension", e);
}
}
return resources;
}
public void setRepositoryService(RepositoryService repositoryService) {
this.repositoryService = repositoryService;
}
}
|
repos\Activiti-develop\activiti-core\activiti-spring-resource-loader\src\main\java\org\activiti\spring\resources\DeploymentResourceLoader.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class CustomerDataValidator extends DataValidator<Customer> {
@Autowired
private CustomerDao customerDao;
@Autowired
private TenantService tenantService;
@Override
protected void validateCreate(TenantId tenantId, Customer customer) {
validateNumberOfEntitiesPerTenant(tenantId, EntityType.CUSTOMER);
}
@Override
protected Customer validateUpdate(TenantId tenantId, Customer customer) {
Customer old = customerDao.findById(customer.getTenantId(), customer.getId().getId());
if (old == null) {
throw new DataValidationException("Can't update non existing customer!");
}
return old;
}
@Override
|
protected void validateDataImpl(TenantId tenantId, Customer customer) {
validateString("Customer title", customer.getTitle());
if (customer.getTitle().equals(CustomerServiceImpl.PUBLIC_CUSTOMER_TITLE)) {
throw new DataValidationException("'Public' title for customer is system reserved!");
}
if (!StringUtils.isEmpty(customer.getEmail())) {
validateEmail(customer.getEmail());
}
if (customer.getTenantId() == null) {
throw new DataValidationException("Customer should be assigned to tenant!");
} else {
if (!tenantService.tenantExists(customer.getTenantId())) {
throw new DataValidationException("Customer is referencing to non-existent tenant!");
}
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\CustomerDataValidator.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public static class RegionEntryWrapper<K, V> implements Region.Entry<K, V> {
@SuppressWarnings("unchecked")
public static <T, K, V> T from(T value) {
return value instanceof Region.Entry
? (T) new RegionEntryWrapper<>((Region.Entry<K, V>) value)
: value;
}
private final Region.Entry<K, V> delegate;
protected RegionEntryWrapper(@NonNull Region.Entry<K, V> regionEntry) {
Assert.notNull(regionEntry, "Region.Entry must not be null");
this.delegate = regionEntry;
}
protected @NonNull Region.Entry<K, V> getDelegate() {
return this.delegate;
}
@Override
public boolean isDestroyed() {
return getDelegate().isDestroyed();
}
@Override
public boolean isLocal() {
return getDelegate().isLocal();
}
@Override
public K getKey() {
return getDelegate().getKey();
}
@Override
|
public Region<K, V> getRegion() {
return getDelegate().getRegion();
}
@Override
public CacheStatistics getStatistics() {
return getDelegate().getStatistics();
}
@Override
public Object setUserAttribute(Object userAttribute) {
return getDelegate().setUserAttribute(userAttribute);
}
@Override
public Object getUserAttribute() {
return getDelegate().getUserAttribute();
}
@Override
public V setValue(V value) {
return getDelegate().setValue(value);
}
@Override
@SuppressWarnings("unchecked")
public V getValue() {
return (V) PdxInstanceWrapper.from(getDelegate().getValue());
}
}
}
|
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\support\PdxInstanceWrapperRegionAspect.java
| 2
|
请完成以下Java代码
|
public BigDecimal getQtyOrdered() {
Object value = fQtyOrdered.getValue();
if (value == null || value.toString().trim().length() == 0)
return Env.ZERO;
else if (value instanceof BigDecimal)
return (BigDecimal) value;
else if (value instanceof Integer)
return BigDecimal.valueOf(((Integer) value));
else
return new BigDecimal(value.toString());
}
@Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == fQtyOrdered) {
try {
setEnabled(false);
commit();
} catch (Exception ex) {
setInfo(ex.getLocalizedMessage(), true, fQtyOrdered);
} finally {
setEnabled(true);
}
}
}
@Override
public void vetoableChange(PropertyChangeEvent evt)
throws PropertyVetoException {
if (evt.getPropertyName().equals(I_C_OrderLine.COLUMNNAME_M_Product_ID)) {
reset(false);
fProduct.setValue(evt.getNewValue());
updateData(true, fProduct);
}
}
private void reset(boolean clearPrimaryField) {
fQtyOrdered.removeActionListener(this);
if (clearPrimaryField) {
fProduct.setValue(null);
}
fQtyOrdered.setValue(Env.ZERO);
fQtyOrdered.setReadWrite(false);
fProduct.requestFocus();
}
private void updateData(boolean requestFocus, Component source) {
if (requestFocus) {
SwingFieldsUtil.focusNextNotEmpty(source, m_editors);
}
fQtyOrdered.setReadWrite(true);
fQtyOrdered.addActionListener(this);
}
private void commit() {
int M_Product_ID = getM_Product_ID();
if (M_Product_ID <= 0)
throw new FillMandatoryException(
I_C_OrderLine.COLUMNNAME_M_Product_ID);
String productStr = fProduct.getDisplay();
if (productStr == null)
|
productStr = "";
BigDecimal qty = getQtyOrdered();
if (qty == null || qty.signum() == 0)
throw new FillMandatoryException(
I_C_OrderLine.COLUMNNAME_QtyOrdered);
//
MOrderLine line = new MOrderLine(order);
line.setM_Product_ID(getM_Product_ID(), true);
line.setQty(qty);
line.saveEx();
//
reset(true);
changed = true;
refreshIncludedTabs();
setInfo(Msg.parseTranslation(Env.getCtx(),
"@RecordSaved@ - @M_Product_ID@:" + productStr
+ ", @QtyOrdered@:" + qty), false, null);
}
public void showCenter() {
AEnv.showCenterWindow(getOwner(), this);
}
public boolean isChanged() {
return changed;
}
public void refreshIncludedTabs() {
for (GridTab includedTab : orderTab.getIncludedTabs()) {
includedTab.dataRefreshAll();
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\form\swing\OrderLineCreate.java
| 1
|
请完成以下Java代码
|
public final <T> T getProperty(final String name)
{
@SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().get(name);
return value;
}
@Override
public <T> T getProperty(final String name, final Supplier<T> valueInitializer)
{
@SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().computeIfAbsent(name, key -> valueInitializer.get());
return value;
}
@Override
public <T> T getProperty(final String name, final Function<ITrx, T> valueInitializer)
{
@SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().computeIfAbsent(name, key -> valueInitializer.apply(this));
return value;
}
@Override
public <T> T setAndGetProperty(@NonNull final String name, @NonNull final Function<T, T> valueRemappingFunction)
{
|
final BiFunction<? super String, ? super Object, ?> remappingFunction = (propertyName, oldValue) -> {
@SuppressWarnings("unchecked") final T oldValueCasted = (T)oldValue;
return valueRemappingFunction.apply(oldValueCasted);
};
@SuppressWarnings("unchecked") final T value = (T)getPropertiesMap().compute(name, remappingFunction);
return value;
}
protected final void setDebugConnectionBackendId(final String debugConnectionBackendId)
{
this.debugConnectionBackendId = debugConnectionBackendId;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\trx\api\impl\AbstractTrx.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return String.valueOf(value);
}
@JsonValue
public int toInt()
{
return value;
}
public BigDecimal toBigDecimal()
{
return BigDecimal.valueOf(value);
}
@Override
public int compareTo(@NonNull final QuantityTU other)
{
return this.value - other.value;
}
public QuantityTU add(@NonNull final QuantityTU toAdd)
{
if (this.value == 0)
{
return toAdd;
}
else if (toAdd.value == 0)
{
return this;
}
else
{
return ofInt(this.value + toAdd.value);
|
}
}
public QuantityTU subtract(@NonNull final QuantityTU toSubtract)
{
if (toSubtract.value == 0)
{
return this;
}
else
{
return ofInt(this.value - toSubtract.value);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\quantity\QuantityTU.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SpringContextAnnotationScannerService implements SampleAnnotationScanner {
@Override
public List<String> scanAnnotatedMethods() {
throw new ScanNotSupportedException();
}
@Override
public List<String> scanAnnotatedClasses() {
ClassPathScanningCandidateComponentProvider provider =
new ClassPathScanningCandidateComponentProvider(false);
provider.addIncludeFilter(new AnnotationTypeFilter(SampleAnnotation.class));
Set<BeanDefinition> beanDefs = provider
.findCandidateComponents("com.baeldung.annotation.scanner");
List<String> annotatedBeans = new ArrayList<>();
for (BeanDefinition bd : beanDefs) {
if (bd instanceof AnnotatedBeanDefinition) {
Map<String, Object> annotAttributeMap = ((AnnotatedBeanDefinition) bd)
.getMetadata()
.getAnnotationAttributes(SampleAnnotation.class.getCanonicalName());
annotatedBeans.add(annotAttributeMap.get("name")
.toString());
|
}
}
return Collections.unmodifiableList(annotatedBeans);
}
@Override
public boolean supportsMethodScan() {
return false;
}
@Override
public boolean supportsClassScan() {
return true;
}
}
|
repos\tutorials-master\spring-boot-modules\spring-boot-libraries-2\src\main\java\com\baeldung\annotation\scanner\springcontextlib\SpringContextAnnotationScannerService.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
GraphQlWebSocketHandler graphQlWebSocketHandler(WebGraphQlHandler webGraphQlHandler,
GraphQlProperties properties, ServerCodecConfigurer configurer) {
return new GraphQlWebSocketHandler(webGraphQlHandler, configurer,
properties.getWebsocket().getConnectionInitTimeout(), properties.getWebsocket().getKeepAlive());
}
@Bean
HandlerMapping graphQlWebSocketEndpoint(GraphQlWebSocketHandler graphQlWebSocketHandler,
GraphQlProperties properties) {
String path = properties.getWebsocket().getPath();
Assert.state(path != null, "'path' must not be null");
logger.info(LogMessage.format("GraphQL endpoint WebSocket %s", path));
SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
mapping.setHandlerPredicate(new WebSocketUpgradeHandlerPredicate());
mapping.setUrlMap(Collections.singletonMap(path, graphQlWebSocketHandler));
|
mapping.setOrder(-2); // Ahead of HTTP endpoint ("routerFunctionMapping" bean)
return mapping;
}
}
static class GraphiQlResourceHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("graphiql/index.html");
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-graphql\src\main\java\org\springframework\boot\graphql\autoconfigure\reactive\GraphQlWebFluxAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public basefont addElement(Element element)
{
addElementToRegistry(element);
return(this);
}
/**
Adds an Element to the element.
@param element Adds an Element to the element.
*/
public basefont addElement(String element)
{
addElementToRegistry(element);
return(this);
|
}
/**
Removes an Element from the element.
@param hashcode the name of the element to be removed.
*/
public basefont removeElement(String hashcode)
{
removeElementFromRegistry(hashcode);
return(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\basefont.java
| 1
|
请完成以下Java代码
|
public class HeaderHttpSessionIdResolver implements HttpSessionIdResolver {
private static final String HEADER_X_AUTH_TOKEN = "X-Auth-Token";
private static final String HEADER_AUTHENTICATION_INFO = "Authentication-Info";
private final String headerName;
/**
* Convenience factory to create {@link HeaderHttpSessionIdResolver} that uses
* "X-Auth-Token" header.
* @return the instance configured to use "X-Auth-Token" header
*/
public static HeaderHttpSessionIdResolver xAuthToken() {
return new HeaderHttpSessionIdResolver(HEADER_X_AUTH_TOKEN);
}
/**
* Convenience factory to create {@link HeaderHttpSessionIdResolver} that uses
* "Authentication-Info" header.
* @return the instance configured to use "Authentication-Info" header
*/
public static HeaderHttpSessionIdResolver authenticationInfo() {
return new HeaderHttpSessionIdResolver(HEADER_AUTHENTICATION_INFO);
}
/**
* The name of the header to obtain the session id from.
* @param headerName the name of the header to obtain the session id from.
*/
|
public HeaderHttpSessionIdResolver(String headerName) {
if (headerName == null) {
throw new IllegalArgumentException("headerName cannot be null");
}
this.headerName = headerName;
}
@Override
public List<String> resolveSessionIds(HttpServletRequest request) {
String headerValue = request.getHeader(this.headerName);
return (headerValue != null) ? Collections.singletonList(headerValue) : Collections.emptyList();
}
@Override
public void setSessionId(HttpServletRequest request, HttpServletResponse response, String sessionId) {
response.setHeader(this.headerName, sessionId);
}
@Override
public void expireSession(HttpServletRequest request, HttpServletResponse response) {
response.setHeader(this.headerName, "");
}
}
|
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\web\http\HeaderHttpSessionIdResolver.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
private String getFullPath(HandlerMethod handlerMethod) {
StringBuilder fullPath = new StringBuilder();
// 获取类级别的路径
RequestMapping classMapping = handlerMethod.getBeanType().getAnnotation(RequestMapping.class);
if (classMapping != null && classMapping.value().length > 0) {
fullPath.append(classMapping.value()[0]);
}
// 获取方法级别的路径
RequestMapping methodMapping = handlerMethod.getMethodAnnotation(RequestMapping.class);
if (methodMapping != null && methodMapping.value().length > 0) {
String methodPath = methodMapping.value()[0];
// 确保路径正确拼接,处理斜杠
if (!fullPath.toString().endsWith("/") && !methodPath.startsWith("/")) {
fullPath.append("/");
}
fullPath.append(methodPath);
}
return fullPath.toString();
}
private boolean isExcludedPath(String path) {
// 使用缓存避免重复计算
return EXCLUDED_PATHS_CACHE.computeIfAbsent(path, p -> {
// 精确匹配
if (exactPatterns.contains(p)) {
return true;
}
// 通配符匹配
return wildcardPatterns.stream().anyMatch(p::startsWith);
});
}
@Bean
|
public OpenAPI customOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("JeecgBoot 后台服务API接口文档")
.version("3.9.0")
.contact(new Contact().name("北京国炬信息技术有限公司").url("www.jeccg.com").email("jeecgos@163.com"))
.description("后台API接口")
.termsOfService("NO terms of service")
.license(new License().name("Apache 2.0").url("http://www.apache.org/licenses/LICENSE-2.0.html")))
.addSecurityItem(new SecurityRequirement().addList(CommonConstant.X_ACCESS_TOKEN))
.components(new Components().addSecuritySchemes(CommonConstant.X_ACCESS_TOKEN,
new SecurityScheme()
.name(CommonConstant.X_ACCESS_TOKEN)
.type(SecurityScheme.Type.APIKEY)
.in(SecurityScheme.In.HEADER) // 关键:指定为 header
));
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\Swagger3Config.java
| 2
|
请完成以下Java代码
|
private String buildUrl() {
Long timestamp = System.currentTimeMillis();
return String.format("%s×tamp=%s&sign=%s", webhookUrl, timestamp, getSign(timestamp));
}
protected Object createMessage(InstanceEvent event, Instance instance) {
Map<String, Object> messageJson = new HashMap<>();
messageJson.put("msgtype", "text");
Map<String, Object> content = new HashMap<>();
content.put("content", createContent(event, instance));
messageJson.put("text", content);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
return new HttpEntity<>(messageJson, headers);
}
@Override
protected String getDefaultMessage() {
return DEFAULT_MESSAGE;
}
private String getSign(Long timestamp) {
try {
String stringToSign = timestamp + "\n" + secret;
Mac mac = Mac.getInstance("HmacSHA256");
mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
return URLEncoder.encode(new String(Base64.encodeBase64(signData)), StandardCharsets.UTF_8);
}
catch (Exception ex) {
log.warn("Failed to sign message", ex);
}
return "";
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
|
}
public String getWebhookUrl() {
return webhookUrl;
}
public void setWebhookUrl(String webhookUrl) {
this.webhookUrl = webhookUrl;
}
@Nullable
public String getSecret() {
return secret;
}
public void setSecret(@Nullable String secret) {
this.secret = secret;
}
}
|
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\DingTalkNotifier.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public @Nullable String getDataSourceClassName() {
return this.dataSourceClassName;
}
public void setDataSourceClassName(@Nullable String dataSourceClassName) {
this.dataSourceClassName = dataSourceClassName;
}
public Map<String, String> getProperties() {
return this.properties;
}
public void setProperties(Map<String, String> properties) {
this.properties = properties;
}
}
static class DataSourceBeanCreationException extends BeanCreationException {
private final DataSourceProperties properties;
private final EmbeddedDatabaseConnection connection;
DataSourceBeanCreationException(String message, DataSourceProperties properties,
|
EmbeddedDatabaseConnection connection) {
super(message);
this.properties = properties;
this.connection = connection;
}
DataSourceProperties getProperties() {
return this.properties;
}
EmbeddedDatabaseConnection getConnection() {
return this.connection;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\autoconfigure\DataSourceProperties.java
| 2
|
请完成以下Java代码
|
public void setESR_Control_Trx_Qty (final @Nullable BigDecimal ESR_Control_Trx_Qty)
{
set_Value (COLUMNNAME_ESR_Control_Trx_Qty, ESR_Control_Trx_Qty);
}
@Override
public BigDecimal getESR_Control_Trx_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Control_Trx_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setESR_Import_ID (final int ESR_Import_ID)
{
if (ESR_Import_ID < 1)
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, null);
else
set_ValueNoCheck (COLUMNNAME_ESR_Import_ID, ESR_Import_ID);
}
@Override
public int getESR_Import_ID()
{
return get_ValueAsInt(COLUMNNAME_ESR_Import_ID);
}
@Override
public void setESR_Trx_Qty (final @Nullable BigDecimal ESR_Trx_Qty)
{
throw new IllegalArgumentException ("ESR_Trx_Qty is virtual column"); }
@Override
public BigDecimal getESR_Trx_Qty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ESR_Trx_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setHash (final @Nullable java.lang.String Hash)
{
set_Value (COLUMNNAME_Hash, Hash);
}
@Override
public java.lang.String getHash()
{
return get_ValueAsString(COLUMNNAME_Hash);
}
@Override
public void setIsArchiveFile (final boolean IsArchiveFile)
{
set_Value (COLUMNNAME_IsArchiveFile, IsArchiveFile);
}
@Override
public boolean isArchiveFile()
{
return get_ValueAsBoolean(COLUMNNAME_IsArchiveFile);
}
@Override
public void setIsReceipt (final boolean IsReceipt)
{
set_Value (COLUMNNAME_IsReceipt, IsReceipt);
}
@Override
public boolean isReceipt()
{
return get_ValueAsBoolean(COLUMNNAME_IsReceipt);
}
|
@Override
public void setIsReconciled (final boolean IsReconciled)
{
set_Value (COLUMNNAME_IsReconciled, IsReconciled);
}
@Override
public boolean isReconciled()
{
return get_ValueAsBoolean(COLUMNNAME_IsReconciled);
}
@Override
public void setIsValid (final boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, IsValid);
}
@Override
public boolean isValid()
{
return get_ValueAsBoolean(COLUMNNAME_IsValid);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setProcessing (final boolean Processing)
{
throw new IllegalArgumentException ("Processing is virtual column"); }
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-gen\de\metas\payment\esr\model\X_ESR_Import.java
| 1
|
请完成以下Java代码
|
public void setVHU_Source(final de.metas.handlingunits.model.I_M_HU VHU_Source)
{
set_ValueFromPO(COLUMNNAME_VHU_Source_ID, de.metas.handlingunits.model.I_M_HU.class, VHU_Source);
}
@Override
public void setVHU_Source_ID (final int VHU_Source_ID)
{
if (VHU_Source_ID < 1)
set_Value (COLUMNNAME_VHU_Source_ID, null);
else
set_Value (COLUMNNAME_VHU_Source_ID, VHU_Source_ID);
}
@Override
public int getVHU_Source_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_Source_ID);
}
/**
* VHUStatus AD_Reference_ID=540478
* Reference name: HUStatus
*/
public static final int VHUSTATUS_AD_Reference_ID=540478;
/** Planning = P */
public static final String VHUSTATUS_Planning = "P";
/** Active = A */
public static final String VHUSTATUS_Active = "A";
/** Destroyed = D */
public static final String VHUSTATUS_Destroyed = "D";
/** Picked = S */
public static final String VHUSTATUS_Picked = "S";
/** Shipped = E */
|
public static final String VHUSTATUS_Shipped = "E";
/** Issued = I */
public static final String VHUSTATUS_Issued = "I";
@Override
public void setVHUStatus (final java.lang.String VHUStatus)
{
set_ValueNoCheck (COLUMNNAME_VHUStatus, VHUStatus);
}
@Override
public java.lang.String getVHUStatus()
{
return get_ValueAsString(COLUMNNAME_VHUStatus);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Trace.java
| 1
|
请完成以下Java代码
|
public void processOLCands(@NonNull final ProcessOLCandsRequest request)
{
final Set<OLCandId> olCandIds = queryBL.createQueryBuilder(I_C_OLCand.class)
.setOnlySelection(request.getPInstanceId())
.create()
.stream()
.map(I_C_OLCand::getC_OLCand_ID)
.map(OLCandId::ofRepoId)
.collect(ImmutableSet.toImmutableSet());
if (olCandIds.isEmpty())
{
Loggables.withLogger(logger, Level.INFO).addLog("Returning! No OlCandIds selection found for PInstanceId: {}. Maybe you created them in another transaction that's not yet committed?", request.getPInstanceId());
return;
}
final Map<AsyncBatchId, List<OLCandId>> asyncBatchId2OLCandIds = trxManager.callInNewTrx(() -> orderService.getAsyncBatchId2OLCandIds(olCandIds));
// Propagating them means that the WPs which create the shipment-scheds and invoice-candidates also belong to this async-batch.
// So, when the async-batch is finally done, we will have those scheds&ICs
final boolean propagateAsyncIdsToShipmentSchduleWPs = request.isShip() || request.isInvoice();
final Set<OrderId> orderIds = orderService.generateOrderSync(asyncBatchId2OLCandIds, propagateAsyncIdsToShipmentSchduleWPs);
if (request.isShip())
{ // now we need a new async-batch! The one we create the Orders with is processed and its observer unregistered
final Set<InOutId> generatedInOutIds = shipmentService.generateShipmentsForOLCands(asyncBatchId2OLCandIds);
Loggables.withLogger(logger, Level.INFO).addLog("Created {} M_InOuts", generatedInOutIds.size());
for (final InOutId inOutId : generatedInOutIds)
{
shipperDeliveryService.createTransportationAndPackagesForShipment(inOutId);
}
|
}
if (request.isInvoice())
{
final List<I_M_InOutLine> shipmentLines = inOutDAO.retrieveShipmentLinesForOrderId(orderIds);
Loggables.withLogger(logger, Level.INFO).addLog("Retrieved {} M_InOutLines for {} C_Order_IDs", shipmentLines.size(), orderIds.size());
invoiceService.generateInvoicesFromShipmentLines(shipmentLines);
}
if (request.isCloseOrder())
{
orderIds.forEach(orderBL::closeOrder);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de-metas-salesorder\src\main\java\de\metas\salesorder\candidate\AutoProcessingOLCandService.java
| 1
|
请完成以下Java代码
|
public void deleteByTenantId(TenantId tenantId) {
deleteAssetProfilesByTenantId(tenantId);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findAssetProfileById(tenantId, new AssetProfileId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(assetProfileDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.ASSET_PROFILE;
}
@Override
public List<EntityInfo> findAssetProfileNamesByTenantId(TenantId tenantId, boolean activeOnly) {
log.trace("Executing findAssetProfileNamesByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
return assetProfileDao.findTenantAssetProfileNames(tenantId.getId(), activeOnly)
.stream().sorted(Comparator.comparing(EntityInfo::getName))
.collect(Collectors.toList());
}
@Override
|
public List<AssetProfileInfo> findAssetProfilesByIds(TenantId tenantId, List<AssetProfileId> assetProfileIds) {
log.trace("Executing findAssetProfilesByIds, tenantId [{}], assetProfileIds [{}]", tenantId, assetProfileIds);
return assetProfileDao.findAssetProfilesByTenantIdAndIds(tenantId.getId(), toUUIDs(assetProfileIds));
}
private final PaginatedRemover<TenantId, AssetProfile> tenantAssetProfilesRemover =
new PaginatedRemover<>() {
@Override
protected PageData<AssetProfile> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return assetProfileDao.findAssetProfiles(id, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, AssetProfile entity) {
removeAssetProfile(tenantId, entity);
}
};
private AssetProfileInfo toAssetProfileInfo(AssetProfile profile) {
return profile == null ? null : new AssetProfileInfo(profile.getId(), profile.getTenantId(), profile.getName(), profile.getImage(),
profile.getDefaultDashboardId());
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\asset\AssetProfileServiceImpl.java
| 1
|
请完成以下Java代码
|
public Set<WarehouseId> getWarehouseFromIds() {return getValues(DistributionFacetGroupType.WAREHOUSE_FROM, DistributionFacetId::getWarehouseId);}
public Set<WarehouseId> getWarehouseToIds() {return getValues(DistributionFacetGroupType.WAREHOUSE_TO, DistributionFacetId::getWarehouseId);}
public Set<OrderId> getSalesOrderIds() {return getValues(DistributionFacetGroupType.SALES_ORDER, DistributionFacetId::getSalesOrderId);}
public Set<PPOrderId> getManufacturingOrderIds() {return getValues(DistributionFacetGroupType.MANUFACTURING_ORDER_NO, DistributionFacetId::getManufacturingOrderId);}
public Set<LocalDate> getDatesPromised() {return getValues(DistributionFacetGroupType.DATE_PROMISED, DistributionFacetId::getDatePromised);}
public Set<ProductId> getProductIds() {return getValues(DistributionFacetGroupType.PRODUCT, DistributionFacetId::getProductId);}
public Set<Quantity> getQuantities() {return getValues(DistributionFacetGroupType.QUANTITY, DistributionFacetId::getQty);}
public Set<ResourceId> getPlantIds() {return getValues(DistributionFacetGroupType.PLANT_RESOURCE_ID, DistributionFacetId::getPlantId);}
|
public <T> Set<T> getValues(DistributionFacetGroupType groupType, Function<DistributionFacetId, T> valueExtractor)
{
if (set.isEmpty())
{
return ImmutableSet.of();
}
return set.stream()
.filter(facetId -> facetId.getGroup().equals(groupType))
.map(valueExtractor)
.collect(ImmutableSet.toImmutableSet());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetIdsCollection.java
| 1
|
请完成以下Java代码
|
private GuavaSession getSession() {
if (session == null) {
session = cluster.getSession();
defaultReadLevel = cluster.getDefaultReadConsistencyLevel();
defaultWriteLevel = cluster.getDefaultWriteConsistencyLevel();
}
return session;
}
protected PreparedStatement prepare(String query) {
return preparedStatementMap.computeIfAbsent(query, i -> getSession().prepare(i));
}
protected AsyncResultSet executeRead(TenantId tenantId, Statement statement) {
return execute(tenantId, statement, defaultReadLevel, rateReadLimiter);
}
protected AsyncResultSet executeWrite(TenantId tenantId, Statement statement) {
return execute(tenantId, statement, defaultWriteLevel, rateWriteLimiter);
}
protected TbResultSetFuture executeAsyncRead(TenantId tenantId, Statement statement) {
return executeAsync(tenantId, statement, defaultReadLevel, rateReadLimiter);
}
protected TbResultSetFuture executeAsyncWrite(TenantId tenantId, Statement statement) {
return executeAsync(tenantId, statement, defaultWriteLevel, rateWriteLimiter);
}
private AsyncResultSet execute(TenantId tenantId, Statement statement, ConsistencyLevel level,
BufferedRateExecutor<CassandraStatementTask, TbResultSetFuture> rateExecutor) {
if (log.isDebugEnabled()) {
log.debug("Execute cassandra statement {}", statementToString(statement));
}
return executeAsync(tenantId, statement, level, rateExecutor).getUninterruptibly();
}
|
private TbResultSetFuture executeAsync(TenantId tenantId, Statement statement, ConsistencyLevel level,
BufferedRateExecutor<CassandraStatementTask, TbResultSetFuture> rateExecutor) {
if (log.isDebugEnabled()) {
log.debug("Execute cassandra async statement {}", statementToString(statement));
}
if (statement.getConsistencyLevel() == null) {
statement = statement.setConsistencyLevel(level);
}
return rateExecutor.submit(new CassandraStatementTask(tenantId, getSession(), statement));
}
private static String statementToString(Statement statement) {
if (statement instanceof BoundStatement) {
return ((BoundStatement) statement).getPreparedStatement().getQuery();
} else {
return statement.toString();
}
}
}
|
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\nosql\CassandraAbstractDao.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class Address {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
@Column(name = "city")
private String city;
@Column(name = "street")
private String street;
@OneToOne(mappedBy = "address")
private User user;
public Address() {
}
public Address(String city, String street) {
this.city = city;
this.street = street;
}
public Long getId() {
return id;
}
public void setId(Long id) {
|
this.id = id;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
|
repos\tutorials-master\persistence-modules\hibernate-exceptions\src\main\java\com\baeldung\hibernate\exception\transientobject\entity\Address.java
| 2
|
请完成以下Java代码
|
public Employee getEmployee(final int id) {
final String query = "SELECT * FROM EMPLOYEE WHERE ID = ?";
return jdbcTemplate.queryForObject(query, new EmployeeRowMapper(), id);
}
public void addEmplyeeUsingExecuteMethod() {
jdbcTemplate.execute("INSERT INTO EMPLOYEE VALUES (6, 'Bill', 'Gates', 'USA')");
}
public String getEmployeeUsingMapSqlParameterSource() {
final SqlParameterSource namedParameters = new MapSqlParameterSource().addValue("id", 1);
return namedParameterJdbcTemplate.queryForObject("SELECT FIRST_NAME FROM EMPLOYEE WHERE ID = :id", namedParameters, String.class);
}
public int getEmployeeUsingBeanPropertySqlParameterSource() {
final Employee employee = new Employee();
employee.setFirstName("James");
final String SELECT_BY_ID = "SELECT COUNT(*) FROM EMPLOYEE WHERE FIRST_NAME = :firstName";
final SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(employee);
return namedParameterJdbcTemplate.queryForObject(SELECT_BY_ID, namedParameters, Integer.class);
}
public int[] batchUpdateUsingJDBCTemplate(final List<Employee> employees) {
return jdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)", new BatchPreparedStatementSetter() {
@Override
public void setValues(final PreparedStatement ps, final int i) throws SQLException {
ps.setInt(1, employees.get(i).getId());
ps.setString(2, employees.get(i).getFirstName());
ps.setString(3, employees.get(i).getLastName());
ps.setString(4, employees.get(i).getAddress());
}
@Override
public int getBatchSize() {
|
return 3;
}
});
}
public int[] batchUpdateUsingNamedParameterJDBCTemplate(final List<Employee> employees) {
final SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(employees.toArray());
final int[] updateCounts = namedParameterJdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)", batch);
return updateCounts;
}
public Employee getEmployeeUsingSimpleJdbcCall(int id) {
SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id);
Map<String, Object> out = simpleJdbcCall.execute(in);
Employee emp = new Employee();
emp.setFirstName((String) out.get("FIRST_NAME"));
emp.setLastName((String) out.get("LAST_NAME"));
return emp;
}
}
|
repos\tutorials-master\persistence-modules\spring-persistence-simple\src\main\java\com\baeldung\spring\jdbc\template\guide\EmployeeDAO.java
| 1
|
请完成以下Java代码
|
public TimerJobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
public TimerJobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext.getTimerJobEntityManager().findJobCountByQueryCriteria(this);
}
public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getTimerJobEntityManager().findJobsByQueryCriteria(this, page);
}
// getters //////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public boolean getRetriesLeft() {
return retriesLeft;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
|
public String getId() {
return id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
public boolean isNoRetriesLeft() {
return noRetriesLeft;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\TimerJobQueryImpl.java
| 1
|
请完成以下Spring Boot application配置
|
spring:
cloud:
gateway:
routes:
- id: rewrite_v1
uri: ${rewrite.backend.uri:http://example.com}
predicates:
- Path=/v1/customer/**
|
filters:
- RewritePath=/v1/customer/(?<segment>.*),/api/$\{segment}
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-gateway\src\main\resources\application-url-rewrite.yml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class EnqueuePurchaseCandidateRouteBuilder extends RouteBuilder
{
@Override
public void configure() throws Exception
{
errorHandler(noErrorHandler());
from(direct(MF_ENQUEUE_PURCHASE_CANDIDATES_V2_CAMEL_URI))
.routeId(MF_ENQUEUE_PURCHASE_CANDIDATES_V2_CAMEL_URI)
.streamCache("true")
.process(exchange -> {
final var request = exchange.getIn().getBody();
if (!(request instanceof JsonPurchaseCandidatesRequest))//
{
throw new RuntimeCamelException("The route " + MF_ENQUEUE_PURCHASE_CANDIDATES_V2_CAMEL_URI + " requires the body to be instanceof JsonPurchaseCandidatesRequest."
|
+ " However, it is " + (request == null ? "null" : request.getClass().getName()));
}
final JsonPurchaseCandidatesRequest jsonPurchaseCandidatesRequest = (JsonPurchaseCandidatesRequest)request;
log.info("Enqueue purchases candidate route invoked with " + jsonPurchaseCandidatesRequest);
exchange.getIn().setBody(jsonPurchaseCandidatesRequest);
})
.marshal(CamelRouteHelper.setupJacksonDataFormatFor(getContext(), JsonPurchaseCandidatesRequest.class))
.removeHeaders("CamelHttp*")
.setHeader(Exchange.HTTP_METHOD, constant(HttpMethods.POST))
.toD("{{metasfresh.enqueue-purchases-candidate-v2.api.uri}}")
.to(direct(UNPACK_V2_API_RESPONSE));
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\to_mf\v2\EnqueuePurchaseCandidateRouteBuilder.java
| 2
|
请完成以下Java代码
|
public class Product {
private String name;
private String description;
private Double price;
private ProductView view;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Double getPrice() {
return price;
}
|
public void setPrice(Double price) {
this.price = price;
}
public ProductView getView() {
return view;
}
public void setView(ProductView view) {
this.view = view;
}
public void showProduct() {
view.printProductDetails(name, description, price);
}
}
|
repos\tutorials-master\patterns-modules\design-patterns-architectural\src\main\java\com\baeldung\mvc_mvp\mvc\Product.java
| 1
|
请完成以下Java代码
|
protected boolean isLUorTUorTopLevelVHU(IAttributeSet attributeSet)
{
if (!isVirtualHU(attributeSet))
{
return true;
}
final I_M_HU hu = huAttributesBL.getM_HU_OrNull(attributeSet);
final boolean virtualTopLevelHU = handlingUnitsBL.isTopLevel(hu);
return virtualTopLevelHU;
}
@Override
public final String generateStringValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
|
throw new UnsupportedOperationException("Not supported");
}
@Override
public final Date generateDateValue(Properties ctx, IAttributeSet attributeSet, I_M_Attribute attribute)
{
throw new UnsupportedOperationException("Not supported");
}
@Override
public final AttributeListValue generateAttributeValue(final Properties ctx, final int tableId, final int recordId, final boolean isSOTrx, final String trxName)
{
throw new UnsupportedOperationException("Not supported");
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\AbstractWeightAttributeValueCallout.java
| 1
|
请完成以下Java代码
|
public List<String> getNames() {
return names;
}
public String getLanguageName() {
return NAME;
}
public String getLanguageVersion() {
return VERSION;
}
public Object getParameter(String key) {
if (key.equals(ScriptEngine.NAME)) {
return getLanguageName();
} else if (key.equals(ScriptEngine.ENGINE)) {
return getEngineName();
} else if (key.equals(ScriptEngine.ENGINE_VERSION)) {
return getEngineVersion();
} else if (key.equals(ScriptEngine.LANGUAGE)) {
return getLanguageName();
} else if (key.equals(ScriptEngine.LANGUAGE_VERSION)) {
return getLanguageVersion();
} else if (key.equals("THREADING")) {
return "MULTITHREADED";
} else {
return null;
}
}
public String getMethodCallSyntax(String object, String method, String... args) {
return "${" + object + "." + method + "(" + joinStrings(", ", args) + ")}";
}
|
public String getOutputStatement(String toDisplay) {
return toDisplay;
}
public String getProgram(String... statements) {
return joinStrings("\n", statements);
}
protected String joinStrings(String delimiter, String[] values) {
if (values == null) {
return null;
}
else {
return String.join(delimiter, values);
}
}
public ScriptEngine getScriptEngine() {
return new FreeMarkerScriptEngine(this);
}
}
|
repos\camunda-bpm-platform-master\freemarker-template-engine\src\main\java\org\camunda\templateengines\FreeMarkerScriptEngineFactory.java
| 1
|
请完成以下Java代码
|
public String getToken() {
return token;
}
/**
* Sets the value of the token property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setToken(String value) {
this.token = value;
}
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
|
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\InstructionType.java
| 1
|
请完成以下Java代码
|
public static IntegerLookupValue unknown(final int id)
{
return new IntegerLookupValue(
id,
unknownCaption(id),
null/* description */,
null/* attributes */,
false/* not active */);
}
@Builder
private IntegerLookupValue(
final int id,
@Nullable final ITranslatableString displayName,
@Nullable final ITranslatableString description,
@Nullable @Singular final Map<String, Object> attributes,
@Nullable final Boolean active)
{
|
super(id,
displayName,
description,
attributes,
active);
}
@Override
public int getIdAsInt()
{
return (Integer)id;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\LookupValue.java
| 1
|
请完成以下Java代码
|
public void setProduct_UUID (java.lang.String Product_UUID)
{
set_Value (COLUMNNAME_Product_UUID, Product_UUID);
}
/** Get Produkt UUID.
@return Produkt UUID */
@Override
public java.lang.String getProduct_UUID ()
{
return (java.lang.String)get_Value(COLUMNNAME_Product_UUID);
}
/** Set Menge.
@param Qty
Menge
*/
@Override
public void setQty (java.math.BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Menge.
@return Menge
*/
@Override
public java.math.BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
{
return Env.ZERO;
}
return bd;
}
/** Set Menge (old).
@param Qty_Old Menge (old) */
@Override
public void setQty_Old (java.math.BigDecimal Qty_Old)
{
set_Value (COLUMNNAME_Qty_Old, Qty_Old);
}
/** Get Menge (old).
@return Menge (old) */
@Override
public java.math.BigDecimal getQty_Old ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty_Old);
if (bd == null)
{
return Env.ZERO;
|
}
return bd;
}
/**
* Type AD_Reference_ID=540660
* Reference name: PMM_RfQResponse_ChangeEvent_Type
*/
public static final int TYPE_AD_Reference_ID=540660;
/** Price = P */
public static final String TYPE_Price = "P";
/** Quantity = Q */
public static final String TYPE_Quantity = "Q";
/** Set Art.
@param Type
Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Type of Validation (SQL, Java Script, Java Language)
*/
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_RfQResponse_ChangeEvent.java
| 1
|
请完成以下Java代码
|
public void remove (int offset, int length)
throws BadLocationException
{
// No format or non manual entry
if (m_VFormat.length() == 0 || length != 1)
{
log.trace("Offset=" + offset + " Length=" + length);
super.remove(offset, length);
return;
}
// begin of string
if (offset == 0)
{
// empty the field
if (length == m_mask.length())
super.remove(offset, length);
return;
}
// one position behind delimiter
if (offset-1 >= 0 && m_mask.charAt(offset-1) != SPACE)
{
if (offset-2 >= 0)
m_tc.setCaretPosition(offset-2);
else
return;
}
else
m_tc.setCaretPosition(offset-1);
} // deleteString
/**
* Get Full Text
* @return text
*/
private String getText()
{
String str = "";
try
{
str = getContent().getString(0, getContent().length()-1); // cr at end
}
catch (Exception e)
{
str = "";
}
return str;
} // getString
/**************************************************************************
* Caret Listener
* @param e
*/
public void caretUpdate(CaretEvent e)
{
// No Format
if (m_VFormat.length() == 0
|
// Format error - all fixed characters
|| m_VFormat.equals(m_mask))
return;
// Selection
if (e.getDot() != e.getMark())
{
m_lastDot = e.getDot();
return;
}
//
// log.debug( "MDocString.caretUpdate -" + m_VFormat + "-" + m_mask + "- dot=" + e.getDot() + ", mark=" + e.getMark());
// Is the current position a fixed character?
if (e.getDot()+1 > m_mask.length() || m_mask.charAt(e.getDot()) == SPACE)
{
m_lastDot = e.getDot();
return;
}
// Direction?
int newDot = -1;
if (m_lastDot > e.getDot()) // <-
newDot = e.getDot() - 1;
else // -> (or same)
newDot = e.getDot() + 1;
//
if (e.getDot() == 0) // first
newDot = 1;
else if (e.getDot() == m_mask.length()-1) // last
newDot = e.getDot() - 1;
//
// log.debug( "OnFixedChar=" + m_mask.charAt(e.getDot()) + ", newDot=" + newDot + ", last=" + m_lastDot);
m_lastDot = e.getDot();
if (newDot >= 0 && newDot < getText().length())
m_tc.setCaretPosition(newDot);
} // caretUpdate
} // MDocString
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\MDocString.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getFileStatusInfo(@RequestParam("fileName") String fileName) {
return minioUtils.getFileStatusInfo(minioConfig.getBucketName(), fileName);
}
/**
* get file url
*
* @param fileName
* @return
*/
@GetMapping("/url")
public String getPresignedObjectUrl(@RequestParam("fileName") String fileName) {
return minioUtils.getPresignedObjectUrl(minioConfig.getBucketName(), fileName);
}
/**
* file download
|
*
* @param fileName
* @param response
*/
@GetMapping("/download")
public void download(@RequestParam("fileName") String fileName, HttpServletResponse response) {
try {
InputStream fileInputStream = minioUtils.getObject(minioConfig.getBucketName(), fileName);
response.setHeader("Content-Disposition", "attachment;filename=" + fileName);
response.setContentType("application/force-download");
response.setCharacterEncoding("UTF-8");
IOUtils.copy(fileInputStream, response.getOutputStream());
} catch (Exception e) {
log.error("download fail");
}
}
}
|
repos\springboot-demo-master\minio\src\main\java\demo\et\minio\controller\OSSController.java
| 2
|
请完成以下Java代码
|
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String getBlurb() {
return blurb;
}
public void setBlurb(String blurb) {
|
this.blurb = blurb;
}
public int getPages() {
return pages;
}
public void setPages(int pages) {
this.pages = pages;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", title='" + title + '\'' +
", author='" + author + '\'' +
", blurb='" + blurb + '\'' +
", pages=" + pages +
'}';
}
}
|
repos\tutorials-master\persistence-modules\spring-data-rest-2\src\main\java\com\baeldung\halbrowser\model\Book.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Map<String, Object> generateListOfCharactersChatClientMap(@PathVariable int amount) {
if (amount > 10) {
throw new IllegalArgumentException("Amount must be less than 10");
}
return characterService.generateMapOfCharactersChatClient(amount);
}
// List of character names
@GetMapping("/chat-model/names/{amount}")
public List<String> generateListOfCharacterNamesChatModel(@PathVariable int amount) {
return characterService.generateListOfCharacterNamesChatModel(amount);
}
@GetMapping("/chat-client/names/{amount}")
public List<String> generateListOfCharacterNamesChatClient(@PathVariable int amount) {
|
return characterService.generateListOfCharacterNamesChatClient(amount);
}
// Custom converter
@GetMapping("/custom-converter/{amount}")
public Map<String, Character> generateMapOfCharactersCustomConverterGenerics(@PathVariable int amount) {
return characterService.generateMapOfCharactersCustomConverter(amount);
}
@GetMapping("/custom-converter/chat-client/{amount}")
public Map<String, Character> generateMapOfCharactersCustomConverterChatClient(@PathVariable int amount) {
return characterService.generateMapOfCharactersCustomConverterChatClient(amount);
}
}
|
repos\tutorials-master\spring-ai-modules\spring-ai-3\src\main\java\com\baeldung\springaistructuredoutput\controller\CharacterController.java
| 2
|
请完成以下Java代码
|
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
protected void setEntity(ENTITY_TYPE entity) {
this.entity = entity;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder
.append("RuntimeEventImpl [id=")
.append(id)
.append(", timestamp=")
.append(timestamp)
.append(", processInstanceId=")
.append(processInstanceId)
.append(", processDefinitionId=")
.append(processDefinitionId)
.append(", processDefinitionKey=")
.append(processDefinitionKey)
.append(", processDefinitionVersion=")
.append(processDefinitionVersion)
.append(", businessKey=")
.append(businessKey)
.append(", parentProcessInstanceId=")
.append(parentProcessInstanceId)
.append(", entity=")
.append(entity)
.append("]");
return builder.toString();
}
@Override
public int hashCode() {
return Objects.hash(
businessKey,
|
entity,
id,
parentProcessInstanceId,
processDefinitionId,
processDefinitionKey,
processDefinitionVersion,
processInstanceId,
timestamp,
getEventType()
);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
RuntimeEventImpl other = (RuntimeEventImpl) obj;
return (
Objects.equals(businessKey, other.businessKey) &&
Objects.equals(entity, other.entity) &&
Objects.equals(id, other.id) &&
Objects.equals(parentProcessInstanceId, other.parentProcessInstanceId) &&
Objects.equals(processDefinitionId, other.processDefinitionId) &&
Objects.equals(processDefinitionKey, other.processDefinitionKey) &&
Objects.equals(processDefinitionVersion, other.processDefinitionVersion) &&
Objects.equals(processInstanceId, other.processInstanceId) &&
Objects.equals(timestamp, other.timestamp)
);
}
}
|
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-model-shared-impl\src\main\java\org\activiti\api\runtime\event\impl\RuntimeEventImpl.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ProjectInitializer extends ChannelInitializer<SocketChannel> {
/**
* webSocket协议名
*/
static final String WEBSOCKET_PROTOCOL = "WebSocket";
/**
* webSocket路径
*/
@Value("${webSocket.netty.path:/webSocket}")
String webSocketPath;
@Autowired
WebSocketHandler webSocketHandler;
@Override
|
protected void initChannel(SocketChannel socketChannel) throws Exception {
// 设置管道
ChannelPipeline pipeline = socketChannel.pipeline();
// 流水线管理通道中的处理程序(Handler),用来处理业务
// webSocket协议本身是基于http协议的,所以这边也要使用http编解码器
pipeline.addLast(new HttpServerCodec());
pipeline.addLast(new ObjectEncoder());
// 以块的方式来写的处理器
pipeline.addLast(new ChunkedWriteHandler());
pipeline.addLast(new HttpObjectAggregator(8192));
pipeline.addLast(new WebSocketServerProtocolHandler(webSocketPath, WEBSOCKET_PROTOCOL, true, 65536 * 10));
// 自定义的handler,处理业务逻辑
pipeline.addLast(webSocketHandler);
}
}
|
repos\springboot-demo-master\netty\src\main\java\com\et\netty\config\ProjectInitializer.java
| 2
|
请完成以下Java代码
|
private static ArrayList<Tag> createTags(final @NonNull Metadata metadata, final PerformanceMonitoringData perfMonData)
{
final ArrayList<Tag> tags = new ArrayList<>();
addTagIfNotNull("name", metadata.getClassName(), tags);
addTagIfNotNull("action", metadata.getFunctionName(), tags);
if (!perfMonData.isInitiator())
{
addTagIfNotNull("depth", String.valueOf(perfMonData.getDepth()), tags);
addTagIfNotNull("initiator", perfMonData.getInitiatorFunctionNameFQ(), tags);
addTagIfNotNull("window", perfMonData.getInitiatorWindow(), tags);
addTagIfNotNull("callerName", metadata.getFunctionNameFQ(), tags);
addTagIfNotNull("calledBy", perfMonData.getLastCalledFunctionNameFQ(), tags);
}
else
{
for (final Entry<String, String> entry : metadata.getLabels().entrySet())
{
if (PerformanceMonitoringService.VOLATILE_LABELS.contains(entry.getKey()))
{
// Avoid OOME: if we included e.g. the recordId, then every recordId would cause a new meter to be created.
continue;
}
addTagIfNotNull(entry.getKey(), entry.getValue(), tags);
}
}
|
return tags;
}
private static void addTagIfNotNull(@Nullable final String name, @Nullable final String value, @NonNull final ArrayList<Tag> tags)
{
final String nameNorm = StringUtils.trimBlankToNull(name);
if (nameNorm == null)
{
return;
}
final String valueNorm = StringUtils.trimBlankToNull(value);
if (valueNorm == null)
{
return;
}
tags.add(Tag.of(nameNorm, valueNorm));
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.monitoring\src\main\java\de\metas\monitoring\adapter\MicrometerPerformanceMonitoringService.java
| 1
|
请完成以下Java代码
|
public void updateUOMConversion(@NonNull final UpdateUOMConversionRequest request)
{
final I_C_UOM_Conversion record = Services.get(IQueryBL.class).createQueryBuilder(I_C_UOM_Conversion.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_UOM_Conversion.COLUMNNAME_M_Product_ID, request.getProductId())
.addEqualsFilter(I_C_UOM_Conversion.COLUMNNAME_C_UOM_ID, request.getFromUomId())
.addEqualsFilter(I_C_UOM_Conversion.COLUMNNAME_C_UOM_To_ID, request.getToUomId())
.create()
.firstOnlyNotNull(I_C_UOM_Conversion.class);// we have a unique-constraint
final BigDecimal fromToMultiplier = request.getFromToMultiplier();
final BigDecimal toFromMultiplier = UOMConversionRate.computeInvertedMultiplier(fromToMultiplier);
record.setMultiplyRate(fromToMultiplier);
record.setDivideRate(toFromMultiplier);
record.setIsCatchUOMForProduct(request.isCatchUOMForProduct());
saveRecord(record);
}
@NonNull
private UOMConversionsMap retrieveProductConversions(@NonNull final ProductId productId)
{
final UomId productStockingUomId = Services.get(IProductBL.class).getStockUOMId(productId);
final ImmutableList<UOMConversionRate> rates = Services.get(IQueryBL.class)
.createQueryBuilderOutOfTrx(I_C_UOM_Conversion.class)
.addEqualsFilter(I_C_UOM_Conversion.COLUMNNAME_M_Product_ID, productId)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(UOMConversionDAO::toUOMConversionOrNull)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
return buildUOMConversionsMap(productId,
productStockingUomId,
rates);
|
}
@NonNull
private static UOMConversionsMap buildUOMConversionsMap(
@NonNull final ProductId productId,
@NonNull final UomId productStockingUomId,
@NonNull final ImmutableList<UOMConversionRate> rates)
{
return UOMConversionsMap.builder()
.productId(productId)
.hasRatesForNonStockingUOMs(!rates.isEmpty())
.rates(ImmutableList.<UOMConversionRate>builder()
.add(UOMConversionRate.one(productStockingUomId)) // default conversion
.addAll(rates)
.build())
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\impl\UOMConversionDAO.java
| 1
|
请完成以下Java代码
|
protected static MailHostServerConfiguration createMailHostServerConfiguration(String host, MailServerInfo mailServer) {
BaseMailHostServerConfiguration serverConfiguration = new BaseMailHostServerConfiguration();
serverConfiguration.setHost(host);
if (mailServer.isMailServerUseSSL()) {
serverConfiguration.setPort(mailServer.getMailServerSSLPort());
serverConfiguration.setTransport(MailHostServerConfiguration.Transport.SMTPS);
} else {
serverConfiguration.setPort(mailServer.getMailServerPort());
serverConfiguration.setTransport(MailHostServerConfiguration.Transport.SMTP);
}
serverConfiguration.setStartTlsEnabled(mailServer.isMailServerUseTLS());
serverConfiguration.setUser(mailServer.getMailServerUsername());
serverConfiguration.setPassword(mailServer.getMailServerPassword());
return serverConfiguration;
}
protected static MailDefaultsConfiguration createMailDefaultsConfiguration(MailServerInfo serverInfo, MailServerInfo fallbackServerInfo) {
String defaultFrom = getDefaultValue(serverInfo, fallbackServerInfo, MailServerInfo::getMailServerDefaultFrom);
Charset defaultCharset = getDefaultValue(serverInfo, fallbackServerInfo, MailServerInfo::getMailServerDefaultCharset);
Collection<String> forceTo = getForceTo(serverInfo, fallbackServerInfo);
return new MailDefaultsConfigurationImpl(defaultFrom, defaultCharset, forceTo);
}
protected static <T> T getDefaultValue(MailServerInfo serverInfo, MailServerInfo fallbackServerInfo, Function<MailServerInfo, T> valueProvider) {
T value = null;
if (serverInfo != null) {
value = valueProvider.apply(serverInfo);
}
if (value == null) {
value = valueProvider.apply(fallbackServerInfo);
}
return value;
}
|
protected static Collection<String> getForceTo(MailServerInfo serverInfo, MailServerInfo fallbackServerInfo) {
String forceTo = null;
if (serverInfo != null) {
forceTo = serverInfo.getMailServerForceTo();
}
if (forceTo == null) {
forceTo = fallbackServerInfo.getMailServerForceTo();
}
if (forceTo == null) {
return Collections.emptyList();
}
return Arrays.stream(forceTo.split(",")).map(String::trim).toList();
}
}
|
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\cfg\mail\FlowableMailClientCreator.java
| 1
|
请完成以下Java代码
|
public boolean isContinueOnError() {
return this.continueOnError;
}
/**
* Sets whether initialization should continue when an error occurs when applying a
* schema or data script.
* @param continueOnError whether to continue when an error occurs.
*/
public void setContinueOnError(boolean continueOnError) {
this.continueOnError = continueOnError;
}
/**
* Returns the statement separator used in the schema and data scripts.
* @return the statement separator
*/
public String getSeparator() {
return this.separator;
}
/**
* Sets the statement separator to use when reading the schema and data scripts.
* @param separator statement separator used in the schema and data scripts
*/
public void setSeparator(String separator) {
this.separator = separator;
}
/**
* Returns the encoding to use when reading the schema and data scripts.
* @return the script encoding
*/
public @Nullable Charset getEncoding() {
return this.encoding;
}
|
/**
* Sets the encoding to use when reading the schema and data scripts.
* @param encoding encoding to use when reading the schema and data scripts
*/
public void setEncoding(@Nullable Charset encoding) {
this.encoding = encoding;
}
/**
* Gets the mode to use when determining whether database initialization should be
* performed.
* @return the initialization mode
* @since 2.5.1
*/
public DatabaseInitializationMode getMode() {
return this.mode;
}
/**
* Sets the mode the use when determining whether database initialization should be
* performed.
* @param mode the initialization mode
* @since 2.5.1
*/
public void setMode(DatabaseInitializationMode mode) {
this.mode = mode;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-sql\src\main\java\org\springframework\boot\sql\init\DatabaseInitializationSettings.java
| 1
|
请完成以下Java代码
|
private I_M_ShipmentSchedule getShipmentScheduleById(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return shipmentSchedulesById.computeIfAbsent(shipmentScheduleId, shipmentScheduleBL::getById);
}
public OrgId getOrgId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId);
return OrgId.ofRepoId(shipmentSchedule.getAD_Org_ID());
}
public BPartnerId getBPartnerId(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
final I_M_ShipmentSchedule shipmentSchedule = getShipmentScheduleById(shipmentScheduleId);
return scheduleEffectiveBL.getBPartnerId(shipmentSchedule);
}
@Nullable
public ShipperId getShipperId(@Nullable final String shipperInternalName)
{
if (Check.isBlank(shipperInternalName))
{
return null;
}
final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper);
|
return shipper != null
? ShipperId.ofRepoId(shipper.getM_Shipper_ID())
: null;
}
@Nullable
public String getTrackingURL(@NonNull final String shipperInternalName)
{
final I_M_Shipper shipper = shipperByInternalName.computeIfAbsent(shipperInternalName, this::loadShipper);
return shipper != null
? shipper.getTrackingURL()
: null;
}
@Nullable
private I_M_Shipper loadShipper(@NonNull final String shipperInternalName)
{
return shipperDAO.getByInternalName(ImmutableSet.of(shipperInternalName)).get(shipperInternalName);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\ShipmentService.java
| 1
|
请完成以下Java代码
|
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_BPartner_Location_ID (final int C_BPartner_Location_ID)
{
if (C_BPartner_Location_ID < 1)
set_Value (COLUMNNAME_C_BPartner_Location_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_Location_ID, C_BPartner_Location_ID);
}
@Override
public int getC_BPartner_Location_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Location_ID);
}
@Override
public void setC_BPartner_Representative_ID (final int C_BPartner_Representative_ID)
{
if (C_BPartner_Representative_ID < 1)
set_Value (COLUMNNAME_C_BPartner_Representative_ID, null);
else
set_Value (COLUMNNAME_C_BPartner_Representative_ID, C_BPartner_Representative_ID);
}
@Override
public int getC_BPartner_Representative_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BPartner_Representative_ID);
}
@Override
public void setC_Fiscal_Representation_ID (final int C_Fiscal_Representation_ID)
{
if (C_Fiscal_Representation_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Fiscal_Representation_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Fiscal_Representation_ID, C_Fiscal_Representation_ID);
}
@Override
public int getC_Fiscal_Representation_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Fiscal_Representation_ID);
}
@Override
public void setTaxID (final @Nullable java.lang.String TaxID)
{
set_Value (COLUMNNAME_TaxID, TaxID);
}
@Override
public java.lang.String getTaxID()
{
return get_ValueAsString(COLUMNNAME_TaxID);
}
@Override
public org.compiere.model.I_C_Country getTo_Country()
{
return get_ValueAsPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class);
}
@Override
public void setTo_Country(final org.compiere.model.I_C_Country To_Country)
{
set_ValueFromPO(COLUMNNAME_To_Country_ID, org.compiere.model.I_C_Country.class, To_Country);
}
@Override
public void setTo_Country_ID (final int To_Country_ID)
{
|
if (To_Country_ID < 1)
set_Value (COLUMNNAME_To_Country_ID, null);
else
set_Value (COLUMNNAME_To_Country_ID, To_Country_ID);
}
@Override
public int getTo_Country_ID()
{
return get_ValueAsInt(COLUMNNAME_To_Country_ID);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
@Override
public void setValidTo (final @Nullable java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
@Override
public java.sql.Timestamp getValidTo()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidTo);
}
@Override
public void setVATaxID (final java.lang.String VATaxID)
{
set_Value (COLUMNNAME_VATaxID, VATaxID);
}
@Override
public java.lang.String getVATaxID()
{
return get_ValueAsString(COLUMNNAME_VATaxID);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Fiscal_Representation.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public boolean matchesFilter(AlarmCommentTrigger trigger, AlarmCommentNotificationRuleTriggerConfig triggerConfig) {
if (trigger.getActionType() == ActionType.UPDATED_COMMENT && !triggerConfig.isNotifyOnCommentUpdate()) {
return false;
}
if (triggerConfig.isOnlyUserComments()) {
if (trigger.getComment().getType() == AlarmCommentType.SYSTEM) {
return false;
}
}
Alarm alarm = trigger.getAlarm();
return emptyOrContains(triggerConfig.getAlarmTypes(), alarm.getType()) &&
emptyOrContains(triggerConfig.getAlarmSeverities(), alarm.getSeverity()) &&
(isEmpty(triggerConfig.getAlarmStatuses()) || AlarmStatusFilter.from(triggerConfig.getAlarmStatuses()).matches(alarm));
}
@Override
public RuleOriginatedNotificationInfo constructNotificationInfo(AlarmCommentTrigger trigger) {
Alarm alarm = trigger.getAlarm();
String originatorName, originatorLabel;
if (alarm instanceof AlarmInfo) {
originatorName = ((AlarmInfo) alarm).getOriginatorName();
originatorLabel = ((AlarmInfo) alarm).getOriginatorLabel();
} else {
var infoOpt = entityService.fetchNameLabelAndCustomerDetails(trigger.getTenantId(), alarm.getOriginator());
originatorName = infoOpt.map(NameLabelAndCustomerDetails::getName).orElse(null);
originatorLabel = infoOpt.map(NameLabelAndCustomerDetails::getLabel).orElse(null);
}
return AlarmCommentNotificationInfo.builder()
.comment(trigger.getComment().getComment().get("text").asText())
.action(trigger.getActionType() == ActionType.ADDED_COMMENT ? "added" : "updated")
.userEmail(trigger.getUser().getEmail())
.userFirstName(trigger.getUser().getFirstName())
.userLastName(trigger.getUser().getLastName())
.alarmId(alarm.getUuidId())
|
.alarmType(alarm.getType())
.alarmOriginator(alarm.getOriginator())
.alarmOriginatorName(originatorName)
.alarmOriginatorLabel(originatorLabel)
.alarmSeverity(alarm.getSeverity())
.alarmStatus(alarm.getStatus())
.alarmCustomerId(alarm.getCustomerId())
.dashboardId(alarm.getDashboardId())
.build();
}
@Override
public NotificationRuleTriggerType getTriggerType() {
return NotificationRuleTriggerType.ALARM_COMMENT;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\AlarmCommentTriggerProcessor.java
| 2
|
请完成以下Java代码
|
public void reorderSlide(XMLSlideShow ppt, int slideNumber, int newSlideNumber) {
List<XSLFSlide> slides = ppt.getSlides();
XSLFSlide secondSlide = slides.get(slideNumber);
ppt.setSlideOrder(secondSlide, newSlideNumber);
}
/**
* Retrieve the placeholder inside a slide
*
* @param slide
* The slide
* @return List of placeholder inside a slide
*/
public List<XSLFShape> retrieveTemplatePlaceholders(XSLFSlide slide) {
List<XSLFShape> placeholders = new ArrayList<>();
for (XSLFShape shape : slide.getShapes()) {
if (shape instanceof XSLFAutoShape) {
placeholders.add(shape);
}
}
return placeholders;
}
/**
* Create a table
*
* @param slide
* Slide
*/
private void createTable(XSLFSlide slide) {
XSLFTable tbl = slide.createTable();
tbl.setAnchor(new Rectangle(50, 50, 450, 300));
int numColumns = 3;
int numRows = 5;
|
// header
XSLFTableRow headerRow = tbl.addRow();
headerRow.setHeight(50);
for (int i = 0; i < numColumns; i++) {
XSLFTableCell th = headerRow.addCell();
XSLFTextParagraph p = th.addNewTextParagraph();
p.setTextAlign(TextParagraph.TextAlign.CENTER);
XSLFTextRun r = p.addNewTextRun();
r.setText("Header " + (i + 1));
r.setBold(true);
r.setFontColor(Color.white);
th.setFillColor(new Color(79, 129, 189));
th.setBorderWidth(TableCell.BorderEdge.bottom, 2.0);
th.setBorderColor(TableCell.BorderEdge.bottom, Color.white);
// all columns are equally sized
tbl.setColumnWidth(i, 150);
}
// data
for (int rownum = 0; rownum < numRows; rownum++) {
XSLFTableRow tr = tbl.addRow();
tr.setHeight(50);
for (int i = 0; i < numColumns; i++) {
XSLFTableCell cell = tr.addCell();
XSLFTextParagraph p = cell.addNewTextParagraph();
XSLFTextRun r = p.addNewTextRun();
r.setText("Cell " + (i * rownum + 1));
if (rownum % 2 == 0) {
cell.setFillColor(new Color(208, 216, 232));
} else {
cell.setFillColor(new Color(233, 247, 244));
}
}
}
}
}
|
repos\tutorials-master\apache-poi-2\src\main\java\com\baeldung\poi\powerpoint\PowerPointHelper.java
| 1
|
请完成以下Java代码
|
public int getXmlRowNumber() {
return xmlRowNumber;
}
public void setXmlRowNumber(int xmlRowNumber) {
this.xmlRowNumber = xmlRowNumber;
}
public int getXmlColumnNumber() {
return xmlColumnNumber;
}
public void setXmlColumnNumber(int xmlColumnNumber) {
this.xmlColumnNumber = xmlColumnNumber;
}
public double getRotation() {
return rotation;
}
public void setRotation(double rotation) {
this.rotation = rotation;
}
public boolean equals(GraphicInfo ginfo) {
if (this.getX() != ginfo.getX()) {
return false;
}
if (this.getY() != ginfo.getY()) {
return false;
}
|
if (this.getHeight() != ginfo.getHeight()) {
return false;
}
if (this.getWidth() != ginfo.getWidth()) {
return false;
}
if (this.getRotation() != ginfo.getRotation()) {
return false;
}
// check for zero value in case we are comparing model value to BPMN DI value
// model values do not have xml location information
if (0 != this.getXmlColumnNumber() && 0 != ginfo.getXmlColumnNumber() && this.getXmlColumnNumber() != ginfo.getXmlColumnNumber()) {
return false;
}
if (0 != this.getXmlRowNumber() && 0 != ginfo.getXmlRowNumber() && this.getXmlRowNumber() != ginfo.getXmlRowNumber()) {
return false;
}
// only check for elements that support this value
if (null != this.getExpanded() && null != ginfo.getExpanded() && !this.getExpanded().equals(ginfo.getExpanded())) {
return false;
}
return true;
}
}
|
repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\GraphicInfo.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void onSuccess(ValidationResult validationResult) {
try {
AggregationParams params;
if (Aggregation.NONE.equals(agg)) {
params = AggregationParams.none();
} else if (intervalType == null || IntervalType.MILLISECONDS.equals(intervalType)) {
params = interval == 0L ? AggregationParams.none() : AggregationParams.milliseconds(agg, interval);
} else {
params = AggregationParams.calendar(agg, intervalType, timeZone);
}
List<ReadTsKvQuery> queries = keys.stream().map(key -> new BaseReadTsKvQuery(key, startTs, endTs, params, limit, orderBy)).collect(Collectors.toList());
Futures.addCallback(tsService.findAll(currentUser.getTenantId(), entityId, queries), new FutureCallback<>() {
@Override
public void onSuccess(List<TsKvEntry> result) {
future.set(result);
}
@Override
public void onFailure(Throwable t) {
future.setException(t);
}
|
}, MoreExecutors.directExecutor());
} catch (Throwable e) {
onFailure(e);
}
}
@Override
public void onFailure(Throwable t) {
future.setException(t);
}
});
return future;
}
}
|
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\telemetry\DefaultTbTelemetryService.java
| 2
|
请完成以下Java代码
|
public String getResourceId() {
if (missingAuthorizations.size() == 1) {
return missingAuthorizations.get(0).getResourceId();
}
return null;
}
/**
* @return Disjunctive list of {@link MissingAuthorization} from
* which a user needs to have at least one for the authorization to pass
*/
public List<MissingAuthorization> getMissingAuthorizations() {
return Collections.unmodifiableList(missingAuthorizations);
}
/**
* Generate exception message from the missing authorizations.
*
* @param userId to use
* @param missingAuthorizations to use
* @return The prepared exception message
*/
private static String generateExceptionMessage(String userId, List<MissingAuthorization> missingAuthorizations) {
StringBuilder sBuilder = new StringBuilder();
sBuilder.append("The user with id '");
sBuilder.append(userId);
sBuilder.append("' does not have one of the following permissions: ");
sBuilder.append(generateMissingAuthorizationsList(missingAuthorizations));
return sBuilder.toString();
}
/**
* Generate a String containing a list of missing authorizations.
*
* @param missingAuthorizations
*/
public static String generateMissingAuthorizationsList(List<MissingAuthorization> missingAuthorizations) {
StringBuilder sBuilder = new StringBuilder();
boolean first = true;
for(MissingAuthorization missingAuthorization: missingAuthorizations) {
if (!first) {
sBuilder.append(" or ");
} else {
first = false;
}
sBuilder.append(generateMissingAuthorizationMessage(missingAuthorization));
}
return sBuilder.toString();
|
}
/**
* Generated exception message for the missing authorization.
*
* @param exceptionInfo to use
*/
private static String generateMissingAuthorizationMessage(MissingAuthorization exceptionInfo) {
StringBuilder builder = new StringBuilder();
String permissionName = exceptionInfo.getViolatedPermissionName();
String resourceType = exceptionInfo.getResourceType();
String resourceId = exceptionInfo.getResourceId();
builder.append("'");
builder.append(permissionName);
builder.append("' permission on resource '");
builder.append((resourceId != null ? (resourceId+"' of type '") : "" ));
builder.append(resourceType);
builder.append("'");
return builder.toString();
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\AuthorizationException.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Integer createOrder(Long userId, Long productId, Integer price) throws Exception {
Integer amount = 1; // 购买数量,暂时设置为 1。
logger.info("[createOrder] 当前 XID: {}", RootContext.getXID());
// 扣减库存
this.reduceStock(productId, amount);
// 扣减余额
this.reduceBalance(userId, price);
// 保存订单
OrderDO order = new OrderDO().setUserId(userId).setProductId(productId).setPayAmount(amount * price);
orderDao.saveOrder(order);
logger.info("[createOrder] 保存订单: {}", order.getId());
// 返回订单编号
return order.getId();
}
private void reduceStock(Long productId, Integer amount) throws IOException {
// 参数拼接
JSONObject params = new JSONObject().fluentPut("productId", String.valueOf(productId))
.fluentPut("amount", String.valueOf(amount));
// 执行调用
HttpResponse response = DefaultHttpExecutor.getInstance().executePost("http://127.0.0.1:8082", "/product/reduce-stock",
params, HttpResponse.class);
// 解析结果
Boolean success = Boolean.valueOf(EntityUtils.toString(response.getEntity()));
if (!success) {
throw new RuntimeException("扣除库存失败");
}
}
|
private void reduceBalance(Long userId, Integer price) throws IOException {
// 参数拼接
JSONObject params = new JSONObject().fluentPut("userId", String.valueOf(userId))
.fluentPut("price", String.valueOf(price));
// 执行调用
HttpResponse response = DefaultHttpExecutor.getInstance().executePost("http://127.0.0.1:8083", "/account/reduce-balance",
params, HttpResponse.class);
// 解析结果
Boolean success = Boolean.valueOf(EntityUtils.toString(response.getEntity()));
if (!success) {
throw new RuntimeException("扣除余额失败");
}
}
}
|
repos\SpringBoot-Labs-master\lab-52\lab-52-seata-at-httpclient-demo\lab-52-seata-at-httpclient-demo-order-service\src\main\java\cn\iocoder\springboot\lab52\orderservice\service\OrderServiceImpl.java
| 2
|
请完成以下Java代码
|
protected String getDeploymentMode() {
return DEPLOYMENT_MODE;
}
@Override
protected void deployResourcesInternal(String deploymentNameHint, Resource[] resources, AppEngine engine) {
AppRepositoryService repositoryService = engine.getAppRepositoryService();
// Create a separate deployment for each resource using the resource name
for (final Resource resource : resources) {
String resourceName = determineResourceName(resource);
if (resourceName.contains("/")) {
resourceName = resourceName.substring(resourceName.lastIndexOf('/') + 1);
} else if (resourceName.contains("\\")) {
resourceName = resourceName.substring(resourceName.lastIndexOf('\\') + 1);
}
final AppDeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(resourceName);
|
addResource(resource, resourceName, deploymentBuilder);
try {
deploymentBuilder.deploy();
} catch (RuntimeException e) {
if (isThrowExceptionOnDeploymentFailure()) {
throw e;
} else {
LOGGER.warn("Exception while autodeploying app definition for resource {}. "
+ "This exception can be ignored if the root cause indicates a unique constraint violation, "
+ "which is typically caused by two (or more) servers booting up at the exact same time and deploying the same definitions. ", resource, e);
}
}
}
}
}
|
repos\flowable-engine-main\modules\flowable-app-engine-spring\src\main\java\org\flowable\app\spring\autodeployment\DefaultAutoDeploymentStrategy.java
| 1
|
请完成以下Java代码
|
public boolean remove(E element) {
if (set.remove(element)) {
list.remove(element);
return true;
}
return false;
}
public int indexOf(E element) {
return list.indexOf(element);
}
public E get(int index) {
return list.get(index);
}
public boolean contains(E element) {
|
return set.contains(element);
}
public int size() {
return list.size();
}
public boolean isEmpty() {
return list.isEmpty();
}
public void clear() {
list.clear();
set.clear();
}
}
|
repos\tutorials-master\core-java-modules\core-java-collections-set-2\src\main\java\com\baeldung\linkedhashsetindexof\ListAndSetApproach.java
| 1
|
请完成以下Java代码
|
public String toString()
{
return "";
}
public String toString(String result, int size)
{
return "";
}
public String parse(String str, int size)
{
return "";
}
public String parse(String str, int size1, String result, int size2)
{
return "";
}
|
// set token-level penalty. It would be useful for implementing
// Dual decompositon decoding.
// e.g.
// "Dual Decomposition for Parsing with Non-Projective Head Automata"
// Terry Koo Alexander M. Rush Michael Collins Tommi Jaakkola David Sontag
public void setPenalty(int i, int j, double penalty)
{
}
public double penalty(int i, int j)
{
return 0.0;
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Tagger.java
| 1
|
请完成以下Java代码
|
public String getUserOperationId() {
return userOperationId;
}
public Date getTime() {
return time;
}
public Date getRemovalTime() {
return removalTime;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public static HistoricDetailDto fromHistoricDetail(HistoricDetail historicDetail) {
HistoricDetailDto dto = null;
if (historicDetail instanceof HistoricFormField) {
HistoricFormField historicFormField = (HistoricFormField) historicDetail;
dto = HistoricFormFieldDto.fromHistoricFormField(historicFormField);
} else if (historicDetail instanceof HistoricVariableUpdate) {
HistoricVariableUpdate historicVariableUpdate = (HistoricVariableUpdate) historicDetail;
dto = HistoricVariableUpdateDto.fromHistoricVariableUpdate(historicVariableUpdate);
}
fromHistoricDetail(historicDetail, dto);
return dto;
}
protected static void fromHistoricDetail(HistoricDetail historicDetail, HistoricDetailDto dto) {
dto.id = historicDetail.getId();
dto.processDefinitionKey = historicDetail.getProcessDefinitionKey();
|
dto.processDefinitionId = historicDetail.getProcessDefinitionId();
dto.processInstanceId = historicDetail.getProcessInstanceId();
dto.activityInstanceId = historicDetail.getActivityInstanceId();
dto.executionId = historicDetail.getExecutionId();
dto.taskId = historicDetail.getTaskId();
dto.caseDefinitionKey = historicDetail.getCaseDefinitionKey();
dto.caseDefinitionId = historicDetail.getCaseDefinitionId();
dto.caseInstanceId = historicDetail.getCaseInstanceId();
dto.caseExecutionId = historicDetail.getCaseExecutionId();
dto.tenantId = historicDetail.getTenantId();
dto.userOperationId = historicDetail.getUserOperationId();
dto.time = historicDetail.getTime();
dto.removalTime = historicDetail.getRemovalTime();
dto.rootProcessInstanceId = historicDetail.getRootProcessInstanceId();
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricDetailDto.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class CreateRemittanceAdviceLineRequest
{
@NonNull
RemittanceAdviceId remittanceAdviceId;
@NonNull
OrgId orgId;
@NonNull
String lineIdentifier;
@NonNull
BigDecimal remittedAmount;
@Nullable
BigDecimal invoiceGrossAmount;
@Nullable
BigDecimal paymentDiscountAmount;
@Nullable
|
BigDecimal serviceFeeAmount;
@Nullable
String invoiceIdentifier;
@Nullable
BPartnerId bpartnerIdentifier;
@Nullable
String externalInvoiceDocBaseType;
@Nullable
Instant dateInvoiced;
@Nullable
BigDecimal serviceFeeVatRate;
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\remittanceadvice\CreateRemittanceAdviceLineRequest.java
| 2
|
请完成以下Java代码
|
public String toString() {
return toString(new TreePath(this.model.getRoot()));
}
/**
* Convenience method for getting a string that describes the tree
* starting at path.
*
* @param path the treepath root of the tree
*/
private String toString(TreePath path) {
String checkString = "n";
String greyString = "n";
String enableString = "n";
if (isPathChecked(path)) {
checkString = "y";
}
|
if (isPathEnabled(path)) {
enableString = "y";
}
if (isPathGreyed(path)) {
greyString = "y";
}
String description = "Path checked: " + checkString + " greyed: " + greyString + " enabled: " + enableString + " Name: "
+ path.toString() + "\n";
for (TreePath childPath : getChildrenPath(path)) {
description += toString(childPath);
}
return description;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\it\cnr\imaa\essi\lablib\gui\checkboxtree\DefaultTreeCheckingModel.java
| 1
|
请完成以下Java代码
|
public void setAD_UI_Element_ID (int AD_UI_Element_ID)
{
if (AD_UI_Element_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_UI_Element_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_UI_Element_ID, Integer.valueOf(AD_UI_Element_ID));
}
/** Get UI Element.
@return UI Element */
@Override
public int getAD_UI_Element_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_UI_Element_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* TooltipIconName AD_Reference_ID=540912
* Reference name: TooltipIcon
*/
public static final int TOOLTIPICONNAME_AD_Reference_ID=540912;
/** text = text */
public static final String TOOLTIPICONNAME_Text = "text";
/** Set Tooltip Icon Name.
@param TooltipIconName Tooltip Icon Name */
@Override
|
public void setTooltipIconName (java.lang.String TooltipIconName)
{
set_Value (COLUMNNAME_TooltipIconName, TooltipIconName);
}
/** Get Tooltip Icon Name.
@return Tooltip Icon Name */
@Override
public java.lang.String getTooltipIconName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TooltipIconName);
}
/**
* Type AD_Reference_ID=540910
* Reference name: Type_AD_UI_ElementField
*/
public static final int TYPE_AD_Reference_ID=540910;
/** widget = widget */
public static final String TYPE_Widget = "widget";
/** tooltip = tooltip */
public static final String TYPE_Tooltip = "tooltip";
/** Set Art.
@param Type Art */
@Override
public void setType (java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Art */
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UI_ElementField.java
| 1
|
请完成以下Java代码
|
public int getNumDoors() {
return numDoors;
}
public String getFeatures() {
return features;
}
public static class CarBuilder {
private final String make;
private final String model;
private final int year;
private String color = "unknown";
private boolean automatic = false;
private int numDoors = 4;
private String features = "";
public CarBuilder(String make, String model, int year) {
this.make = make;
this.model = model;
this.year = year;
}
public CarBuilder color(String color) {
this.color = color;
return this;
}
public CarBuilder automatic(boolean automatic) {
this.automatic = automatic;
|
return this;
}
public CarBuilder numDoors(int numDoors) {
this.numDoors = numDoors;
return this;
}
public CarBuilder features(String features) {
this.features = features;
return this;
}
public Car build() {
return new Car(this);
}
}
@Override
public String toString() {
return "Car [make=" + make + ", model=" + model + ", year=" + year + ", color=" + color + ", automatic=" + automatic + ", numDoors=" + numDoors + ", features=" + features + "]";
}
}
|
repos\tutorials-master\core-java-modules\core-java-lang-oop-methods-2\src\main\java\com\baeldung\methods\Car.java
| 1
|
请完成以下Java代码
|
public void setClient_Info (final @Nullable java.lang.String Client_Info)
{
set_Value (COLUMNNAME_Client_Info, Client_Info);
}
@Override
public java.lang.String getClient_Info()
{
return get_ValueAsString(COLUMNNAME_Client_Info);
}
@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 setHostKey (final @Nullable java.lang.String HostKey)
{
set_Value (COLUMNNAME_HostKey, HostKey);
}
@Override
public java.lang.String getHostKey()
{
return get_ValueAsString(COLUMNNAME_HostKey);
}
@Override
public void setIsLoginIncorrect (final boolean IsLoginIncorrect)
{
set_Value (COLUMNNAME_IsLoginIncorrect, IsLoginIncorrect);
}
@Override
public boolean isLoginIncorrect()
{
return get_ValueAsBoolean(COLUMNNAME_IsLoginIncorrect);
}
@Override
public void setLoginDate (final @Nullable java.sql.Timestamp LoginDate)
{
set_Value (COLUMNNAME_LoginDate, LoginDate);
}
@Override
public java.sql.Timestamp getLoginDate()
{
return get_ValueAsTimestamp(COLUMNNAME_LoginDate);
}
@Override
public void setLoginUsername (final @Nullable java.lang.String LoginUsername)
{
set_Value (COLUMNNAME_LoginUsername, LoginUsername);
}
@Override
public java.lang.String getLoginUsername()
{
return get_ValueAsString(COLUMNNAME_LoginUsername);
}
@Override
public void setProcessed (final boolean Processed)
{
set_ValueNoCheck (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
|
@Override
public void setRemote_Addr (final @Nullable java.lang.String Remote_Addr)
{
set_ValueNoCheck (COLUMNNAME_Remote_Addr, Remote_Addr);
}
@Override
public java.lang.String getRemote_Addr()
{
return get_ValueAsString(COLUMNNAME_Remote_Addr);
}
@Override
public void setRemote_Host (final @Nullable java.lang.String Remote_Host)
{
set_ValueNoCheck (COLUMNNAME_Remote_Host, Remote_Host);
}
@Override
public java.lang.String getRemote_Host()
{
return get_ValueAsString(COLUMNNAME_Remote_Host);
}
@Override
public void setWebSession (final @Nullable java.lang.String WebSession)
{
set_ValueNoCheck (COLUMNNAME_WebSession, WebSession);
}
@Override
public java.lang.String getWebSession()
{
return get_ValueAsString(COLUMNNAME_WebSession);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Session.java
| 1
|
请完成以下Java代码
|
public class DatabaseEventFlusher extends AbstractEventFlusher {
private static final Logger LOGGER = LoggerFactory.getLogger(DatabaseEventFlusher.class);
@Override
public void closing(CommandContext commandContext) {
if (commandContext.getException() != null) {
return; // Not interested in events about exceptions
}
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
EventLogEntryEntityManager eventLogEntryEntityManager = processEngineConfiguration.getEventLogEntryEntityManager();
for (EventLoggerEventHandler eventHandler : eventHandlers) {
try {
eventLogEntryEntityManager.insert(eventHandler.generateEventLogEntry(commandContext), false);
} catch (Exception e) {
LOGGER.warn("Could not create event log", e);
}
}
}
|
@Override
public void afterSessionsFlush(CommandContext commandContext) {
}
@Override
public void closeFailure(CommandContext commandContext) {
}
@Override
public Integer order() {
return 100;
}
@Override
public boolean multipleAllowed() {
return false;
}
}
|
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\event\logger\DatabaseEventFlusher.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
IQueryBuilder<I_MD_Candidate_ATP_QueryResult> createDBQueryForStockQueryBuilder(@NonNull final AvailableToPromiseQuery query)
{
final IQueryBL queryBL = Services.get(IQueryBL.class);
final IQueryBuilder<I_MD_Candidate_ATP_QueryResult> queryBuilder = //
queryBL.createQueryBuilder(I_MD_Candidate_ATP_QueryResult.class);
if (!isRealSqlQuery())
{
// Date; this only makes sense in unit test's there the I_MD_Candidate_ATP_QueryResult records to return were hand-crafted for the respective test
queryBuilder.addCompareFilter(I_MD_Candidate_ATP_QueryResult.COLUMN_DateProjected, Operator.LESS_OR_EQUAL, TimeUtil.asTimestamp(query.getDate()));
}
// Warehouse
final Set<WarehouseId> warehouseIds = query.getWarehouseIds();
if (!warehouseIds.isEmpty())
{
queryBuilder.addInArrayFilter(I_MD_Candidate_ATP_QueryResult.COLUMN_M_Warehouse_ID, warehouseIds);
}
// Product
final List<Integer> productIds = query.getProductIds();
if (!productIds.isEmpty())
{
queryBuilder.addInArrayFilter(I_MD_Candidate_ATP_QueryResult.COLUMN_M_Product_ID, productIds);
}
// BPartner
final BPartnerClassifier bpartner = query.getBpartner();
if (bpartner.isAny())
{
// nothing to filter
}
else if (bpartner.isNone())
|
{
queryBuilder.addEqualsFilter(I_MD_Candidate_ATP_QueryResult.COLUMNNAME_C_BPartner_Customer_ID, null);
}
else // specific
{
queryBuilder.addInArrayFilter(I_MD_Candidate_ATP_QueryResult.COLUMNNAME_C_BPartner_Customer_ID, bpartner.getBpartnerId(), null);
}
//
// Storage Attributes Key
final ImmutableList<AttributesKeyPattern> storageAttributesKeyPatterns = query.getStorageAttributesKeyPatterns();
if(!storageAttributesKeyPatterns.isEmpty())
{
final AttributesKeyQueryHelper<I_MD_Candidate_ATP_QueryResult> helper = AttributesKeyQueryHelper.createFor(I_MD_Candidate_ATP_QueryResult.COLUMN_StorageAttributesKey);
final IQueryFilter<I_MD_Candidate_ATP_QueryResult> attributesFilter = helper.createFilter(storageAttributesKeyPatterns);
queryBuilder.filter(attributesFilter);
}
return queryBuilder;
}
private boolean isRealSqlQuery()
{
final boolean isRealSqlQuery = !Adempiere.isUnitTestMode();
return isRealSqlQuery;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\atp\AvailableToPromiseSqlHelper.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
protected static class TokenRelayConfiguration {
@Bean
public TokenRelayGatewayFilterFactory tokenRelayGatewayFilterFactory(
ObjectProvider<ReactiveOAuth2AuthorizedClientManager> clientManager) {
return new TokenRelayGatewayFilterFactory(clientManager);
}
}
}
class GatewayHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, ClassLoader classLoader) {
if (!ClassUtils.isPresent("org.springframework.cloud.gateway.route.RouteLocator", classLoader)) {
return;
}
hints.reflection()
|
.registerType(TypeReference.of(FilterDefinition.class),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.registerType(TypeReference.of(PredicateDefinition.class),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.registerType(TypeReference.of(AbstractNameValueGatewayFilterFactory.NameValueConfig.class),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS))
.registerType(TypeReference
.of("org.springframework.cloud.gateway.discovery.DiscoveryClientRouteDefinitionLocator$DelegatingServiceInstance"),
hint -> hint.withMembers(MemberCategory.DECLARED_FIELDS, MemberCategory.INVOKE_DECLARED_METHODS,
MemberCategory.INVOKE_DECLARED_CONSTRUCTORS));
}
}
|
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GatewayAutoConfiguration.java
| 2
|
请完成以下Java代码
|
public DocumentFilterDescriptorsProvider getFilterDescriptorsProvider()
{
if (filterDescriptorsProvider == null)
{
filterDescriptorsProvider = ImmutableDocumentFilterDescriptorsProvider.of(createFilterDescriptors());
}
return filterDescriptorsProvider;
}
public Collection<DocumentFilterDescriptor> getFilterDescriptors()
{
return getFilterDescriptorsProvider().getAll();
}
private List<DocumentFilterDescriptor> createFilterDescriptors()
{
return ImmutableList.of(
createIsCustomerFilterDescriptor(),
createIsVendorFilterDescriptor());
}
private DocumentFilterDescriptor createIsCustomerFilterDescriptor()
{
return DocumentFilterDescriptor.builder()
.setFilterId(FILTERID_IsCustomer)
.setFrequentUsed(true)
.addParameter(DocumentFilterParamDescriptor.builder()
.fieldName(PARAM_IsCustomer)
.displayName(Services.get(IMsgBL.class).translatable(PARAM_IsCustomer))
.widgetType(DocumentFieldWidgetType.YesNo))
.build();
}
private DocumentFilterDescriptor createIsVendorFilterDescriptor()
{
return DocumentFilterDescriptor.builder()
.setFilterId(FILTERID_IsVendor)
.setFrequentUsed(true)
.addParameter(DocumentFilterParamDescriptor.builder()
.fieldName(PARAM_IsVendor)
.displayName(Services.get(IMsgBL.class).translatable(PARAM_IsVendor))
.widgetType(DocumentFieldWidgetType.YesNo))
.build();
}
public static Predicate<PricingConditionsRow> isEditableRowOrMatching(final DocumentFilterList filters)
{
if (filters.isEmpty())
{
return Predicates.alwaysTrue();
}
final boolean showCustomers = filters.getParamValueAsBoolean(FILTERID_IsCustomer, PARAM_IsCustomer, false);
final boolean showVendors = filters.getParamValueAsBoolean(FILTERID_IsVendor, PARAM_IsVendor, false);
|
final boolean showAll = !showCustomers && !showVendors;
if (showAll)
{
return Predicates.alwaysTrue();
}
return row -> row.isEditable()
|| ((showCustomers && row.isCustomer()) || (showVendors && row.isVendor()));
}
public DocumentFilterList extractFilters(@NonNull final JSONFilterViewRequest filterViewRequest)
{
return filterViewRequest.getFiltersUnwrapped(getFilterDescriptorsProvider());
}
public DocumentFilterList extractFilters(@NonNull final CreateViewRequest request)
{
return request.isUseAutoFilters()
? getDefaultFilters()
: request.getFiltersUnwrapped(getFilterDescriptorsProvider());
}
private DocumentFilterList getDefaultFilters()
{
if (defaultFilters == null)
{
final DocumentFilter isCustomer = DocumentFilter.singleParameterFilter(FILTERID_IsCustomer, PARAM_IsCustomer, Operator.EQUAL, true);
defaultFilters = DocumentFilterList.of(isCustomer);
}
return defaultFilters;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\PricingConditionsViewFilters.java
| 1
|
请完成以下Java代码
|
private static void dbUpdateTaxCategory(final ImportRecordsSelection selection)
{
StringBuilder sql = new StringBuilder("UPDATE ")
.append(targetTableName + " i ")
.append(" SET C_TaxCategory_ID=(SELECT C_TaxCategory_ID FROM C_TaxCategory tc")
.append(" WHERE tc.isActive='Y' AND i.C_TaxCategory_Name=tc.Name AND tc.AD_Client_ID in (i.AD_Client_ID, 0) ORDER BY tc.AD_Client_ID DESC LIMIT 1) ")
.append("WHERE C_TaxCategory_ID IS NULL")
.append(" AND " + COLUMNNAME_I_IsImported + "='N'")
.append(selection.toSqlWhereClause("i"));
DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
sql = new StringBuilder("UPDATE ")
.append(targetTableName)
.append(" SET " + COLUMNNAME_I_IsImported + "='E', " + COLUMNNAME_I_ErrorMsg + "=" + COLUMNNAME_I_ErrorMsg + "||'ERR=Invalid TaxCategory,' ")
.append("WHERE C_TaxCategory_ID IS NULL AND C_TaxCategory_Name IS NOT NULL")
.append(" AND " + COLUMNNAME_I_IsImported + "<>'Y'")
.append(selection.toSqlWhereClause());
DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
}
private static void dbUpdateCampaignPrice(final ImportRecordsSelection selection, final Properties ctx)
|
{
final String sql = "UPDATE "
+ targetTableName + " i "
+ " SET C_Campaign_Price_ID=(SELECT C_Campaign_Price_ID FROM C_Campaign_Price c"
+ " WHERE i.M_Product_ID=c.M_Product_ID "
+ " AND (i.C_BPartner_ID=c.C_BPartner_ID OR (i.C_BPartner_ID IS NULL AND c.C_BPartner_ID IS NULL) ) "
+ " AND (i.C_BP_Group_ID=c.C_BP_Group_ID OR (i.C_BP_Group_ID IS NULL AND c.C_BP_Group_ID IS NULL ) ) "
+ " AND (i.M_PricingSystem_ID=c.M_PricingSystem_ID OR i.M_PricingSystem_ID IS NULL and c.M_PricingSystem_ID IS NULL) "
+ " AND i.C_Country_ID=c.C_Country_ID "
+ " AND i.C_UOM_ID=c.C_UOM_ID "
+ " AND i.C_TaxCategory_ID=c.C_TaxCategory_ID "
+ " AND i.AD_Org_ID=c.AD_Org_ID "
+ " AND i.AD_Client_ID=c.AD_Client_ID "
+ " AND i.C_Country_ID=c.C_Country_ID "
+ " AND i.validFrom = c.validFrom ORDER BY updated DESC LIMIT 1) "
+ "WHERE C_Campaign_Price_ID IS NULL"
+ " AND " + COLUMNNAME_I_IsImported + "='N'"
+ selection.toSqlWhereClause("i");
DB.executeUpdateAndThrowExceptionOnFail(sql, ITrx.TRXNAME_ThreadInherited);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\campaign_price\impexp\CampaignPriceImportTableSqlUpdater.java
| 1
|
请完成以下Java代码
|
public class WebuiDocumentReferenceCandidate
{
private final RelatedDocumentsCandidateGroup relatedDocumentsCandidateGroup;
private final ITranslatableString filterCaption;
public WebuiDocumentReferenceCandidate(
@NonNull final RelatedDocumentsCandidateGroup relatedDocumentsCandidateGroup,
@NonNull final ITranslatableString filterCaption)
{
this.relatedDocumentsCandidateGroup = relatedDocumentsCandidateGroup;
this.filterCaption = filterCaption;
}
public Stream<WebuiDocumentReference> evaluateAndStream(@NonNull final RelatedDocumentsEvaluationContext context)
{
return relatedDocumentsCandidateGroup.evaluateAndStream(context)
.map(relatedDocuments -> toDocumentReference(relatedDocuments, filterCaption));
}
public static WebuiDocumentReference toDocumentReference(
@NonNull final RelatedDocuments relatedDocuments,
@NonNull final ITranslatableString filterCaption)
|
{
return WebuiDocumentReference.builder()
.id(WebuiDocumentReferenceId.ofRelatedDocumentsId(relatedDocuments.getId()))
.internalName(relatedDocuments.getInternalName())
.caption(relatedDocuments.getCaption())
.targetWindow(toDocumentReferenceTargetWindow(relatedDocuments.getTargetWindow()))
.priority(relatedDocuments.getPriority())
.documentsCount(relatedDocuments.getRecordCount())
.filter(MQueryDocumentFilterHelper.createDocumentFilterFromMQuery(relatedDocuments.getQuery(), filterCaption))
.loadDuration(relatedDocuments.getRecordCountDuration())
.build();
}
private static WebuiDocumentReferenceTargetWindow toDocumentReferenceTargetWindow(@NonNull final RelatedDocumentsTargetWindow relatedDocumentsTargetWindow)
{
final WindowId windowId = WindowId.of(relatedDocumentsTargetWindow.getAdWindowId());
final String category = relatedDocumentsTargetWindow.getCategory();
return category != null
? WebuiDocumentReferenceTargetWindow.ofWindowIdAndCategory(windowId, category)
: WebuiDocumentReferenceTargetWindow.ofWindowId(windowId);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\references\WebuiDocumentReferenceCandidate.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public static class Ssl {
/**
* Whether to enable SSL support. Enabled automatically if "bundle" is provided
* unless specified otherwise.
*/
private @Nullable Boolean enabled;
/**
* SSL bundle name.
*/
private @Nullable String bundle;
public boolean isEnabled() {
return (this.enabled != null) ? this.enabled : this.bundle != null;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public @Nullable String getBundle() {
return this.bundle;
}
public void setBundle(@Nullable String bundle) {
this.bundle = bundle;
}
}
/**
* Jedis client properties.
*/
public static class Jedis {
/**
* Jedis pool configuration.
*/
private final Pool pool = new Pool();
public Pool getPool() {
return this.pool;
}
}
/**
* Lettuce client properties.
*/
public static class Lettuce {
/**
* Shutdown timeout.
*/
private Duration shutdownTimeout = Duration.ofMillis(100);
/**
* Defines from which Redis nodes data is read.
*/
private @Nullable String readFrom;
/**
* Lettuce pool configuration.
*/
private final Pool pool = new Pool();
private final Cluster cluster = new Cluster();
public Duration getShutdownTimeout() {
return this.shutdownTimeout;
}
public void setShutdownTimeout(Duration shutdownTimeout) {
this.shutdownTimeout = shutdownTimeout;
}
public @Nullable String getReadFrom() {
return this.readFrom;
}
public void setReadFrom(@Nullable String readFrom) {
|
this.readFrom = readFrom;
}
public Pool getPool() {
return this.pool;
}
public Cluster getCluster() {
return this.cluster;
}
public static class Cluster {
private final Refresh refresh = new Refresh();
public Refresh getRefresh() {
return this.refresh;
}
public static class Refresh {
/**
* Whether to discover and query all cluster nodes for obtaining the
* cluster topology. When set to false, only the initial seed nodes are
* used as sources for topology discovery.
*/
private boolean dynamicRefreshSources = true;
/**
* Cluster topology refresh period.
*/
private @Nullable Duration period;
/**
* Whether adaptive topology refreshing using all available refresh
* triggers should be used.
*/
private boolean adaptive;
public boolean isDynamicRefreshSources() {
return this.dynamicRefreshSources;
}
public void setDynamicRefreshSources(boolean dynamicRefreshSources) {
this.dynamicRefreshSources = dynamicRefreshSources;
}
public @Nullable Duration getPeriod() {
return this.period;
}
public void setPeriod(@Nullable Duration period) {
this.period = period;
}
public boolean isAdaptive() {
return this.adaptive;
}
public void setAdaptive(boolean adaptive) {
this.adaptive = adaptive;
}
}
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-data-redis\src\main\java\org\springframework\boot\data\redis\autoconfigure\DataRedisProperties.java
| 2
|
请完成以下Java代码
|
public class TreeBuilderException extends ELException {
private static final long serialVersionUID = 1L;
private final String expression;
private final int position;
private final String encountered;
private final String expected;
public TreeBuilderException(String expression, int position, String encountered, String expected, String message) {
super(LocalMessages.get("error.build", expression, message));
this.expression = expression;
this.position = position;
this.encountered = encountered;
this.expected = expected;
}
/**
* @return the expression string
*/
public String getExpression() {
return expression;
}
/**
* @return the error position
*/
|
public int getPosition() {
return position;
}
/**
* @return the substring (or description) that has been encountered
*/
public String getEncountered() {
return encountered;
}
/**
* @return the substring (or description) that was expected
*/
public String getExpected() {
return expected;
}
}
|
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\TreeBuilderException.java
| 1
|
请完成以下Java代码
|
public static HalVariableValue generateTaskVariableValue(VariableInstance variableInstance, String taskId) {
return fromVariableInstance(variableInstance)
.link(REL_SELF, TaskRestService.PATH, taskId, "localVariables");
}
public static HalVariableValue generateExecutionVariableValue(VariableInstance variableInstance, String executionId) {
return fromVariableInstance(variableInstance)
.link(REL_SELF, ExecutionRestService.PATH, executionId, "localVariables");
}
public static HalVariableValue generateProcessInstanceVariableValue(VariableInstance variableInstance, String processInstanceId) {
return fromVariableInstance(variableInstance)
.link(REL_SELF, ProcessInstanceRestService.PATH, processInstanceId, "variables");
}
public static HalVariableValue generateCaseExecutionVariableValue(VariableInstance variableInstance, String caseExecutionId) {
return fromVariableInstance(variableInstance)
.link(REL_SELF, CaseExecutionRestService.PATH, caseExecutionId, "localVariables");
}
public static HalVariableValue generateCaseInstanceVariableValue(VariableInstance variableInstance, String caseInstanceId) {
return fromVariableInstance(variableInstance)
.link(REL_SELF, CaseInstanceRestService.PATH, caseInstanceId, "variables");
}
private HalVariableValue link(HalRelation relation, String resourcePath, String resourceId, String variablesPath) {
if (resourcePath.startsWith("/")) {
// trim leading / because otherwise it will be encode as %2F (see CAM-3091)
resourcePath = resourcePath.substring(1);
}
this.linker.createLink(relation, resourcePath, resourceId, variablesPath, this.name);
return this;
}
public static HalVariableValue fromVariableInstance(VariableInstance variableInstance) {
HalVariableValue dto = new HalVariableValue();
VariableValueDto variableValueDto = VariableValueDto.fromTypedValue(variableInstance.getTypedValue());
|
dto.name = variableInstance.getName();
dto.value = variableValueDto.getValue();
dto.type = variableValueDto.getType();
dto.valueInfo = variableValueDto.getValueInfo();
return dto;
}
public String getName() {
return name;
}
public Object getValue() {
return value;
}
public String getType() {
return type;
}
public Map<String, Object> getValueInfo() {
return valueInfo;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\hal\HalVariableValue.java
| 1
|
请完成以下Java代码
|
private DefaultView getView(@NonNull final LookupDataSourceContext evalCtx)
{
final ViewId viewId = evalCtx.getViewId();
return DefaultView.cast(viewsRepository.getView(viewId));
}
@Nullable
private LookupValue convertRawFieldValueToLookupValue(final Object fieldValue)
{
if (fieldValue == null)
{
return null;
}
else if (fieldValue instanceof LookupValue)
{
return (LookupValue)fieldValue;
}
else if (fieldValue instanceof LocalDate)
{
final LocalDate date = (LocalDate)fieldValue;
return StringLookupValue.of(
Values.localDateToJson(date),
|
TranslatableStrings.date(date));
}
else if (fieldValue instanceof Boolean)
{
final boolean booleanValue = StringUtils.toBoolean(fieldValue);
return StringLookupValue.of(
DisplayType.toBooleanString(booleanValue),
msgBL.getTranslatableMsgText(booleanValue));
}
else if (fieldValue instanceof String)
{
final String stringValue = (String)fieldValue;
return StringLookupValue.of(stringValue, stringValue);
}
else
{
throw new AdempiereException("Value not supported: " + fieldValue + " (" + fieldValue.getClass() + ")")
.appendParametersToMessage()
.setParameter("fieldName", fieldName);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\provider\standard\FacetsFilterLookupDescriptor.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.