instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public String toString() {
return "ProcessDefinition(" + id + ")";
}
@Override
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
@Override
public String getDescription() {
return (String) getProperty("documentation");
} | /**
* @return all lane-sets defined on this process-instance. Returns an empty list if none are defined.
*/
public List<LaneSet> getLaneSets() {
if (laneSets == null) {
laneSets = new ArrayList<>();
}
return laneSets;
}
public void setParticipantProcess(ParticipantProcess participantProcess) {
this.participantProcess = participantProcess;
}
public ParticipantProcess getParticipantProcess() {
return participantProcess;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ProcessDefinitionImpl.java | 1 |
请完成以下Java代码 | public byte[] cfbEncrypt(SecretKey key, IvParameterSpec iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(data);
}
public byte[] cfbDecrypt(SecretKey key, IvParameterSpec iv, byte[] cipherText) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CFB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(cipherText);
}
public byte[] ofbEncrypt(SecretKey key, IvParameterSpec iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/OFB32/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv);
return cipher.doFinal(data);
}
public byte[] ofbDecrypt(SecretKey key, IvParameterSpec iv, byte[] cipherText) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/OFB32/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, key, iv);
return cipher.doFinal(cipherText);
}
public byte[][] ctrEncrypt(SecretKey key, IvParameterSpec iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, iv); | return new byte[][] { cipher.getIV(), cipher.doFinal(data) };
}
public byte[] ctrDecrypt(SecretKey key, byte[] iv, byte[] cipherText) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(iv));
return cipher.doFinal(cipherText);
}
public byte[][] gcmEncrypt(SecretKey key, byte[] iv, byte[] data) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, key, new GCMParameterSpec(128, iv));
byte[] ciphertext = cipher.doFinal(data);
return new byte[][] { iv, ciphertext };
}
public byte[] gcmDecrypt(SecretKey key, byte[] iv, byte[] ciphertext) throws GeneralSecurityException {
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, key, new GCMParameterSpec(128, iv));
byte[] plaintext = cipher.doFinal(ciphertext);
return plaintext;
}
} | repos\tutorials-master\core-java-modules\core-java-security-3\src\main\java\com\baeldung\crypto\CryptoDriver.java | 1 |
请完成以下Java代码 | public static EventLogEntryCollector getThreadLocal()
{
final EventLogEntryCollector eventLogCollector = threadLocalCollector.get();
Check.errorIf(eventLogCollector == null,
"Missing thread-local EventLogEntryCollector instance. It is expected that one was created using createThreadLocalForEvent().");
return eventLogCollector;
}
public void addEventLog(@NonNull final EventLogEntryRequest eventLogRequest)
{
final EventLogEntry eventLogEntry = EventLogEntry.builder()
.uuid(event.getUuid())
.clientId(eventLogRequest.getClientId())
.orgId(eventLogRequest.getOrgId())
.processed(eventLogRequest.isProcessed())
.error(eventLogRequest.isError())
.adIssueId(eventLogRequest.getAdIssueId())
.message(eventLogRequest.getMessage())
.eventHandlerClass(eventLogRequest.getEventHandlerClass())
.build();
eventLogEntries.add(eventLogEntry);
}
@Override
public void close()
{
// Restore previous entry collector
// or clear the current one
if (previousEntryCollector != null)
{
threadLocalCollector.set(previousEntryCollector);
}
else
{
threadLocalCollector.remove(); | }
// Avoid throwing exception because EventLogService is not available in unit tests
if (Adempiere.isUnitTestMode())
{
return;
}
try
{
final EventLogService eventStoreService = SpringContextHolder.instance.getBean(EventLogService.class);
eventStoreService.saveEventLogEntries(eventLogEntries);
}
catch (final Exception ex)
{
logger.warn("Failed saving {}. Ignored", eventLogEntries, ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\log\EventLogEntryCollector.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public BigDecimal getCurrentAtpAndUpdateQtyDetails(@NonNull final Candidate candidate, @NonNull final Candidate stockCandidate, @Nullable final Candidate previousStockCandidate)
{
final Candidate actualPreviousStockCandidate = CoalesceUtil.coalesceSuppliers(() -> previousStockCandidate,
() -> getPreviousStockCandidateOrNull(stockCandidate));
final BigDecimal previousQty = actualPreviousStockCandidate == null ? BigDecimal.ZERO : actualPreviousStockCandidate.getQuantity();
final CandidateId actualPreviousStockCandidateId = actualPreviousStockCandidate == null ? null : actualPreviousStockCandidate.getId();
final CandidateId currentCandidateId = candidate.getId();
final CandidateQtyDetailsPersistMultiRequest request = CandidateQtyDetailsPersistMultiRequest.builder()
.candidateId(currentCandidateId)
.stockCandidateId(stockCandidate.getId())
.details(ImmutableList.of(CandidateQtyDetailsPersistRequest.builder()
.detailCandidateId(actualPreviousStockCandidateId)
.qtyInStockUom(previousQty)
.build(),
CandidateQtyDetailsPersistRequest.builder()
.detailCandidateId(currentCandidateId)
.qtyInStockUom(candidate.getStockImpactPlannedQuantity())
.build()
))
.build();
candidateQtyDetailsRepository.save(request);
return candidate.getStockImpactPlannedQuantity().add(previousQty);
}
@Nullable
private Candidate getPreviousStockCandidateOrNull(final @NonNull Candidate stockCandidate)
{
final MaterialDescriptor materialDescriptor = stockCandidate.getMaterialDescriptor();
final MaterialDescriptorQuery materialDescriptorQuery = MaterialDescriptorQuery.builder()
.warehouseId(materialDescriptor.getWarehouseId()) | .productId(materialDescriptor.getProductId())
.storageAttributesKey(materialDescriptor.getStorageAttributesKey())
.customer(BPartnerClassifier.specificOrAny(materialDescriptor.getCustomerId()))
.customerIdOperator(MaterialDescriptorQuery.CustomerIdOperator.GIVEN_ID_ONLY)
.timeRangeEnd(DateAndSeqNo.atTimeNoSeqNo(stockCandidate.getMaterialDescriptor().getDate())
.withOperator(DateAndSeqNo.Operator.EXCLUSIVE))
.build();
final CandidatesQuery findPreviousStockQuery = CandidatesQuery.builder()
.materialDescriptorQuery(materialDescriptorQuery)
.type(CandidateType.STOCK)
.matchExactStorageAttributesKey(true)
.build();
return candidateRepositoryRetrieval.retrievePreviousMatchForCandidateIdOrNull(findPreviousStockQuery, stockCandidate.getId());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\dispo-commons\src\main\java\de\metas\material\dispo\commons\repository\CandidateRepositoryWriteService.java | 2 |
请完成以下Java代码 | public class X_C_MediatedCommissionSettings extends org.compiere.model.PO implements I_C_MediatedCommissionSettings, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1726230519L;
/** Standard Constructor */
public X_C_MediatedCommissionSettings (final Properties ctx, final int C_MediatedCommissionSettings_ID, @Nullable final String trxName)
{
super (ctx, C_MediatedCommissionSettings_ID, trxName);
}
/** Load Constructor */
public X_C_MediatedCommissionSettings (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_MediatedCommissionSettings_ID (final int C_MediatedCommissionSettings_ID)
{
if (C_MediatedCommissionSettings_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_MediatedCommissionSettings_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_MediatedCommissionSettings_ID, C_MediatedCommissionSettings_ID);
}
@Override
public int getC_MediatedCommissionSettings_ID()
{
return get_ValueAsInt(COLUMNNAME_C_MediatedCommissionSettings_ID);
}
@Override
public void setCommission_Product_ID (final int Commission_Product_ID)
{
if (Commission_Product_ID < 1)
set_Value (COLUMNNAME_Commission_Product_ID, null);
else
set_Value (COLUMNNAME_Commission_Product_ID, Commission_Product_ID);
}
@Override
public int getCommission_Product_ID() | {
return get_ValueAsInt(COLUMNNAME_Commission_Product_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPointsPrecision (final int PointsPrecision)
{
set_Value (COLUMNNAME_PointsPrecision, PointsPrecision);
}
@Override
public int getPointsPrecision()
{
return get_ValueAsInt(COLUMNNAME_PointsPrecision);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_MediatedCommissionSettings.java | 1 |
请完成以下Java代码 | public int getC_OLCandProcessor_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OLCandProcessor_ID);
}
@Override
public void setC_Order_Line_Alloc_ID (final int C_Order_Line_Alloc_ID)
{
if (C_Order_Line_Alloc_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Order_Line_Alloc_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Order_Line_Alloc_ID, C_Order_Line_Alloc_ID);
}
@Override
public int getC_Order_Line_Alloc_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Order_Line_Alloc_ID);
}
@Override
public org.compiere.model.I_C_OrderLine getC_OrderLine()
{
return get_ValueAsPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class);
}
@Override
public void setC_OrderLine(final org.compiere.model.I_C_OrderLine C_OrderLine)
{
set_ValueFromPO(COLUMNNAME_C_OrderLine_ID, org.compiere.model.I_C_OrderLine.class, C_OrderLine);
}
@Override
public void setC_OrderLine_ID (final int C_OrderLine_ID)
{
if (C_OrderLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_OrderLine_ID, C_OrderLine_ID);
}
@Override
public int getC_OrderLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_OrderLine_ID);
}
/**
* DocStatus AD_Reference_ID=131
* Reference name: _Document Status
*/
public static final int DOCSTATUS_AD_Reference_ID=131;
/** Drafted = DR */
public static final String DOCSTATUS_Drafted = "DR";
/** Completed = CO */
public static final String DOCSTATUS_Completed = "CO";
/** Approved = AP */
public static final String DOCSTATUS_Approved = "AP";
/** NotApproved = NA */
public static final String DOCSTATUS_NotApproved = "NA";
/** Voided = VO */
public static final String DOCSTATUS_Voided = "VO";
/** Invalid = IN */ | public static final String DOCSTATUS_Invalid = "IN";
/** Reversed = RE */
public static final String DOCSTATUS_Reversed = "RE";
/** Closed = CL */
public static final String DOCSTATUS_Closed = "CL";
/** Unknown = ?? */
public static final String DOCSTATUS_Unknown = "??";
/** InProgress = IP */
public static final String DOCSTATUS_InProgress = "IP";
/** WaitingPayment = WP */
public static final String DOCSTATUS_WaitingPayment = "WP";
/** WaitingConfirmation = WC */
public static final String DOCSTATUS_WaitingConfirmation = "WC";
@Override
public void setDocStatus (final @Nullable java.lang.String DocStatus)
{
throw new IllegalArgumentException ("DocStatus is virtual column"); }
@Override
public java.lang.String getDocStatus()
{
return get_ValueAsString(COLUMNNAME_DocStatus);
}
@Override
public void setQtyOrdered (final BigDecimal QtyOrdered)
{
set_Value (COLUMNNAME_QtyOrdered, QtyOrdered);
}
@Override
public BigDecimal getQtyOrdered()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_Order_Line_Alloc.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProductAccounts
{
@NonNull AcctSchemaId acctSchemaId;
@NonNull Optional<ActivityId> activityId;
@NonNull Account P_Revenue_Acct;
@NonNull Account P_Expense_Acct;
@NonNull Account P_Asset_Acct;
@NonNull Account P_COGS_Acct;
@NonNull Account P_PurchasePriceVariance_Acct;
@NonNull Account P_InvoicePriceVariance_Acct;
@NonNull Account P_TradeDiscountRec_Acct;
@NonNull Account P_TradeDiscountGrant_Acct;
@NonNull Account P_CostAdjustment_Acct;
@NonNull Account P_InventoryClearing_Acct;
@NonNull Account P_WIP_Acct;
@NonNull Account P_MethodChangeVariance_Acct;
@NonNull Account P_UsageVariance_Acct;
@NonNull Account P_RateVariance_Acct;
@NonNull Account P_MixVariance_Acct;
@NonNull Account P_FloorStock_Acct;
@NonNull Account P_CostOfProduction_Acct;
@NonNull Account P_Labor_Acct;
@NonNull Account P_Burden_Acct;
@NonNull Account P_OutsideProcessing_Acct;
@NonNull Account P_Overhead_Acct;
@NonNull Account P_Scrap_Acct;
@NonNull
public Account getAccount(@NonNull final ProductAcctType acctType)
{
final Account account;
switch (acctType)
{
case P_Revenue_Acct:
account = P_Revenue_Acct;
break;
case P_Expense_Acct:
account = P_Expense_Acct;
break;
case P_Asset_Acct:
account = P_Asset_Acct;
break;
case P_COGS_Acct:
account = P_COGS_Acct;
break;
case P_PurchasePriceVariance_Acct:
account = P_PurchasePriceVariance_Acct;
break;
case P_InvoicePriceVariance_Acct:
account = P_InvoicePriceVariance_Acct;
break;
case P_TradeDiscountRec_Acct:
account = P_TradeDiscountRec_Acct;
break;
case P_TradeDiscountGrant_Acct:
account = P_TradeDiscountGrant_Acct;
break;
case P_CostAdjustment_Acct:
account = P_CostAdjustment_Acct;
break;
case P_InventoryClearing_Acct:
account = P_InventoryClearing_Acct;
break; | case P_WIP_Acct:
account = P_WIP_Acct;
break;
case P_MethodChangeVariance_Acct:
account = P_MethodChangeVariance_Acct;
break;
case P_UsageVariance_Acct:
account = P_UsageVariance_Acct;
break;
case P_RateVariance_Acct:
account = P_RateVariance_Acct;
break;
case P_MixVariance_Acct:
account = P_MixVariance_Acct;
break;
case P_FloorStock_Acct:
account = P_FloorStock_Acct;
break;
case P_CostOfProduction_Acct:
account = P_CostOfProduction_Acct;
break;
case P_Labor_Acct:
account = P_Labor_Acct;
break;
case P_Burden_Acct:
account = P_Burden_Acct;
break;
case P_OutsideProcessing_Acct:
account = P_OutsideProcessing_Acct;
break;
case P_Overhead_Acct:
account = P_Overhead_Acct;
break;
case P_Scrap_Acct:
account = P_Scrap_Acct;
break;
default:
throw new IllegalArgumentException();
}
return account;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\accounts\ProductAccounts.java | 2 |
请完成以下Java代码 | public static int bytesToInt(byte[] bytes, int start)
{
int num = bytes[start] & 0xFF;
num |= ((bytes[start + 1] << 8) & 0xFF00);
num |= ((bytes[start + 2] << 16) & 0xFF0000);
num |= ((bytes[start + 3] << 24) & 0xFF000000);
return num;
}
/**
* 字节数组和整型的转换,高位在前,适用于读取writeInt的数据
*
* @param bytes 字节数组
* @return 整型
*/
public static int bytesHighFirstToInt(byte[] bytes, int start)
{
int num = bytes[start + 3] & 0xFF;
num |= ((bytes[start + 2] << 8) & 0xFF00);
num |= ((bytes[start + 1] << 16) & 0xFF0000);
num |= ((bytes[start] << 24) & 0xFF000000);
return num;
}
/**
* 字节数组转char,高位在前,适用于读取writeChar的数据
*
* @param bytes
* @param start
* @return
*/
public static char bytesHighFirstToChar(byte[] bytes, int start)
{
char c = (char) (((bytes[start] & 0xFF) << 8) | (bytes[start + 1] & 0xFF));
return c;
}
/**
* 读取float,高位在前
*
* @param bytes
* @param start
* @return
*/
public static float bytesHighFirstToFloat(byte[] bytes, int start)
{
int l = bytesHighFirstToInt(bytes, start);
return Float.intBitsToFloat(l);
} | /**
* 无符号整型输出
* @param out
* @param uint
* @throws IOException
*/
public static void writeUnsignedInt(DataOutputStream out, int uint) throws IOException
{
out.writeByte((byte) ((uint >>> 8) & 0xFF));
out.writeByte((byte) ((uint >>> 0) & 0xFF));
}
public static int convertTwoCharToInt(char high, char low)
{
int result = high << 16;
result |= low;
return result;
}
public static char[] convertIntToTwoChar(int n)
{
char[] result = new char[2];
result[0] = (char) (n >>> 16);
result[1] = (char) (0x0000FFFF & n);
return result;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\utility\ByteUtil.java | 1 |
请完成以下Java代码 | public class BuilderMethods {
private final int intValue;
private final String strSample;
public BuilderMethods(final int newId, final String newName) {
this.intValue = newId;
this.strSample = newName;
}
public int getId() {
return this.intValue;
}
public String getName() {
return this.strSample;
}
@Override
public int hashCode() {
return new HashCodeBuilder().append(this.intValue).append(this.strSample).toHashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof BuilderMethods == false) {
return false;
}
if (this == obj) {
return true;
}
final BuilderMethods otherObject = (BuilderMethods) obj;
return new EqualsBuilder().append(this.intValue, otherObject.intValue).append(this.strSample, otherObject.strSample).isEquals();
}
@Override
public String toString() {
return new ToStringBuilder(this).append("INTVALUE", this.intValue).append("STRINGVALUE", this.strSample).toString();
}
public static void main(final String[] arguments) {
final BuilderMethods simple1 = new BuilderMethods(1, "The First One");
System.out.println(simple1.getName());
System.out.println(simple1.hashCode()); | System.out.println(simple1.toString());
SampleLazyInitializer sampleLazyInitializer = new SampleLazyInitializer();
try {
sampleLazyInitializer.get();
} catch (ConcurrentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
SampleBackgroundInitializer sampleBackgroundInitializer = new SampleBackgroundInitializer();
sampleBackgroundInitializer.start();
// Proceed with other tasks instead of waiting for the SampleBackgroundInitializer task to finish.
try {
Object result = sampleBackgroundInitializer.get();
} catch (ConcurrentException e) {
e.printStackTrace();
}
}
}
class SampleBackgroundInitializer extends BackgroundInitializer<String> {
@Override
protected String initialize() throws Exception {
return null;
}
// Any complex task that takes some time
} | repos\tutorials-master\libraries-apache-commons\src\main\java\com\baeldung\commons\lang3\BuilderMethods.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static final class DataSourceBeanCondition {
}
@ConditionalOnBean(JdbcConnectionDetails.class)
private static final class JdbcConnectionDetailsCondition {
}
@ConditionalOnProperty("spring.liquibase.url")
private static final class LiquibaseUrlCondition {
}
}
static class LiquibaseAutoConfigurationRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("db/changelog/**");
}
}
/**
* Adapts {@link LiquibaseProperties} to {@link LiquibaseConnectionDetails}.
*/
static final class PropertiesLiquibaseConnectionDetails implements LiquibaseConnectionDetails {
private final LiquibaseProperties properties;
PropertiesLiquibaseConnectionDetails(LiquibaseProperties properties) {
this.properties = properties;
}
@Override | public @Nullable String getUsername() {
return this.properties.getUser();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
@Override
public @Nullable String getJdbcUrl() {
return this.properties.getUrl();
}
@Override
public @Nullable String getDriverClassName() {
String driverClassName = this.properties.getDriverClassName();
return (driverClassName != null) ? driverClassName : LiquibaseConnectionDetails.super.getDriverClassName();
}
}
@FunctionalInterface
interface SpringLiquibaseCustomizer {
/**
* Customize the given {@link SpringLiquibase} instance.
* @param springLiquibase the instance to configure
*/
void customize(SpringLiquibase springLiquibase);
}
} | repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseAutoConfiguration.java | 2 |
请完成以下Java代码 | public class CacheGetException extends AdempiereException
{
/**
*
*/
private static final long serialVersionUID = -2145287441754772885L;
private Object targetObject;
private Object[] methodArgs;
private int parameterIndex;
private Object parameter;
private boolean parameterSet = false;
private Class<? extends Annotation> annotationType = null;
public CacheGetException(final String message)
{
// NOTE: don't try to translate the build message because it's not translatable
super(TranslatableStrings.constant(message));
}
@Override
protected ITranslatableString buildMessage()
{
final TranslatableStringBuilder message = TranslatableStrings.builder();
message.append(super.buildMessage());
if (targetObject != null)
{
message.append("\n Target object: ").append(targetObject.toString());
}
if (methodArgs != null)
{
message.append("\n Method Arguments: ").append(Arrays.asList(methodArgs).toString());
}
if (parameterSet)
{
message.append("\n Invalid parameter at index ").append(parameterIndex).append(": ").append(String.valueOf(parameter));
if (parameter != null)
{
message.append(" (").append(parameter.getClass().toString()).append(")");
}
}
if (annotationType != null)
{
message.append("\n Annotation: ").append(annotationType.toString()); | }
return message.build();
}
public CacheGetException setTargetObject(final Object targetObject)
{
this.targetObject = targetObject;
resetMessageBuilt();
return this;
}
public CacheGetException setMethodArguments(final Object[] methodArgs)
{
this.methodArgs = methodArgs;
resetMessageBuilt();
return this;
}
public CacheGetException setInvalidParameter(final int parameterIndex, final Object parameter)
{
this.parameterIndex = parameterIndex;
this.parameter = parameter;
this.parameterSet = true;
resetMessageBuilt();
return this;
}
public CacheGetException setAnnotation(final Class<? extends Annotation> annotation)
{
this.annotationType = annotation;
return this;
}
public CacheGetException addSuppressIfNotNull(final Throwable exception)
{
if(exception != null)
{
addSuppressed(exception);
}
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\interceptor\CacheGetException.java | 1 |
请完成以下Java代码 | public ListQueryParameterObject configureQuery(Object parameters) {
ListQueryParameterObject queryObject = new ListQueryParameterObject();
queryObject.setParameter(parameters);
return configureQuery(queryObject);
}
public boolean isAuthenticatedTenant(String tenantId) {
if (tenantId != null && isTenantCheckEnabled()) {
Authentication currentAuthentication = getCurrentAuthentication();
List<String> authenticatedTenantIds = currentAuthentication.getTenantIds();
if (authenticatedTenantIds != null) {
return authenticatedTenantIds.contains(tenantId); | } else {
return false;
}
} else {
return true;
}
}
public boolean isTenantCheckEnabled() {
return Context.getProcessEngineConfiguration().isTenantCheckEnabled()
&& Context.getCommandContext().isTenantCheckEnabled()
&& getCurrentAuthentication() != null
&& !getAuthorizationManager().isCamundaAdmin(getCurrentAuthentication());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TenantManager.java | 1 |
请完成以下Java代码 | public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Interface.
@param IsInterface Interface */
@Override
public void setIsInterface (boolean IsInterface)
{
set_Value (COLUMNNAME_IsInterface, Boolean.valueOf(IsInterface));
}
/** Get Interface.
@return Interface */
@Override
public boolean isInterface ()
{
Object oo = get_Value(COLUMNNAME_IsInterface);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\javaclasses\model\X_AD_JavaClass.java | 1 |
请完成以下Java代码 | private void setName(final I_C_BP_Relation rel)
{
final StringBuffer name = new StringBuffer();
final String nameFrom = bPartnerBL.getBPartnerName(BPartnerId.ofRepoId(rel.getC_BPartner_ID()));
name.append(nameFrom);
if (rel.getC_BPartner_Location_ID() > 0)
{
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(rel.getC_BPartner_ID(), rel.getC_BPartner_Location_ID());
final I_C_BPartner_Location bPartnerLocation = bPartnersRepo.getBPartnerLocationById(bPartnerLocationId);
final String locFrom = bPartnerLocation.getName();
name.append("(").append(locFrom).append(")");
}
name.append("->");
final String nameTo = bPartnersRepo.getBPartnerNameById(BPartnerId.ofRepoId(rel.getC_BPartnerRelation_ID()));
name.append(nameTo);
if (rel.getC_BPartnerRelation_Location_ID() > 0)
{
final BPartnerLocationId bPartnerLocationId = BPartnerLocationId.ofRepoId(rel.getC_BPartnerRelation_ID(), rel.getC_BPartnerRelation_Location_ID());
final String locTo = bPartnersRepo.getBPartnerLocationById(bPartnerLocationId).getName();
name.append("(").append(locTo).append(")");
}
rel.setName(name.toString());
makeUniqueName(rel);
} | private void makeUniqueName(final I_C_BP_Relation rel)
{
int cnt = 1;
while (cnt < 100)
{
final StringBuffer nameCurrent = new StringBuffer(rel.getName());
if (cnt > 1)
{
nameCurrent.append(" (").append(cnt).append(")");
}
final String whereClause = I_C_BP_Relation.COLUMNNAME_Name + "=?"
+ " AND " + I_C_BP_Relation.COLUMNNAME_C_BP_Relation_ID + "<>?";
final boolean match = new Query(getCtx(), I_C_BP_Relation.Table_Name, whereClause, get_TrxName())
.setParameters(nameCurrent.toString(), rel.getC_BP_Relation_ID())
.setClient_ID()
.anyMatch();
if (!match)
{
rel.setName(nameCurrent.toString());
return;
}
cnt++;
}
throw new AdempiereException("Cannot make name " + rel.getName() + " unique");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\process\CreateBPRelationFromDocument.java | 1 |
请完成以下Java代码 | private static DataEntryListValueId convertValueToListValueId(
@Nullable final Object value,
@NonNull final DataEntryField field)
{
if (value == null)
{
return null;
}
//
// Match by ID
final Integer valueInt = NumberUtils.asIntegerOrNull(value);
if (valueInt != null)
{
final DataEntryListValueId id = DataEntryListValueId.ofRepoIdOrNull(valueInt);
if (id != null)
{
final DataEntryListValue matchedListValue = field.getFirstListValueMatching(listValue -> id.equals(listValue.getId()))
.orElse(null);
if (matchedListValue != null)
{
return matchedListValue.getId();
}
}
}
//
// Match by Name
{
final String captionStr = value.toString().trim();
if (captionStr.isEmpty())
{
return null; | }
final DataEntryListValue matchedListValue = field.getFirstListValueMatching(listValue -> listValue.isNameMatching(captionStr))
.orElse(null);
if (matchedListValue != null)
{
return matchedListValue.getId();
}
}
//
// Fail
throw new AdempiereException("No list value found for `" + value + "`");
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\data\DataEntryRecordField.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static void chainingTaskExample() {
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<Integer> firstTask = executor.submit(() -> {return 42;});
Future<String> secondTask = executor.submit(() -> {
try {
Integer result = firstTask.get();
return "Result based on Task 1: " + result;
} catch (InterruptedException | ExecutionException e) {
// Handle exception
System.err.println("Error occured: " + e.getMessage());
}
return null;
});
executor.shutdown();
try {
// Wait for the second task to complete and retrieve the result
String result = secondTask.get();
System.out.println(result); // Output: Result based on Task 1: 42
} catch (InterruptedException | ExecutionException e) {
// Handle exception
System.err.println("Error occured: " + e.getMessage());
}
}
public static void exceptionHandlingExample() {
ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(() -> {
// Simulate a task that might throw an exception
if (true) {
throw new RuntimeException("Something went wrong!");
}
return "Success";
});
try {
// This might block the main thread if the task throws an exception
String result = future.get();
System.out.println("Result: " + result);
} catch (InterruptedException | ExecutionException e) {
// Handle exceptions thrown by the task or during retrieval
System.err.println("Error occured: " + e.getMessage());
} finally {
executor.shutdown();
}
}
public static void timeoutExample() { | ExecutorService executor = Executors.newFixedThreadPool(2);
Future<String> future = executor.submit(() -> {
try {
System.out.println("Start");
Thread.sleep(5000);
System.out.println("End");
} catch (InterruptedException e) {
System.err.println("Error occured: " + e.getMessage());
}
return "Task completed";
});
try {
String result = future.get(2, TimeUnit.SECONDS);
System.out.println("Result: " + result);
} catch (TimeoutException e) {
System.err.println("Task execution timed out!");
future.cancel(true);
} catch (Exception e) {
System.err.println("Error occured: " + e.getMessage());
} finally {
executor.shutdown();
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
timeoutExample();
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-5\src\main\java\com\baeldung\executorservicevscompletablefuture\ExecutorServiceDemo.java | 2 |
请完成以下Java代码 | private MInOutLine createLine(MInvoice invoice, MInvoiceLine invoiceLine)
{
final IInvoiceBL invoiceBL = Services.get(IInvoiceBL.class);
final MatchInvoiceService matchInvoiceService = MatchInvoiceService.get();
final StockQtyAndUOMQty qtyMatched = matchInvoiceService.getMaterialQtyMatched(invoiceLine);
final StockQtyAndUOMQty qtyInvoiced = StockQtyAndUOMQtys.create(
invoiceLine.getQtyInvoiced(), ProductId.ofRepoId(invoiceLine.getM_Product_ID()),
invoiceLine.getQtyEntered(), UomId.ofRepoId(invoiceLine.getC_UOM_ID()));
final StockQtyAndUOMQty qtyNotMatched = StockQtyAndUOMQtys.subtract(qtyInvoiced, qtyMatched);
// If is fully matched don't create anything
if (qtyNotMatched.signum() == 0)
{
return null;
}
MInOut inout = getCreateHeader(invoice);
MInOutLine sLine = new MInOutLine(inout);
sLine.setInvoiceLine(invoiceLine, 0, // Locator | invoice.isSOTrx() ? qtyNotMatched.getStockQty().toBigDecimal() : ZERO);
sLine.setQtyEntered(qtyNotMatched.getUOMQtyNotNull().toBigDecimal());
sLine.setMovementQty(qtyNotMatched.getStockQty().toBigDecimal());
if (invoiceBL.isCreditMemo(invoice))
{
sLine.setQtyEntered(sLine.getQtyEntered().negate());
sLine.setMovementQty(sLine.getMovementQty().negate());
}
sLine.saveEx();
//
invoiceLine.setM_InOutLine_ID(sLine.getM_InOutLine_ID());
invoiceLine.saveEx();
//
return sLine;
}
} // InvoiceCreateInOut | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\InvoiceCreateInOut.java | 1 |
请完成以下Java代码 | public List<String> getValuesInObject(JSONObject jsonObject, String key) {
List<String> accumulatedValues = new ArrayList<>();
for (String currentKey : jsonObject.keySet()) {
Object value = jsonObject.get(currentKey);
if (currentKey.equals(key)) {
accumulatedValues.add(value.toString());
}
if (value instanceof JSONObject) {
accumulatedValues.addAll(getValuesInObject((JSONObject)value, key));
} else if (value instanceof JSONArray) {
accumulatedValues.addAll(getValuesInArray((JSONArray)value, key));
}
}
return accumulatedValues;
}
/**
* Get values associated with the provided key in the given JSONArray instance
*
* @param jsonArray JSONArray instance in which to search the key
* @param key Key we're interested in
*
* @return List of values associated with the given key, in the order of appearance.
* If the key is absent, empty list is returned.
*/
public List<String> getValuesInArray(JSONArray jsonArray, String key) {
List<String> accumulatedValues = new ArrayList<>();
for (Object obj : jsonArray) {
if (obj instanceof JSONArray) {
accumulatedValues.addAll(getValuesInArray((JSONArray)obj, key));
} else if (obj instanceof JSONObject) {
accumulatedValues.addAll(getValuesInObject((JSONObject)obj, key));
}
}
return accumulatedValues;
}
/**
* Among all the values associated with the given key, get the N-th value
*
* @param jsonObject JSONObject instance in which to search the key
* @param key Key we're interested in
* @param N Index of the value to get
* | * @return N-th value associated with the key, or null if the key is absent or
* the number of values associated with the key is less than N
*/
public String getNthValue(JSONObject jsonObject, String key, int N) {
List<String> values = getValuesInObject(jsonObject, key);
return (values.size() >= N) ? values.get(N - 1) : null;
}
/**
* Count the number of values associated with the given key
*
* @param jsonObject JSONObject instance in which to count the key
* @param key Key we're interested in
*
* @return The number of values associated with the given key
*/
public int getCount(JSONObject jsonObject, String key) {
List<String> values = getValuesInObject(jsonObject, key);
return values.size();
}
} | repos\tutorials-master\json-modules\json\src\main\java\com\baeldung\jsonvaluegetter\JSONObjectValueGetter.java | 1 |
请完成以下Java代码 | private static MediaType initContentType(RestClient webClient) {
HttpHeaders headers = new HttpHeaders();
webClient.mutate().defaultHeaders(headers::putAll);
MediaType contentType = headers.getContentType();
return (contentType != null) ? contentType : MediaType.APPLICATION_JSON;
}
@Override
@SuppressWarnings("NullAway")
public GraphQlResponse execute(GraphQlRequest request) {
Map<String, Object> body = this.restClient.post()
.contentType(this.contentType)
.accept(MediaType.APPLICATION_JSON, MediaTypes.APPLICATION_GRAPHQL_RESPONSE)
.body(request.toMap())
.exchange((httpRequest, httpResponse) -> {
if (httpResponse.getStatusCode().equals(HttpStatus.OK)) {
return httpResponse.bodyTo(MAP_TYPE);
}
else if (httpResponse.getStatusCode().is4xxClientError() && isGraphQlResponse(httpResponse)) {
return httpResponse.bodyTo(MAP_TYPE);
}
else if (httpResponse.getStatusCode().is4xxClientError()) {
throw HttpClientErrorException.create(httpResponse.getStatusText(), httpResponse.getStatusCode(),
httpResponse.getStatusText(), httpResponse.getHeaders(),
getBody(httpResponse), getCharset(httpResponse));
}
else {
throw HttpServerErrorException.create(httpResponse.getStatusText(), httpResponse.getStatusCode(),
httpResponse.getStatusText(), httpResponse.getHeaders(),
getBody(httpResponse), getCharset(httpResponse));
} | });
return new ResponseMapGraphQlResponse((body != null) ? body : Collections.emptyMap());
}
private static boolean isGraphQlResponse(ClientHttpResponse clientResponse) {
return MediaTypes.APPLICATION_GRAPHQL_RESPONSE
.isCompatibleWith(clientResponse.getHeaders().getContentType());
}
private static byte[] getBody(HttpInputMessage message) {
try {
return FileCopyUtils.copyToByteArray(message.getBody());
}
catch (IOException ignore) {
}
return new byte[0];
}
private static @Nullable Charset getCharset(HttpMessage response) {
HttpHeaders headers = response.getHeaders();
MediaType contentType = headers.getContentType();
return (contentType != null) ? contentType.getCharset() : null;
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\HttpSyncGraphQlTransport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserInfo implements Serializable {
@Id
@GeneratedValue
private Integer uid;
@Column(unique =true)
private String username;
private String name;
private String password;
private String salt;
private byte state;
@ManyToMany(fetch= FetchType.EAGER)
@JoinTable(name = "SysUserRole", joinColumns = { @JoinColumn(name = "uid") }, inverseJoinColumns ={@JoinColumn(name = "roleId") })
private List<SysRole> roleList;
public Integer getUid() {
return uid;
}
public void setUid(Integer uid) {
this.uid = uid;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) { | this.password = password;
}
public String getSalt() {
return salt;
}
public void setSalt(String salt) {
this.salt = salt;
}
public byte getState() {
return state;
}
public void setState(byte state) {
this.state = state;
}
public List<SysRole> getRoleList() {
return roleList;
}
public void setRoleList(List<SysRole> roleList) {
this.roleList = roleList;
}
/**
* Salt
* @return
*/
public String getCredentialsSalt(){
return this.username+this.salt;
}
} | repos\springboot-demo-master\shiro\src\main\java\com\et\shiro\entity\UserInfo.java | 2 |
请完成以下Java代码 | 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 void setNetDays (int NetDays)
{
set_Value (COLUMNNAME_NetDays, Integer.valueOf(NetDays));
}
/** Get Net Days.
@return Net Days in which payment is due
*/
public int getNetDays ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NetDays);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to. | @return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Contract.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void afterConnectionEstablished(WebSocketSession session) throws Exception {
LOG.info("WS session: {}", session.getId());
this.sessions.put(session.getId(), session);
}
@Override
public void handleMessage(WebSocketSession session, WebSocketMessage<?> message) throws Exception {
TextMessage textMessage = (TextMessage)message;
String payload = textMessage.getPayload();
LOG.info("WS message: {} message={}", session.getId(), payload);
session.sendMessage(new TextMessage("Echo: " + payload));
}
@Override
public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception {
LOG.info("WS transport error: {}", session.getId());
this.sessions.remove(session.getId(), session);
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception {
LOG.info("WS connection closed: {}", session.getId()); | this.sessions.remove(session.getId(), session);
}
@Override
public boolean supportsPartialMessages() {
return false;
}
@PreDestroy
public void close() throws Exception {
LOG.info("WS shutdown");
this.executorService.shutdownNow();
}
} | repos\spring-examples-java-17\spring-websockets\src\main\java\itx\examples\springboot\websockets\config\WSHandler.java | 2 |
请完成以下Java代码 | public class SysPosition {
/**
* id
*/
@TableId(type = IdType.ASSIGN_ID)
@Schema(description = "id")
private java.lang.String id;
/**
* 职务编码
*/
@Excel(name = "职务编码", width = 15)
@Schema(description = "职务编码")
private java.lang.String code;
/**
* 职务级别名称
*/
@Excel(name = "职务级别名称", width = 15)
@Schema(description = "职务级别名称")
private java.lang.String name;
/**
* 职级
*/
//@Excel(name = "职级", width = 15,dicCode ="position_rank")
@Schema(description = "职务等级")
private java.lang.Integer postLevel;
/**
* 公司id
*/
@Schema(description = "公司id")
private java.lang.String companyId;
/**
* 创建人
*/
@Schema(description = "创建人")
private java.lang.String createBy;
/**
* 创建时间
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "创建时间")
private java.util.Date createTime;
/**
* 修改人 | */
@Schema(description = "修改人")
private java.lang.String updateBy;
/**
* 修改时间
*/
@JsonFormat(timezone = "GMT+8", pattern = "yyyy-MM-dd HH:mm:ss")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@Schema(description = "修改时间")
private java.util.Date updateTime;
/**
* 组织机构编码
*/
@Schema(description = "组织机构编码")
private java.lang.String sysOrgCode;
/**租户ID*/
@Schema(description = "租户ID")
private java.lang.Integer tenantId;
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\entity\SysPosition.java | 1 |
请完成以下Java代码 | public void init(FilterConfig filterConfig) {
ClassPathResource classPathResource = new ClassPathResource("web/notTrustHost.html");
try {
classPathResource.getInputStream();
byte[] bytes = FileCopyUtils.copyToByteArray(classPathResource.getInputStream());
this.notTrustHostHtmlView = new String(bytes, StandardCharsets.UTF_8);
} catch (IOException e) {
logger.error("Failed to load notTrustHost.html file", e);
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String url = WebUtils.getSourceUrl(request);
String host = WebUtils.getHost(url);
assert host != null;
if (isNotTrustHost(host)) {
String html = this.notTrustHostHtmlView.replace("${current_host}", host);
response.getWriter().write(html);
response.getWriter().close();
} else {
chain.doFilter(request, response);
}
}
public boolean isNotTrustHost(String host) {
// 如果配置了黑名单,优先检查黑名单 | if (CollectionUtils.isNotEmpty(ConfigConstants.getNotTrustHostSet())) {
return ConfigConstants.getNotTrustHostSet().contains(host);
}
// 如果配置了白名单,检查是否在白名单中
if (CollectionUtils.isNotEmpty(ConfigConstants.getTrustHostSet())) {
// 支持通配符 * 表示允许所有主机
if (ConfigConstants.getTrustHostSet().contains("*")) {
logger.debug("允许所有主机访问(通配符模式): {}", host);
return false;
}
return !ConfigConstants.getTrustHostSet().contains(host);
}
// 安全加固:默认拒绝所有未配置的主机(防止SSRF攻击)
// 如果需要允许所有主机,请在配置文件中明确设置 trust.host = *
logger.warn("未配置信任主机列表,拒绝访问主机: {},请在配置文件中设置 trust.host 或 KK_TRUST_HOST 环境变量", host);
return true;
}
@Override
public void destroy() {
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\web\filter\TrustHostFilter.java | 1 |
请完成以下Java代码 | private static void updateActionButtonUI_PreferredSize(final VEditorActionButton actionButton, final JComponent textComponent)
{
final Dimension textCompSize = textComponent.getPreferredSize();
final int textCompHeight = textCompSize.height;
final Dimension buttonSize = new Dimension(textCompHeight, textCompHeight);
actionButton.setPreferredSize(buttonSize);
}
private static void updateActionButtonUI_Background(final VEditorActionButton actionButton, final JComponent textComponent)
{
final Color textCompBackground = textComponent.getBackground();
actionButton.setBackground(textCompBackground);
}
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
if (isDisposed())
{
return;
}
final JComponent textComponent = (JComponent)evt.getSource();
if (textComponent == null) | {
return; // shall not happen
}
final VEditorActionButton actionButton = getActionButton();
if (actionButton == null)
{
dispose();
return;
}
final String propertyName = evt.getPropertyName();
if (PROPERTY_PreferredSize.equals(propertyName))
{
updateActionButtonUI_PreferredSize(actionButton, textComponent);
}
else if (PROPERTY_Background.equals(propertyName))
{
updateActionButtonUI_Background(actionButton, textComponent);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VEditorActionButton.java | 1 |
请完成以下Java代码 | public double getValue() {
return value;
}
/**
* @param value the value to set
*/
public void setValue(double value) {
this.value = value;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((symbol == null) ? 0 : symbol.hashCode());
result = prime * result + ((ts == null) ? 0 : ts.hashCode());
long temp;
temp = Double.doubleToLongBits(value);
result = prime * result + (int) (temp ^ (temp >>> 32));
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Quote other = (Quote) obj;
if (symbol == null) {
if (other.symbol != null)
return false; | } else if (!symbol.equals(other.symbol))
return false;
if (ts == null) {
if (other.ts != null)
return false;
} else if (!ts.equals(other.ts))
return false;
if (Double.doubleToLongBits(value) != Double.doubleToLongBits(other.value))
return false;
return true;
}
@Override
public String toString() {
return "Quote [ts=" + ts + ", symbol=" + symbol + ", value=" + value + "]";
}
} | repos\tutorials-master\web-modules\ratpack\src\main\java\com\baeldung\model\Quote.java | 1 |
请完成以下Java代码 | private void add(Document document) throws IOException
{
out.writeInt(document.category);
Set<Map.Entry<Integer, int[]>> entrySet = document.tfMap.entrySet();
out.writeInt(entrySet.size());
for (Map.Entry<Integer, int[]> entry : entrySet)
{
out.writeInt(entry.getKey());
out.writeInt(entry.getValue()[0]);
}
++size;
}
@Override
public int size()
{
return size;
}
@Override
public void clear()
{
size = 0;
}
@Override
public IDataSet shrink(int[] idMap)
{
try
{
clear();
Iterator<Document> iterator = iterator();
initCache();
while (iterator.hasNext())
{
Document document = iterator.next();
FrequencyMap<Integer> tfMap = new FrequencyMap<Integer>();
for (Map.Entry<Integer, int[]> entry : document.tfMap.entrySet())
{
Integer feature = entry.getKey();
if (idMap[feature] == -1) continue;
tfMap.put(idMap[feature], entry.getValue());
}
// 检查是否是空白文档
if (tfMap.size() == 0) continue;
document.tfMap = tfMap;
add(document);
}
}
catch (IOException e)
{
throw new RuntimeException(e);
}
return this;
}
@Override
public Iterator<Document> iterator()
{
try
{
out.close();
final DataInputStream in = new DataInputStream(new FileInputStream(cache));
return new Iterator<Document>()
{
@Override
public void remove()
{
throw new RuntimeException("不支持的操作");
}
@Override
public boolean hasNext() | {
try
{
boolean next = in.available() > 0;
if (!next) in.close();
return next;
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
@Override
public Document next()
{
try
{
return new Document(in);
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
};
}
catch (IOException e)
{
throw new RuntimeException(e);
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\corpus\FileDataSet.java | 1 |
请完成以下Java代码 | private void deleteAllAttachmentMultiRefs(@NonNull final AttachmentEntryId attachmententryId)
{
Services.get(IQueryBL.class)
.createQueryBuilder(I_AD_Attachment_MultiRef.class)
.addEqualsFilter(I_AD_Attachment_MultiRef.COLUMN_AD_AttachmentEntry_ID, attachmententryId)
.create()
.delete();
}
public void delete(@NonNull final AttachmentEntry attachmentEntry)
{
deleteAllAttachmentMultiRefs(attachmentEntry.getId());
Services.get(IQueryBL.class).createQueryBuilder(I_AD_AttachmentEntry.class)
.addEqualsFilter(I_AD_AttachmentEntry.COLUMN_AD_AttachmentEntry_ID, attachmentEntry.getId())
.create()
.delete();
}
private static byte[] getBinaryDataFromLocalFileURL(@NonNull final URI uri){
try
{
final URL url = uri.toURL();
final Path filePath = FileUtil.getFilePath(url);
return Files.readAllBytes(filePath);
} | catch (final IOException e)
{
throw new AdempiereException("Could not get binary data from url " + uri, e);
}
}
private static byte[] getBinaryData(@NonNull final I_AD_AttachmentEntry record)
{
final AttachmentEntryType type = AttachmentEntryType.ofCode(record.getType());
if (AttachmentEntryType.LocalFileURL.equals(type))
{
Check.assumeNotNull(record.getURL(), "AD_AttachmentEntry.URL cannot be null for type = {}, AD_AttachmentEntry_ID = {}",
AttachmentEntryType.LocalFileURL.getCode(), record.getAD_AttachmentEntry_ID());
return getBinaryDataFromLocalFileURL(URI.create(record.getURL()));
}
return record.getBinaryData();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\attachments\AttachmentEntryRepository.java | 1 |
请完成以下Java代码 | default CookieSameSiteSupplier whenHasName(Supplier<String> nameSupplier) {
Assert.notNull(nameSupplier, "'nameSupplier' must not be null");
return when((cookie) -> ObjectUtils.nullSafeEquals(cookie.getName(), nameSupplier.get()));
}
/**
* Limit this supplier so that it's only called if the Cookie name matches the given
* regex.
* @param regex the regex pattern that must match
* @return a new {@link CookieSameSiteSupplier} that only calls this supplier when the
* name matches the regex
*/
default CookieSameSiteSupplier whenHasNameMatching(String regex) {
Assert.hasText(regex, "'regex' must not be empty");
return whenHasNameMatching(Pattern.compile(regex));
}
/**
* Limit this supplier so that it's only called if the Cookie name matches the given
* {@link Pattern}.
* @param pattern the regex pattern that must match
* @return a new {@link CookieSameSiteSupplier} that only calls this supplier when the
* name matches the pattern
*/
default CookieSameSiteSupplier whenHasNameMatching(Pattern pattern) {
Assert.notNull(pattern, "'pattern' must not be null");
return when((cookie) -> pattern.matcher(cookie.getName()).matches());
}
/**
* Limit this supplier so that it's only called if the predicate accepts the Cookie.
* @param predicate the predicate used to match the cookie
* @return a new {@link CookieSameSiteSupplier} that only calls this supplier when the
* cookie matches the predicate
*/
default CookieSameSiteSupplier when(Predicate<Cookie> predicate) {
Assert.notNull(predicate, "'predicate' must not be null");
return (cookie) -> predicate.test(cookie) ? getSameSite(cookie) : null;
}
/**
* Return a new {@link CookieSameSiteSupplier} that always returns
* {@link SameSite#NONE}.
* @return the supplier instance
*/
static CookieSameSiteSupplier ofNone() {
return of(SameSite.NONE);
}
/**
* Return a new {@link CookieSameSiteSupplier} that always returns | * {@link SameSite#LAX}.
* @return the supplier instance
*/
static CookieSameSiteSupplier ofLax() {
return of(SameSite.LAX);
}
/**
* Return a new {@link CookieSameSiteSupplier} that always returns
* {@link SameSite#STRICT}.
* @return the supplier instance
*/
static CookieSameSiteSupplier ofStrict() {
return of(SameSite.STRICT);
}
/**
* Return a new {@link CookieSameSiteSupplier} that always returns the given
* {@link SameSite} value.
* @param sameSite the value to return
* @return the supplier instance
*/
static CookieSameSiteSupplier of(SameSite sameSite) {
Assert.notNull(sameSite, "'sameSite' must not be null");
return (cookie) -> sameSite;
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\CookieSameSiteSupplier.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getElementId() {
return elementId;
}
@ApiParam("Only return jobs with the given elementId")
public void setElementId(String elementId) {
this.elementId = elementId;
}
public String getElementName() {
return elementName;
}
@ApiParam("Only return jobs with the given elementName")
public void setElementName(String elementName) {
this.elementName = elementName;
}
public boolean isWithException() {
return withException;
}
@ApiParam("Only return jobs with an exception")
public void setWithException(boolean withException) {
this.withException = withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
@ApiParam("Only return jobs with the given exception message")
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public String getTenantId() {
return tenantId;
}
@ApiParam("Only return jobs with the given tenant id")
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
@ApiParam("Only return jobs with a tenantId like the given value")
public void setTenantIdLike(String tenantIdLike) {
this.tenantIdLike = tenantIdLike;
} | public boolean isWithoutTenantId() {
return withoutTenantId;
}
@ApiParam("Only return jobs without a tenantId")
public void setWithoutTenantId(boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public boolean isLocked() {
return locked;
}
@ApiParam("Only return jobs that are locked")
public void setLocked(boolean locked) {
this.locked = locked;
}
public boolean isUnlocked() {
return unlocked;
}
@ApiParam("Only return jobs that are unlocked")
public void setUnlocked(boolean unlocked) {
this.unlocked = unlocked;
}
public boolean isWithoutScopeType() {
return withoutScopeType;
}
@ApiParam("Only return jobs without a scope type")
public void setWithoutScopeType(boolean withoutScopeType) {
this.withoutScopeType = withoutScopeType;
}
} | repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\query\ExternalWorkerJobQueryRequest.java | 2 |
请完成以下Java代码 | private Evaluatee createEvaluationContext()
{
return Evaluatees.mapBuilder()
.put("MainFromMillis", DB.TO_DATE(timeRange.getFrom()))
.put("MainToMillis", DB.TO_DATE(timeRange.getTo()))
.put("FromMillis", DB.TO_DATE(timeRange.getFrom()))
.put("ToMillis", DB.TO_DATE(timeRange.getTo()))
.put(KPIDataContext.CTXNAME_AD_User_ID, UserId.toRepoId(context.getUserId()))
.put(KPIDataContext.CTXNAME_AD_Role_ID, RoleId.toRepoId(context.getRoleId()))
.put(KPIDataContext.CTXNAME_AD_Client_ID, ClientId.toRepoId(context.getClientId()))
.put(KPIDataContext.CTXNAME_AD_Org_ID, OrgId.toRepoId(context.getOrgId()))
.put("#Date", DB.TO_DATE(SystemTime.asZonedDateTime()))
.build();
} | public KPIZoomIntoDetailsInfo getKPIZoomIntoDetailsInfo()
{
final String sqlWhereClause = datasource
.getSqlDetailsWhereClause()
.evaluate(createEvaluationContext(), IExpressionEvaluator.OnVariableNotFound.Fail);
return KPIZoomIntoDetailsInfo.builder()
.filterCaption(kpiCaption)
.targetWindowId(datasource.getTargetWindowId())
.tableName(datasource.getSourceTableName())
.sqlWhereClause(sqlWhereClause)
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\sql\SQLKPIDataLoader.java | 1 |
请完成以下Java代码 | public class PlanItemFutureJavaDelegateActivityBehavior extends CoreCmmnActivityBehavior {
protected PlanItemFutureJavaDelegate<Object> planItemJavaDelegate;
public PlanItemFutureJavaDelegateActivityBehavior(PlanItemFutureJavaDelegate<?> planItemJavaDelegate) {
this.planItemJavaDelegate = (PlanItemFutureJavaDelegate<Object>) planItemJavaDelegate;
}
@Override
public void execute(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
if (cmmnEngineConfiguration.isLoggingSessionEnabled()) {
CmmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_ENTER,
"Executing service task with java class " + planItemJavaDelegate.getClass().getName(),
planItemInstanceEntity, cmmnEngineConfiguration.getObjectMapper());
}
CompletableFuture<Object> future = planItemJavaDelegate.execute(planItemInstanceEntity, cmmnEngineConfiguration.getAsyncTaskInvoker());
CommandContextUtil.getAgenda(commandContext)
.planFutureOperation(future, new DelegateCompleteAction(planItemInstanceEntity, cmmnEngineConfiguration.isLoggingSessionEnabled()));
}
protected class DelegateCompleteAction implements BiConsumer<Object, Throwable> {
protected final PlanItemInstanceEntity planItemInstance;
protected final boolean loggingSessionEnabled;
public DelegateCompleteAction(PlanItemInstanceEntity planItemInstance, boolean loggingSessionEnabled) {
this.planItemInstance = planItemInstance;
this.loggingSessionEnabled = loggingSessionEnabled;
}
@Override
public void accept(Object value, Throwable throwable) {
if (throwable == null) { | planItemJavaDelegate.afterExecution(planItemInstance, value);
if (loggingSessionEnabled) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration();
CmmnLoggingSessionUtil.addLoggingData(LoggingSessionConstants.TYPE_SERVICE_TASK_EXIT,
"Executed service task with java class " + planItemJavaDelegate.getClass().getName(),
planItemInstance, cmmnEngineConfiguration.getObjectMapper());
}
CommandContextUtil.getAgenda().planCompletePlanItemInstanceOperation(planItemInstance);
} else {
sneakyThrow(throwable);
}
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\PlanItemFutureJavaDelegateActivityBehavior.java | 1 |
请完成以下Java代码 | public void clear()
{
map.clear();
}
@SuppressWarnings("unchecked")
@Override
public Object clone()
{
try
{
final IdentityHashSet<E> newSet = (IdentityHashSet<E>)super.clone();
newSet.map = (IdentityHashMap<E, Object>)map.clone();
return newSet;
}
catch (CloneNotSupportedException e)
{
throw new InternalError();
}
}
// -- Serializable --//
private synchronized void writeObject(java.io.ObjectOutputStream s)
throws java.io.IOException
{
// Write out any hidden serialization magic
s.defaultWriteObject();
// Write out size
s.writeInt(map.size());
// Write out all elements in the proper order.
for (Iterator<E> i = map.keySet().iterator(); i.hasNext();)
s.writeObject(i.next()); | }
private synchronized void readObject(java.io.ObjectInputStream s)
throws java.io.IOException, ClassNotFoundException
{
// Read in any hidden serialization magic
s.defaultReadObject();
// Read in size (number of Mappings)
int size = s.readInt();
// Read in IdentityHashMap capacity and load factor and create backing IdentityHashMap
map = new IdentityHashMap<E, Object>((size * 4) / 3);
// Allow for 33% growth (i.e., capacity is >= 2* size()).
// Read in all elements in the proper order.
for (int i = 0; i < size; i++)
{
@SuppressWarnings("unchecked")
final E e = (E)s.readObject();
map.put(e, PRESENT);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\collections\IdentityHashSet.java | 1 |
请完成以下Java代码 | public void asyncSend(String topic, Message<?> message) {
rocketMQTemplate.asyncSend(topic, message, getDefaultSendCallBack());
}
/**
* 发送异步消息
*
* @param topic 消息Topic
* @param message 消息实体
* @param sendCallback 回调函数
*/
public void asyncSend(String topic, Message<?> message, SendCallback sendCallback) {
rocketMQTemplate.asyncSend(topic, message, sendCallback);
}
/**
* 发送异步消息
*
* @param topic 消息Topic
* @param message 消息实体
* @param sendCallback 回调函数
* @param timeout 超时时间
*/
public void asyncSend(String topic, Message<?> message, SendCallback sendCallback, long timeout) {
rocketMQTemplate.asyncSend(topic, message, sendCallback, timeout);
}
/**
* 发送异步消息
*
* @param topic 消息Topic
* @param message 消息实体
* @param sendCallback 回调函数
* @param timeout 超时时间
* @param delayLevel 延迟消息的级别
*/
public void asyncSend(String topic, Message<?> message, SendCallback sendCallback, long timeout, int delayLevel) {
rocketMQTemplate.asyncSend(topic, message, sendCallback, timeout, delayLevel);
}
/**
* 发送顺序消息
*
* @param message
* @param topic
* @param hashKey
*/
public void syncSendOrderly(Enum topic, Message<?> message, String hashKey) {
syncSendOrderly(topic.name(), message, hashKey);
}
/**
* 发送顺序消息
*
* @param message
* @param topic
* @param hashKey
*/
public void syncSendOrderly(String topic, Message<?> message, String hashKey) {
LOG.info("发送顺序消息,topic:" + topic + ",hashKey:" + hashKey);
rocketMQTemplate.syncSendOrderly(topic, message, hashKey);
}
/**
* 发送顺序消息
*
* @param message
* @param topic
* @param hashKey
* @param timeout
*/
public void syncSendOrderly(String topic, Message<?> message, String hashKey, long timeout) {
LOG.info("发送顺序消息,topic:" + topic + ",hashKey:" + hashKey + ",timeout:" + timeout);
rocketMQTemplate.syncSendOrderly(topic, message, hashKey, timeout); | }
/**
* 默认CallBack函数
*
* @return
*/
private SendCallback getDefaultSendCallBack() {
return new SendCallback() {
@Override
public void onSuccess(SendResult sendResult) {
LOG.info("---发送MQ成功---");
}
@Override
public void onException(Throwable throwable) {
throwable.printStackTrace();
LOG.error("---发送MQ失败---"+throwable.getMessage(), throwable.getMessage());
}
};
}
@PreDestroy
public void destroy() {
LOG.info("---RocketMq助手注销---");
}
} | repos\springboot-demo-master\rocketmq\src\main\java\demo\et59\rocketmq\util\RocketMqHelper.java | 1 |
请完成以下Java代码 | public void addStringListParameter(String name, List<String> value) {
addParameter(name, value, Types.VARCHAR, "VARCHAR");
}
public void addBooleanParameter(String name, boolean value) {
addParameter(name, value, Types.BOOLEAN, "BOOLEAN");
}
public void addUuidListParameter(String name, List<UUID> value) {
addParameter(name, value, UUID_TYPE.getJdbcTypeCode(), UUID_TYPE.getFriendlyName());
}
public String getQuery() {
return query.toString();
}
public static class Parameter {
private final Object value;
private final int type;
private final String name;
public Parameter(Object value, int type, String name) {
this.value = value;
this.type = type; | this.name = name;
}
}
public TenantId getTenantId() {
return securityCtx.getTenantId();
}
public CustomerId getCustomerId() {
return securityCtx.getCustomerId();
}
public EntityType getEntityType() {
return securityCtx.getEntityType();
}
public boolean isIgnorePermissionCheck() {
return securityCtx.isIgnorePermissionCheck();
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\query\SqlQueryContext.java | 1 |
请完成以下Java代码 | public static String decode(String source) {
return decode(source, StandardCharsets.UTF_8);
}
/**
* Decode the given encoded URI component value by replacing each "<i>{@code %xy}</i>"
* sequence with a hexadecimal representation of the character in the specified
* character encoding, leaving other characters unmodified.
* @param source the encoded URI component value
* @param charset the character encoding to use to decode the "<i>{@code %xy}</i>"
* sequences
* @return the decoded value
* @since 4.0.0
*/
public static String decode(String source, Charset charset) {
int length = source.length();
int firstPercentIndex = source.indexOf('%');
if (length == 0 || firstPercentIndex < 0) {
return source;
}
StringBuilder output = new StringBuilder(length);
output.append(source, 0, firstPercentIndex);
byte[] bytes = null;
int i = firstPercentIndex;
while (i < length) {
char ch = source.charAt(i);
if (ch == '%') {
try {
if (bytes == null) {
bytes = new byte[(length - i) / 3];
}
int pos = 0;
while (i + 2 < length && ch == '%') { | bytes[pos++] = (byte) HexFormat.fromHexDigits(source, i + 1, i + 3);
i += 3;
if (i < length) {
ch = source.charAt(i);
}
}
if (i < length && ch == '%') {
throw new IllegalArgumentException("Incomplete trailing escape (%) pattern");
}
output.append(new String(bytes, 0, pos, charset));
}
catch (NumberFormatException ex) {
throw new IllegalArgumentException("Invalid encoded sequence \"" + source.substring(i) + "\"");
}
}
else {
output.append(ch);
i++;
}
}
return output.toString();
}
} | repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\net\util\UrlDecoder.java | 1 |
请完成以下Java代码 | public class C_Queue_WorkPackage_CleanupStaleEntries extends JavaProcess
{
@Override
protected void prepare()
{
// nothing
}
@Override
protected String doIt() throws Exception
{
final int staleWorkpackagesCount = new WorkpackageCleanupStaleEntries()
.setContext(getCtx())
.setLogger(this)
.setAD_PInstance_ID(getPinstanceId()) | .runAndGetUpdatedCount();
//
// If there were stale workpackages found, throw an exception
// We do this because this process is designed to be executed from AD_Scheduler which is monitored by zabbix.
// If the process fails, there will be a log entry in AD_Scheduler system which will be flagged as "IsError"
// and it will be monitored by zabbix which will inform the support guys.
if (staleWorkpackagesCount != 0)
{
throw new AdempiereException("We found and deactivated " + staleWorkpackagesCount + " workpackages");
}
return MSG_OK;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\process\C_Queue_WorkPackage_CleanupStaleEntries.java | 1 |
请完成以下Java代码 | public Integer getRoleId() {
return roleId;
}
/**
* 设置 角色ID.
*
* @param roleId 角色ID.
*/
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
/**
* 获取 权限ID.
*
* @return 权限ID.
*/
public Integer getPermissionId() {
return permissionId;
}
/**
* 设置 权限ID.
*
* @param permissionId 权限ID.
*/
public void setPermissionId(Integer permissionId) {
this.permissionId = permissionId;
}
/**
* 获取 创建时间.
*
* @return 创建时间.
*/
public Date getCreatedTime() {
return createdTime;
}
/**
* 设置 创建时间.
*
* @param createdTime 创建时间. | */
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
/**
* 获取 更新时间.
*
* @return 更新时间.
*/
public Date getUpdatedTime() {
return updatedTime;
}
/**
* 设置 更新时间.
*
* @param updatedTime 更新时间.
*/
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
protected Serializable pkVal() {
return this.id;
}
} | repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\RolePermission.java | 1 |
请完成以下Java代码 | public boolean isContractedProduct()
{
if (getC_Flatrate_Term() != null)
{
return true;
}
return false;
}
@Override
public I_M_Product getM_Product()
{
return Services.get(IProductDAO.class).getById(getProductId());
}
@Override
public int getProductId()
{
return orderLine.getM_Product_ID();
}
@Override
public I_C_UOM getC_UOM()
{
return Services.get(IUOMDAO.class).getById(orderLine.getC_UOM_ID());
}
@Nullable
@Override
public I_C_Flatrate_Term getC_Flatrate_Term()
{
final I_M_HU_PI_Item_Product hupip = getM_HU_PI_Item_Product();
if (hupip == null)
{
// the procurement product must have an M_HU_PI_Item_Product set
return null;
}
// the product and M_HU_PI_Item_Product must belong to a PMM_ProductEntry that is currently valid
final I_PMM_Product pmmProduct = Services.get(IPMMProductBL.class).getPMMProductForDateProductAndASI(
getDate(),
ProductId.ofRepoId(getM_Product().getM_Product_ID()),
BPartnerId.ofRepoIdOrNull(getC_BPartner().getC_BPartner_ID()),
hupip.getM_HU_PI_Item_Product_ID(),
getM_AttributeSetInstance());
if (pmmProduct == null)
{
return null;
}
// retrieve the freshest, currently valid term for the partner and pmm product.
return Services.get(IPMMContractsDAO.class).retrieveTermForPartnerAndProduct(
getDate(),
getC_BPartner().getC_BPartner_ID(),
pmmProduct.getPMM_Product_ID());
}
/**
* @return the M_HU_PI_ItemProduct if set in the orderline. Null othersiwe.
*/
private I_M_HU_PI_Item_Product getM_HU_PI_Item_Product()
{
final de.metas.handlingunits.model.I_C_OrderLine huOrderLine = InterfaceWrapperHelper.create(orderLine, de.metas.handlingunits.model.I_C_OrderLine.class);
return huOrderLine.getM_HU_PI_Item_Product();
}
@Override
public I_C_Flatrate_DataEntry getC_Flatrate_DataEntry()
{ | return Services.get(IPMMContractsDAO.class).retrieveFlatrateDataEntry(
getC_Flatrate_Term(),
getDate());
}
@Override
public Object getWrappedModel()
{
return orderLine;
}
@Override
public Timestamp getDate()
{
return CoalesceUtil.coalesceSuppliers(
() -> orderLine.getDatePromised(),
() -> orderLine.getC_Order().getDatePromised());
}
@Override
public BigDecimal getQty()
{
return orderLine.getQtyOrdered();
}
@Override
public void setM_PricingSystem_ID(int M_PricingSystem_ID)
{
throw new NotImplementedException();
}
@Override
public void setM_PriceList_ID(int M_PriceList_ID)
{
throw new NotImplementedException();
}
/**
* Sets a private member variable to the given {@code price}.
*/
@Override
public void setPrice(BigDecimal price)
{
this.price = price;
}
/**
*
* @return the value that was set via {@link #setPrice(BigDecimal)}.
*/
public BigDecimal getPrice()
{
return price;
}
public I_M_AttributeSetInstance getM_AttributeSetInstance()
{
return orderLine.getM_AttributeSetInstance();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PMMPricingAware_C_OrderLine.java | 1 |
请完成以下Java代码 | public boolean isRequired() {
return required;
}
public boolean isEnabled() {
return enabled;
}
public boolean isActive() {
return active;
}
public boolean isDisabled() {
return disabled;
}
public static CaseExecutionDto fromCaseExecution(CaseExecution caseExecution) {
CaseExecutionDto dto = new CaseExecutionDto();
dto.id = caseExecution.getId(); | dto.caseInstanceId = caseExecution.getCaseInstanceId();
dto.caseDefinitionId = caseExecution.getCaseDefinitionId();
dto.activityId = caseExecution.getActivityId();
dto.activityName = caseExecution.getActivityName();
dto.activityType = caseExecution.getActivityType();
dto.activityDescription = caseExecution.getActivityDescription();
dto.parentId = caseExecution.getParentId();
dto.tenantId = caseExecution.getTenantId();
dto.required = caseExecution.isRequired();
dto.active = caseExecution.isActive();
dto.enabled = caseExecution.isEnabled();
dto.disabled = caseExecution.isDisabled();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\CaseExecutionDto.java | 1 |
请完成以下Java代码 | public static LocatorScannedCodeResolverResult notFound(@NonNull final List<LocatorNotResolvedReason> notFoundReasons)
{
return new LocatorScannedCodeResolverResult(notFoundReasons);
}
public static LocatorScannedCodeResolverResult found(@NonNull final LocatorQRCode locatorQRCode)
{
return new LocatorScannedCodeResolverResult(locatorQRCode);
}
public boolean isFound() {return locatorQRCode != null;}
@NonNull
public LocatorId getLocatorId()
{ | return getLocatorQRCode().getLocatorId();
}
@NonNull
public LocatorQRCode getLocatorQRCode()
{
if (locatorQRCode == null)
{
throw AdempiereException.notFound()
.setParameter("notResolvedReasons", notResolvedReasons);
}
return locatorQRCode;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\resolver\LocatorScannedCodeResolverResult.java | 1 |
请完成以下Java代码 | public void discover() {
doDiscover(HandlerSupplier.class, HandlerFunction.class);
doDiscover(HandlerSupplier.class, HandlerDiscoverer.Result.class);
}
public static class Result {
private final HandlerFunction<ServerResponse> handlerFunction;
private final List<HandlerFilterFunction<ServerResponse, ServerResponse>> lowerPrecedenceFilters;
private final List<HandlerFilterFunction<ServerResponse, ServerResponse>> higherPrecedenceFilters;
public Result(HandlerFunction<ServerResponse> handlerFunction,
List<HandlerFilterFunction<ServerResponse, ServerResponse>> lowerPrecedenceFilters,
List<HandlerFilterFunction<ServerResponse, ServerResponse>> higherPrecedenceFilters) {
this.handlerFunction = handlerFunction;
this.lowerPrecedenceFilters = Objects.requireNonNullElse(lowerPrecedenceFilters, Collections.emptyList());
this.higherPrecedenceFilters = Objects.requireNonNullElse(higherPrecedenceFilters, Collections.emptyList());
} | public HandlerFunction<ServerResponse> getHandlerFunction() {
return handlerFunction;
}
public List<HandlerFilterFunction<ServerResponse, ServerResponse>> getLowerPrecedenceFilters() {
return lowerPrecedenceFilters;
}
public List<HandlerFilterFunction<ServerResponse, ServerResponse>> getHigherPrecedenceFilters() {
return higherPrecedenceFilters;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\HandlerDiscoverer.java | 1 |
请完成以下Spring Boot application配置 | server:
port: 8082 # 端口
spring:
application:
name: product-service
datasource:
url: jdbc:mysql://127.0.0.1:3306/seata_product?useSSL=false&useUnicode=true&characterEncoding=UTF-8
driver-class-name: com.mysql.jdbc.Driver
username: root
password:
# Seata 配置项,对应 SeataProperties 类
seata:
application-id: ${spring.application.name} # Seata 应用编号,默认为 ${spring.application.name}
tx-service-group: ${spring.application.name}-group # Seata | 事务组编号,用于 TC 集群名
# 服务配置项,对应 ServiceProperties 类
service:
# 虚拟组和分组的映射
vgroup-mapping:
product-service-group: default
# 分组和 Seata 服务的映射
grouplist:
default: 127.0.0.1:8091 | repos\SpringBoot-Labs-master\lab-52\lab-52-seata-at-httpclient-demo\lab-52-seata-at-httpclient-demo-product-service\src\main\resources\application.yaml | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ReceiptCandidatesRestController
{
private final ReceiptCandidateAPIService receiptCandidateAPIService;
public ReceiptCandidatesRestController(@NonNull final ReceiptCandidateAPIService receiptCandidateAPIService)
{
this.receiptCandidateAPIService = receiptCandidateAPIService;
}
@GetMapping("receiptCandidates")
public ResponseEntity<JsonResponseReceiptCandidates> getReceiptCandidates(
@ApiParam("Max number of items to be returned in one request.") //
@RequestParam(name = "limit", required = false, defaultValue = "500") //
@Nullable final Integer limit)
{ | final QueryLimit limitEff = QueryLimit.ofNullableOrNoLimit(limit).ifNoLimitUse(500);
final JsonResponseReceiptCandidates result = receiptCandidateAPIService.exportReceiptCandidates(limitEff);
return ResponseEntity.ok(result);
}
@PostMapping("receiptCandidatesResult")
public ResponseEntity<String> postReceiptCandidatesStatus(@RequestBody @NonNull final JsonRequestCandidateResults status)
{
try (final MDC.MDCCloseable ignore = MDC.putCloseable("TransactionIdAPI", status.getTransactionKey()))
{
receiptCandidateAPIService.updateStatus(status);
return ResponseEntity.accepted().body("Receipt candidates updated");
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v1\shipping\ReceiptCandidatesRestController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JsonAttribute
{
@NonNull AttributeCode code;
@NonNull String caption;
@NonNull JsonAttributeValueType valueType;
@Nullable Object value;
@Nullable String valueFormatted;
public static JsonAttribute of(@NonNull Attribute attribute, @NonNull final String adLanguage)
{
return JsonAttribute.builder()
.code(attribute.getAttributeCode())
.caption(attribute.getDisplayName().translate(adLanguage))
.valueType(JsonAttributeValueType.of(attribute.getValueType()))
.value(attribute.getValueAsJson())
.valueFormatted(attribute.getValueAsTranslatableString().translate(adLanguage)) | .build();
}
public static List<JsonAttribute> ofList(@NonNull List<Attribute> attributes, @NonNull final String adLanguage)
{
return attributes.stream()
.map(attribute -> JsonAttribute.of(attribute, adLanguage))
.collect(ImmutableList.toImmutableList());
}
public static List<JsonAttribute> of(@NonNull Attributes attributes, @NonNull final String adLanguage)
{
return ofList(attributes.getAttributes(), adLanguage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\json\JsonAttribute.java | 2 |
请完成以下Java代码 | protected Object evaluateScript(ScriptingEngines scriptingEngines, ScriptEngineRequest request) {
return scriptingEngines.evaluate(request).getResult();
}
protected void validateParameters() {
if (script == null) {
throw new FlowableIllegalStateException("The field 'script' should be set on " + getClass().getSimpleName());
}
if (language == null) {
throw new FlowableIllegalStateException("The field 'language' should be set on " + getClass().getSimpleName());
}
}
protected abstract ScriptingEngines getScriptingEngines();
public void setScript(String script) {
this.script = script;
}
/**
* Sets the script as Expression for backwards compatibility.
* Requires to for 'field' injection of scripts.
* Expression is not evaluated
*/ | public void setScript(Expression script) {
this.script = script.getExpressionText();
}
public String getScript() {
return script;
}
public void setLanguage(Expression language) {
this.language = language;
}
public void setResultVariable(Expression resultVariable) {
this.resultVariable = resultVariable;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\scripting\AbstractScriptEvaluator.java | 1 |
请完成以下Java代码 | public void throwAsGotoAntiPattern() throws MyException {
try {
// bunch of code
throw new MyException();
// second bunch of code
} catch ( MyException e ) {
// third bunch of code
}
}
public int getPlayerScoreSwallowingExceptionAntiPattern(String playerFile) {
try {
// ...
} catch (Exception e) {} // <== catch and swallow
return 0;
}
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative(String playerFile) {
try {
// ...
} catch (Exception e) {
e.printStackTrace();
}
return 0;
}
public int getPlayerScoreSwallowingExceptionAntiPatternAlternative2(String playerFile) throws PlayerScoreException {
try {
throw new IOException(); | } catch (IOException e) {
throw new PlayerScoreException(e);
}
}
public int getPlayerScoreReturnInFinallyAntiPattern(String playerFile) {
int score = 0;
try {
throw new IOException();
} finally {
return score; // <== the IOException is dropped
}
}
private boolean isFilenameValid(String name) {
return false;
}
} | repos\tutorials-master\core-java-modules\core-java-exceptions\src\main\java\com\baeldung\exceptions\exceptionhandling\Exceptions.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Pair<ApiFeature, ApiUsageStateValue> checkStateUpdatedDueToThreshold(ApiFeature feature) {
ApiUsageStateValue featureValue = ApiUsageStateValue.ENABLED;
for (ApiUsageRecordKey recordKey : ApiUsageRecordKey.getKeys(feature)) {
long value = get(recordKey);
boolean featureEnabled = getProfileFeatureEnabled(recordKey);
ApiUsageStateValue tmpValue;
if (featureEnabled) {
long threshold = getProfileThreshold(recordKey);
long warnThreshold = getProfileWarnThreshold(recordKey);
if (threshold == 0 || value == 0 || value < warnThreshold) {
tmpValue = ApiUsageStateValue.ENABLED;
} else if (value < threshold) {
tmpValue = ApiUsageStateValue.WARNING;
} else {
tmpValue = ApiUsageStateValue.DISABLED;
}
} else {
tmpValue = ApiUsageStateValue.DISABLED;
}
featureValue = ApiUsageStateValue.toMoreRestricted(featureValue, tmpValue);
}
return setFeatureValue(feature, featureValue) ? Pair.of(feature, featureValue) : null;
}
public Map<ApiFeature, ApiUsageStateValue> checkStateUpdatedDueToThresholds() {
return checkStateUpdatedDueToThreshold(new HashSet<>(Arrays.asList(ApiFeature.values())));
} | public Map<ApiFeature, ApiUsageStateValue> checkStateUpdatedDueToThreshold(Set<ApiFeature> features) {
Map<ApiFeature, ApiUsageStateValue> result = new HashMap<>();
for (ApiFeature feature : features) {
Pair<ApiFeature, ApiUsageStateValue> tmp = checkStateUpdatedDueToThreshold(feature);
if (tmp != null) {
result.put(tmp.getFirst(), tmp.getSecond());
}
}
return result;
}
@Override
public EntityType getEntityType() {
return EntityType.TENANT;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\apiusage\TenantApiUsageState.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String getSerialNumber() {
return serialNumber;
}
public void setSerialNumber(String serialNumber) {
this.serialNumber = serialNumber;
}
public DeviceMapping updated(OffsetDateTime updated) {
this.updated = updated;
return this;
}
/**
* Der Zeitstempel der letzten Änderung
* @return updated
**/
@Schema(example = "2020-11-28T08:37:39.637Z", description = "Der Zeitstempel der letzten Änderung")
public OffsetDateTime getUpdated() {
return updated;
}
public void setUpdated(OffsetDateTime updated) {
this.updated = updated;
}
@Override
public boolean equals(java.lang.Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeviceMapping deviceMapping = (DeviceMapping) o;
return Objects.equals(this._id, deviceMapping._id) &&
Objects.equals(this.serialNumber, deviceMapping.serialNumber) &&
Objects.equals(this.updated, deviceMapping.updated);
} | @Override
public int hashCode() {
return Objects.hash(_id, serialNumber, updated);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeviceMapping {\n");
sb.append(" _id: ").append(toIndentedString(_id)).append("\n");
sb.append(" serialNumber: ").append(toIndentedString(serialNumber)).append("\n");
sb.append(" updated: ").append(toIndentedString(updated)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceMapping.java | 2 |
请完成以下Java代码 | public static MOrg[] getOfClient (PO po)
{
return getOfClient(po.getCtx(), po.getAD_Client_ID());
}
// metas
public static MOrg[] getOfClient(Properties ctx, int AD_Client_ID)
{
final List<I_AD_Org> clientOrgs = Services.get(IOrgDAO.class).retrieveClientOrgs(ctx, AD_Client_ID);
return LegacyAdapters.convertToPOArray(clientOrgs, MOrg.class);
} // getOfClient
@Deprecated
public static MOrg get (Properties ctx, int AD_Org_ID)
{
if (AD_Org_ID < 0)
{
return null;
}
final I_AD_Org org = Services.get(IOrgDAO.class).retrieveOrg(ctx, AD_Org_ID);
return LegacyAdapters.convertToPO(org);
} // get
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param AD_Org_ID id
* @param trxName transaction
*/
public MOrg (Properties ctx, int AD_Org_ID, String trxName)
{
super(ctx, AD_Org_ID, trxName);
if (is_new())
{
// setValue (null);
// setName (null);
setIsSummary (false);
}
} // MOrg
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MOrg (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MOrg
/**
* Parent Constructor
* @param client client
* @param name name
*/
public MOrg (MClient client, String name)
{
this (client.getCtx(), -1, client.get_TrxName());
setAD_Client_ID (client.getAD_Client_ID());
setValue (name);
setName (name); | } // MOrg
/** Linked Business Partner */
private Integer m_linkedBPartner = null;
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
if (!success)
{
return success;
}
if (newRecord)
{
// Info
Services.get(IOrgDAO.class).createOrUpdateOrgInfo(OrgInfoUpdateRequest.builder()
.orgId(OrgId.ofRepoId(getAD_Org_ID()))
.build());
// TreeNode
// insert_Tree(MTree_Base.TREETYPE_Organization);
}
// Value/Name change
if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name")))
{
MAccount.updateValueDescription(getCtx(), "AD_Org_ID=" + getAD_Org_ID(), get_TrxName());
final String elementOrgTrx = Env.CTXNAME_AcctSchemaElementPrefix + X_C_AcctSchema_Element.ELEMENTTYPE_OrgTrx;
if ("Y".equals(Env.getContext(getCtx(), elementOrgTrx)))
{
MAccount.updateValueDescription(getCtx(), "AD_OrgTrx_ID=" + getAD_Org_ID(), get_TrxName());
}
}
return true;
} // afterSave
/**
* Get Linked BPartner
* @return C_BPartner_ID
*/
public int getLinkedC_BPartner_ID(String trxName)
{
if (m_linkedBPartner == null)
{
int C_BPartner_ID = DB.getSQLValue(trxName,
"SELECT C_BPartner_ID FROM C_BPartner WHERE AD_OrgBP_ID=?",
getAD_Org_ID());
if (C_BPartner_ID < 0)
{
C_BPartner_ID = 0;
}
m_linkedBPartner = new Integer (C_BPartner_ID);
}
return m_linkedBPartner.intValue();
} // getLinkedC_BPartner_ID
} // MOrg | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MOrg.java | 1 |
请完成以下Java代码 | 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 setIsToleranceExceeded (final boolean IsToleranceExceeded)
{
set_Value (COLUMNNAME_IsToleranceExceeded, IsToleranceExceeded);
}
@Override
public boolean isToleranceExceeded()
{
return get_ValueAsBoolean(COLUMNNAME_IsToleranceExceeded);
}
@Override
public void setLine (final int Line)
{
set_Value (COLUMNNAME_Line, Line);
}
@Override
public int getLine()
{
return get_ValueAsInt(COLUMNNAME_Line);
}
@Override
public void setPP_Order_Weighting_RunCheck_ID (final int PP_Order_Weighting_RunCheck_ID)
{
if (PP_Order_Weighting_RunCheck_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_RunCheck_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_RunCheck_ID, PP_Order_Weighting_RunCheck_ID);
}
@Override
public int getPP_Order_Weighting_RunCheck_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_RunCheck_ID);
} | @Override
public org.eevolution.model.I_PP_Order_Weighting_Run getPP_Order_Weighting_Run()
{
return get_ValueAsPO(COLUMNNAME_PP_Order_Weighting_Run_ID, org.eevolution.model.I_PP_Order_Weighting_Run.class);
}
@Override
public void setPP_Order_Weighting_Run(final org.eevolution.model.I_PP_Order_Weighting_Run PP_Order_Weighting_Run)
{
set_ValueFromPO(COLUMNNAME_PP_Order_Weighting_Run_ID, org.eevolution.model.I_PP_Order_Weighting_Run.class, PP_Order_Weighting_Run);
}
@Override
public void setPP_Order_Weighting_Run_ID (final int PP_Order_Weighting_Run_ID)
{
if (PP_Order_Weighting_Run_ID < 1)
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PP_Order_Weighting_Run_ID, PP_Order_Weighting_Run_ID);
}
@Override
public int getPP_Order_Weighting_Run_ID()
{
return get_ValueAsInt(COLUMNNAME_PP_Order_Weighting_Run_ID);
}
@Override
public void setWeight (final BigDecimal Weight)
{
set_Value (COLUMNNAME_Weight, Weight);
}
@Override
public BigDecimal getWeight()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_Order_Weighting_RunCheck.java | 1 |
请完成以下Java代码 | public static Set<String> gatherStringPropertyFromJsonNodes(Iterable<JsonNode> jsonNodes, String propertyName) {
Set<String> result = new HashSet<String>(); // Using a Set to filter out doubles
for (JsonNode node : jsonNodes) {
if (node.has(propertyName)) {
String propertyValue = node.get(propertyName).asText();
if (propertyValue != null) {
// Just to be safe
result.add(propertyValue);
}
}
}
return result;
}
public static List<JsonNode> filterOutJsonNodes(List<JsonLookupResult> lookupResults) {
List<JsonNode> jsonNodes = new ArrayList<JsonNode>(lookupResults.size());
for (JsonLookupResult lookupResult : lookupResults) {
jsonNodes.add(lookupResult.getJsonNode());
}
return jsonNodes;
}
// Helper classes
public static class JsonLookupResult {
private String id;
private String name;
private JsonNode jsonNode;
public JsonLookupResult(String id, String name, JsonNode jsonNode) {
this(name, jsonNode);
this.id = id;
}
public JsonLookupResult(String name, JsonNode jsonNode) {
this.name = name;
this.jsonNode = jsonNode;
}
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 JsonNode getJsonNode() {
return jsonNode;
}
public void setJsonNode(JsonNode jsonNode) {
this.jsonNode = jsonNode;
}
}
} | repos\Activiti-develop\activiti-core\activiti-json-converter\src\main\java\org\activiti\editor\language\json\converter\util\JsonConverterUtil.java | 1 |
请完成以下Java代码 | public void updateBillToAddress(final I_C_Flatrate_Term term)
{
documentLocationBL.updateRenderedAddressAndCapturedLocation(ContractDocumentLocationAdapterFactory.billLocationAdapter(term));
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = {
I_C_Flatrate_Term.COLUMNNAME_DropShip_BPartner_ID,
I_C_Flatrate_Term.COLUMNNAME_DropShip_Location_ID,
I_C_Flatrate_Term.COLUMNNAME_DropShip_User_ID },
skipIfCopying = true)
public void updateDropshipAddress(final I_C_Flatrate_Term term)
{
documentLocationBL.updateRenderedAddressAndCapturedLocation(ContractDocumentLocationAdapterFactory.dropShipLocationAdapter(term));
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_NEW,
ModelValidator.TYPE_BEFORE_CHANGE
},
ifColumnsChanged = {
I_C_Flatrate_Term.COLUMNNAME_Type_Conditions,
I_C_Flatrate_Term.COLUMNNAME_StartDate,
I_C_Flatrate_Term.COLUMNNAME_EndDate,
I_C_Flatrate_Term.COLUMNNAME_AD_Org_ID,
I_C_Flatrate_Term.COLUMNNAME_Bill_BPartner_ID
})
public void ensureOneContract(@NonNull final I_C_Flatrate_Term term)
{
ensureOneContractOfGivenType(term);
}
@DocValidate(timings = ModelValidator.TIMING_BEFORE_COMPLETE)
public void ensureOneContractBeforeComplete(@NonNull final I_C_Flatrate_Term term)
{
ensureOneContractOfGivenType(term);
}
private void ensureOneContractOfGivenType(@NonNull final I_C_Flatrate_Term term)
{
flatrateBL.ensureOneContractOfGivenType(term, TypeConditions.MARGIN_COMMISSION);
final TypeConditions contractType = TypeConditions.ofCode(term.getType_Conditions());
switch (contractType)
{ | case MEDIATED_COMMISSION:
case MARGIN_COMMISSION:
case LICENSE_FEE:
flatrateBL.ensureOneContractOfGivenType(term, contractType);
default:
logger.debug("Skipping ensureOneContractOfGivenType check for 'Type_Conditions' =" + contractType);
}
}
@DocValidate(timings = { ModelValidator.TIMING_BEFORE_COMPLETE })
public void setC_Flatrate_Term_Master(@NonNull final I_C_Flatrate_Term term)
{
if (term.getC_Flatrate_Term_Master_ID() <= 0)
{
final I_C_Flatrate_Term ancestor = flatrateDAO.retrieveAncestorFlatrateTerm(term);
if (ancestor == null)
{
term.setC_Flatrate_Term_Master_ID(term.getC_Flatrate_Term_ID());
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\interceptor\C_Flatrate_Term.java | 1 |
请完成以下Java代码 | public int hashCode()
{
return pipeList.hashCode();
}
@Override
public Pipe<M, M> get(int index)
{
return pipeList.get(index);
}
@Override
public Pipe<M, M> set(int index, Pipe<M, M> element)
{
return pipeList.set(index, element);
}
@Override
public void add(int index, Pipe<M, M> element)
{
pipeList.add(index, element);
}
/**
* 以最高优先级加入管道
*
* @param pipe
*/
public void addFirst(Pipe<M, M> pipe)
{
pipeList.addFirst(pipe);
}
/**
* 以最低优先级加入管道
*
* @param pipe
*/
public void addLast(Pipe<M, M> pipe)
{
pipeList.addLast(pipe);
}
@Override
public Pipe<M, M> remove(int index) | {
return pipeList.remove(index);
}
@Override
public int indexOf(Object o)
{
return pipeList.indexOf(o);
}
@Override
public int lastIndexOf(Object o)
{
return pipeList.lastIndexOf(o);
}
@Override
public ListIterator<Pipe<M, M>> listIterator()
{
return pipeList.listIterator();
}
@Override
public ListIterator<Pipe<M, M>> listIterator(int index)
{
return pipeList.listIterator(index);
}
@Override
public List<Pipe<M, M>> subList(int fromIndex, int toIndex)
{
return pipeList.subList(fromIndex, toIndex);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\tokenizer\pipe\Pipeline.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class JsonResponseManufacturingOrder
{
@NonNull
JsonMetasfreshId orderId;
@NonNull
String orgCode;
@NonNull
String documentNo;
@Nullable
String description;
@NonNull
ZonedDateTime dateOrdered;
@NonNull | ZonedDateTime dateStartSchedule;
@NonNull
JsonProduct finishGoodProduct;
@NonNull
JsonQuantity qtyToProduce;
@NonNull
@Singular
List<JsonResponseManufacturingOrderBOMLine> components;
@JsonPOJOBuilder(withPrefix = "")
public static class JsonResponseManufacturingOrderBuilder
{
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-manufacturing\src\main\java\de\metas\common\manufacturing\v1\JsonResponseManufacturingOrder.java | 2 |
请完成以下Java代码 | public static String convertToTitleCaseSplitting(String text) {
if (text == null || text.isEmpty()) {
return text;
}
return Arrays
.stream(text.split(WORD_SEPARATOR))
.map(word -> word.isEmpty()
? word
: Character.toTitleCase(word.charAt(0)) + word
.substring(1)
.toLowerCase())
.collect(Collectors.joining(WORD_SEPARATOR));
}
public static String convertToTitleCaseIcu4j(String text) { | if (text == null || text.isEmpty()) {
return text;
}
return UCharacter.toTitleCase(text, BreakIterator.getTitleInstance());
}
public static String convertToTileCaseWordUtilsFull(String text) {
return WordUtils.capitalizeFully(text);
}
public static String convertToTileCaseWordUtils(String text) {
return WordUtils.capitalize(text);
}
} | repos\tutorials-master\core-java-modules\core-java-string-conversions-4\src\main\java\com\baeldung\titlecase\TitleCaseConverter.java | 1 |
请完成以下Java代码 | public void delete(final I_M_HU_Attribute huAttribute)
{
final SaveDecoupledHUAttributesDAO delegate = getDelegate();
delegate.delete(huAttribute);
}
@Override
public List<I_M_HU_Attribute> retrieveAllAttributesNoCache(final Collection<HuId> huIds)
{
final SaveDecoupledHUAttributesDAO delegate = getDelegate();
return delegate.retrieveAllAttributesNoCache(huIds);
}
@Override
public HUAndPIAttributes retrieveAttributesOrdered(final I_M_HU hu)
{
final SaveDecoupledHUAttributesDAO delegate = getDelegate();
return delegate.retrieveAttributesOrdered(hu); | }
@Override
public I_M_HU_Attribute retrieveAttribute(final I_M_HU hu, final AttributeId attributeId)
{
final SaveDecoupledHUAttributesDAO delegate = getDelegate();
return delegate.retrieveAttribute(hu, attributeId);
}
@Override
public void flush()
{
final SaveDecoupledHUAttributesDAO attributesDAO = getDelegateOrNull();
if (attributesDAO != null)
{
attributesDAO.flush();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\impl\SaveOnCommitHUAttributesDAO.java | 1 |
请完成以下Java代码 | default int getSearchStringMinLength()
{
return -1;
}
default Optional<Duration> getSearchStartDelay()
{
return Optional.empty();
}
default <T extends LookupDescriptor> T cast(final Class<T> ignoredLookupDescriptorClass)
{
@SuppressWarnings("unchecked")
final T thisCasted = (T)this;
return thisCasted;
}
default <T extends LookupDescriptor> T castOrNull(final Class<T> lookupDescriptorClass) | {
if (lookupDescriptorClass.isAssignableFrom(getClass()))
{
@SuppressWarnings("unchecked")
final T thisCasted = (T)this;
return thisCasted;
}
return null;
}
default TooltipType getTooltipType()
{
return TooltipType.DEFAULT;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\LookupDescriptor.java | 1 |
请完成以下Java代码 | public PgPassParseException setConfigFile(final File configFile)
{
this.configFile = configFile;
return this;
}
public File getConfigFile()
{
return configFile;
}
public PgPassParseException setConfigLineNo(final int configLineNo)
{
this.configLineNo = configLineNo;
return this;
}
public int getLineNo()
{
return configLineNo;
}
@Override
public String getMessage()
{
final StringBuilder sb = new StringBuilder();
sb.append("Parse error: ");
final String message = super.getMessage();
if (message != null && !message.isEmpty())
{ | sb.append(message);
}
else
{
sb.append("unknown");
}
if (configFile != null)
{
sb.append("\nConfig file: ").append(configFile);
}
if (configLineNo > 0)
{
sb.append("\nLine: ").append(configLineNo);
}
return sb.toString();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\sql\postgresql\PgPassParseException.java | 1 |
请完成以下Java代码 | public final class NullModelTranslationMap implements IModelTranslationMap
{
public static final transient IModelTranslationMap instance = new NullModelTranslationMap();
private NullModelTranslationMap()
{
}
@Override
public int getRecordId()
{
throw new UnsupportedOperationException();
}
@Override
public IModelTranslation getTranslation(final String adLanguage)
{
return NullModelTranslation.instance;
}
@Override
public Map<String, IModelTranslation> getAllTranslations() | {
return ImmutableMap.of();
}
@Override
public ITranslatableString getColumnTrl(final String columnName, final String defaultValue)
{
return TranslatableStrings.anyLanguage(defaultValue);
}
@Override
public Optional<String> translateColumn(final String columnName, final String adLanguage)
{
return Optional.empty();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\impl\NullModelTranslationMap.java | 1 |
请完成以下Java代码 | public class ExecutorRouteConsistentHash extends ExecutorRouter {
private static int VIRTUAL_NODE_NUM = 100;
/**
* get hash code on 2^32 ring (md5散列的方式计算hash值)
* @param key
* @return
*/
private static long hash(String key) {
// md5 byte
MessageDigest md5;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 not supported", e);
}
md5.reset();
byte[] keyBytes = null;
try {
keyBytes = key.getBytes("UTF-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("Unknown string :" + key, e);
}
md5.update(keyBytes);
byte[] digest = md5.digest();
// hash code, Truncate to 32-bits
long hashCode = ((long) (digest[3] & 0xFF) << 24)
| ((long) (digest[2] & 0xFF) << 16)
| ((long) (digest[1] & 0xFF) << 8)
| (digest[0] & 0xFF);
long truncateHashCode = hashCode & 0xffffffffL;
return truncateHashCode;
} | public String hashJob(int jobId, List<String> addressList) {
// ------A1------A2-------A3------
// -----------J1------------------
TreeMap<Long, String> addressRing = new TreeMap<Long, String>();
for (String address: addressList) {
for (int i = 0; i < VIRTUAL_NODE_NUM; i++) {
long addressHash = hash("SHARD-" + address + "-NODE-" + i);
addressRing.put(addressHash, address);
}
}
long jobHash = hash(String.valueOf(jobId));
SortedMap<Long, String> lastRing = addressRing.tailMap(jobHash);
if (!lastRing.isEmpty()) {
return lastRing.get(lastRing.firstKey());
}
return addressRing.firstEntry().getValue();
}
@Override
public ReturnT<String> route(TriggerParam triggerParam, List<String> addressList) {
String address = hashJob(triggerParam.getJobId(), addressList);
return new ReturnT<String>(address);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\route\strategy\ExecutorRouteConsistentHash.java | 1 |
请完成以下Java代码 | public void onClose(Session session, CloseReason closeReason) {
logger.info("[onClose][session({}) 连接关闭。关闭原因是({})}]", session, closeReason);
WebSocketUtil.removeSession(session);
}
@OnError
public void onError(Session session, Throwable throwable) {
logger.info("[onClose][session({}) 发生异常]", session, throwable);
}
@Override
public void afterPropertiesSet() throws Exception {
// 通过 ApplicationContext 获得所有 MessageHandler Bean
applicationContext.getBeansOfType(MessageHandler.class).values() // 获得所有 MessageHandler Bean
.forEach(messageHandler -> HANDLERS.put(messageHandler.getType(), messageHandler)); // 添加到 handlers 中
logger.info("[afterPropertiesSet][消息处理器数量:{}]", HANDLERS.size());
}
private Class<? extends Message> getMessageClass(MessageHandler handler) {
// 获得 Bean 对应的 Class 类名。因为有可能被 AOP 代理过。
Class<?> targetClass = AopProxyUtils.ultimateTargetClass(handler);
// 获得接口的 Type 数组
Type[] interfaces = targetClass.getGenericInterfaces();
Class<?> superclass = targetClass.getSuperclass();
while ((Objects.isNull(interfaces) || 0 == interfaces.length) && Objects.nonNull(superclass)) { // 此处,是以父类的接口为准
interfaces = superclass.getGenericInterfaces();
superclass = targetClass.getSuperclass();
}
if (Objects.nonNull(interfaces)) { | // 遍历 interfaces 数组
for (Type type : interfaces) {
// 要求 type 是泛型参数
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
// 要求是 MessageHandler 接口
if (Objects.equals(parameterizedType.getRawType(), MessageHandler.class)) {
Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
// 取首个元素
if (Objects.nonNull(actualTypeArguments) && actualTypeArguments.length > 0) {
return (Class<Message>) actualTypeArguments[0];
} else {
throw new IllegalStateException(String.format("类型(%s) 获得不到消息类型", handler));
}
}
}
}
}
throw new IllegalStateException(String.format("类型(%s) 获得不到消息类型", handler));
}
} | repos\SpringBoot-Labs-master\lab-25\lab-websocket-25-01\src\main\java\cn\iocoder\springboot\lab25\springwebsocket\websocket\WebsocketServerEndpoint.java | 1 |
请完成以下Java代码 | public class BpmnAggregatedVariableType implements VariableType {
public static final String TYPE_NAME = "bpmnAggregation";
protected final ProcessEngineConfigurationImpl processEngineConfiguration;
public BpmnAggregatedVariableType(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
@Override
public String getTypeName() {
return TYPE_NAME;
}
@Override
public boolean isCachable() {
return true;
}
@Override
public boolean isAbleToStore(Object value) {
return value instanceof BpmnAggregation;
} | @Override
public boolean isReadOnly() {
return true;
}
@Override
public void setValue(Object value, ValueFields valueFields) {
if (value instanceof BpmnAggregation) {
valueFields.setTextValue(((BpmnAggregation) value).getExecutionId());
} else {
valueFields.setTextValue(null);
}
}
@Override
public Object getValue(ValueFields valueFields) {
CommandContext commandContext = Context.getCommandContext();
if (commandContext != null) {
return BpmnAggregation.aggregateOverview(valueFields.getTextValue(), valueFields.getName(), commandContext);
} else {
return processEngineConfiguration.getCommandExecutor()
.execute(context -> BpmnAggregation.aggregateOverview(valueFields.getTextValue(), valueFields.getName(), context));
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\variable\BpmnAggregatedVariableType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public PlatformTransactionManager getTransactionManager() {
return transactionManager;
}
public void setTransactionManager(PlatformTransactionManager transactionManager) {
this.transactionManager = transactionManager;
}
public PlatformTransactionManager getCamundaTransactionManager() {
return camundaTransactionManager;
}
public void setCamundaTransactionManager(PlatformTransactionManager camundaTransactionManager) {
this.camundaTransactionManager = camundaTransactionManager;
}
public DataSource getDataSource() {
return dataSource; | }
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public DataSource getCamundaDataSource() {
return camundaDataSource;
}
public void setCamundaDataSource(DataSource camundaDataSource) {
this.camundaDataSource = camundaDataSource;
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\configuration\impl\DefaultDatasourceConfiguration.java | 2 |
请完成以下Java代码 | public void lock()
{
// assertUnlock();
allTags = new int[size()];
for (int i = 0; i < size(); i++)
{
allTags[i] = i;
}
}
// private void assertUnlock()
// {
// if (allTags != null)
// {
// throw new IllegalStateException("标注集已锁定,无法修改");
// }
// }
@Override
public String stringOf(int id)
{
return idStringMap.get(id);
}
@Override
public int idOf(String string)
{
Integer id = stringIdMap.get(string);
if (id == null) id = -1;
return id;
}
@Override
public Iterator<Map.Entry<String, Integer>> iterator()
{
return stringIdMap.entrySet().iterator();
}
/**
* 获取所有标签及其下标
*
* @return
*/
public int[] allTags()
{
return allTags;
}
public void save(DataOutputStream out) throws IOException
{
out.writeInt(type.ordinal());
out.writeInt(size());
for (String tag : idStringMap)
{
out.writeUTF(tag);
}
}
@Override
public boolean load(ByteArray byteArray)
{
idStringMap.clear(); | stringIdMap.clear();
int size = byteArray.nextInt();
for (int i = 0; i < size; i++)
{
String tag = byteArray.nextUTF();
idStringMap.add(tag);
stringIdMap.put(tag, i);
}
lock();
return true;
}
public void load(DataInputStream in) throws IOException
{
idStringMap.clear();
stringIdMap.clear();
int size = in.readInt();
for (int i = 0; i < size; i++)
{
String tag = in.readUTF();
idStringMap.add(tag);
stringIdMap.put(tag, i);
}
lock();
}
public Collection<String> tags()
{
return idStringMap;
}
public boolean contains(String tag)
{
return idStringMap.contains(tag);
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\tagset\TagSet.java | 1 |
请完成以下Java代码 | public void resetCacheFor(@NonNull final I_DataEntry_ListValue dataEntryListValueRecord)
{
if (dataEntryListValueRecord.getDataEntry_Field_ID() > 0)
{
resetCacheFor(dataEntryListValueRecord.getDataEntry_Field());
}
}
public void resetCacheFor(@NonNull final I_DataEntry_Field dataEntryFieldRecord)
{
if (dataEntryFieldRecord.getDataEntry_Line_ID() > 0)
{
resetCacheFor(dataEntryFieldRecord.getDataEntry_Line());
}
}
public void resetCacheFor(@NonNull final I_DataEntry_Line dataEntryLineRecord)
{
if (dataEntryLineRecord.getDataEntry_Section_ID() > 0)
{
resetCacheFor(dataEntryLineRecord.getDataEntry_Section());
}
}
public void resetCacheFor(@NonNull final I_DataEntry_Section dataEntrySectionRecord)
{
if (dataEntrySectionRecord.getDataEntry_SubTab_ID() > 0) | {
resetCacheFor(dataEntrySectionRecord.getDataEntry_SubTab());
}
}
public void resetCacheFor(@NonNull final I_DataEntry_SubTab dataEntrySubGroupRecord)
{
if (dataEntrySubGroupRecord.getDataEntry_Tab_ID() > 0)
{
resetCacheFor(dataEntrySubGroupRecord.getDataEntry_Tab());
}
}
public void resetCacheFor(@NonNull final I_DataEntry_Tab dataEntryGroupRecord)
{
final int windowId = dataEntryGroupRecord.getDataEntry_TargetWindow_ID();
if (windowId > 0)
{
documentDescriptorFactory.invalidateForWindow(WindowId.of(windowId));
final boolean forgetNotSavedDocuments = false;
documentCollection.cacheReset(forgetNotSavedDocuments);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dataentry\interceptor\DataEntryInterceptorUtil.java | 1 |
请完成以下Java代码 | public void setQty (BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
/** Get Quantity.
@return Quantity
*/
public BigDecimal getQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Qty);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Serial No.
@param SerNo
Product Serial Number
*/
public void setSerNo (String SerNo)
{
set_Value (COLUMNNAME_SerNo, SerNo);
}
/** Get Serial No.
@return Product Serial Number
*/
public String getSerNo ()
{
return (String)get_Value(COLUMNNAME_SerNo);
}
/** Set Usable Life - Months.
@param UseLifeMonths
Months of the usable life of the asset
*/
public void setUseLifeMonths (int UseLifeMonths)
{
set_Value (COLUMNNAME_UseLifeMonths, Integer.valueOf(UseLifeMonths));
}
/** Get Usable Life - Months.
@return Months of the usable life of the asset
*/
public int getUseLifeMonths ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeMonths);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Usable Life - Years.
@param UseLifeYears
Years of the usable life of the asset
*/
public void setUseLifeYears (int UseLifeYears)
{
set_Value (COLUMNNAME_UseLifeYears, Integer.valueOf(UseLifeYears));
}
/** Get Usable Life - Years.
@return Years of the usable life of the asset
*/
public int getUseLifeYears ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UseLifeYears);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Use units.
@param UseUnits
Currently used units of the assets
*/
public void setUseUnits (int UseUnits)
{
set_ValueNoCheck (COLUMNNAME_UseUnits, Integer.valueOf(UseUnits));
}
/** Get Use units.
@return Currently used units of the assets
*/
public int getUseUnits () | {
Integer ii = (Integer)get_Value(COLUMNNAME_UseUnits);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
/** Set Version No.
@param VersionNo
Version Number
*/
public void setVersionNo (String VersionNo)
{
set_Value (COLUMNNAME_VersionNo, VersionNo);
}
/** Get Version No.
@return Version Number
*/
public String getVersionNo ()
{
return (String)get_Value(COLUMNNAME_VersionNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset.java | 1 |
请完成以下Java代码 | public void setPhase(int phase) {
this.phase = phase;
}
/**
* Return the phase in which this component will be started and stopped.
*/
@Override
public int getPhase() {
return this.phase;
}
@Override
public void start() {
synchronized (this.lifeCycleMonitor) {
if (!this.running) {
logger.info("Starting...");
doStart();
this.running = true;
logger.info("Started.");
}
}
}
@Override
public void stop() {
synchronized (this.lifeCycleMonitor) {
if (this.running) {
logger.info("Stopping...");
doStop(); | this.running = false;
logger.info("Stopped.");
}
}
}
@Override
public void stop(Runnable callback) {
synchronized (this.lifeCycleMonitor) {
stop();
callback.run();
}
}
@Override
public boolean isRunning() {
return this.running;
}
@Override
public void destroy() {
stop();
}
} | repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\AbstractActivitiSmartLifeCycle.java | 1 |
请完成以下Java代码 | private Regex oneOrMoreTimes() {
return new Regex(this.value + "+");
}
private Regex zeroOrOnce() {
return new Regex(this.value + "?");
}
Pattern compile() {
return Pattern.compile("^" + this.value + "$");
}
@Override
public int length() {
return this.value.length();
}
@Override
public char charAt(int index) {
return this.value.charAt(index);
}
@Override
public CharSequence subSequence(int start, int end) {
return this.value.subSequence(start, end);
}
@Override | public String toString() {
return this.value;
}
private static Regex of(CharSequence... expressions) {
return new Regex(String.join("", expressions));
}
private static Regex oneOf(CharSequence... expressions) {
return new Regex("(?:" + String.join("|", expressions) + ")");
}
private static Regex group(CharSequence... expressions) {
return new Regex("(?:" + String.join("", expressions) + ")");
}
} | repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\core\Regex.java | 1 |
请完成以下Java代码 | public static StringBuilder getInfoDetail(StringBuilder sb, Properties ctx)
{
if (sb == null)
{
sb = new StringBuilder();
}
if (ctx == null)
{
ctx = Env.getCtx();
}
// Envoronment
final CConnection cc = CConnection.get();
sb.append(NL)
.append("=== Environment === ").append(NL)
.append(Adempiere.getCheckSum()).append(NL)
.append(Adempiere.getSummaryAscii()).append(NL)
.append(getLocalHost()).append(NL)
.append(cc.getDbUid() + "@" + cc.getConnectionURL()).append(NL)
.append(cc.getInfo()).append(NL);
// Context
sb.append(NL)
.append("=== Context ===").append(NL);
final String[] context = Env.getEntireContext(ctx);
Arrays.sort(context);
for (int i = 0; i < context.length; i++)
{
sb.append(context[i]).append(NL);
}
// System
sb.append(NL)
.append("=== System ===").append(NL);
final Object[] pp = System.getProperties().keySet().toArray();
Arrays.sort(pp);
for (int i = 0; i < pp.length; i++)
{
final String key = pp[i].toString();
final String value = System.getProperty(key);
sb.append(key).append("=").append(value).append(NL);
}
return sb;
} // getInfoDetail
/**
* Get Database Info
*
* @return host : port : sid
*/
private static String getDatabaseInfo()
{
final StringBuilder sb = new StringBuilder();
final CConnection cc = CConnection.get();
sb.append(cc.getDbHost()).append(" : ")
.append(cc.getDbPort()).append(" / ") | .append(cc.getDbName());
// Connection Manager
return sb.toString();
} // getDatabaseInfo
/**
* Get Localhost
*
* @return local host
*/
private static String getLocalHost()
{
try
{
final InetAddress id = InetAddress.getLocalHost();
return id.toString();
}
catch (final Exception e)
{
logger.error("getLocalHost", e);
}
return "-no local host info -";
} // getLocalHost
/**
* Get translated Message, if DB connection exists
*
* @param msg AD_Message
* @return translated msg if connected
*/
private static String getMsg(final String msg)
{
if (DB.isConnected())
{
return Services.get(IMsgBL.class).translate(Env.getCtx(), msg);
}
return msg;
} // getMsg
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\util\SupportInfo.java | 1 |
请完成以下Spring Boot application配置 | # the db host
spring.data.mongodb.host=localhost
# the connection port (defaults to 27107)
spring.data.mongodb.port=27017
# The database's name
spring.data.mongodb.database=JMeter-Jenkins
# Or this
# spring.data.mongodb.uri=mongodb://localhost/JMeter-Jenkins |
# spring.data.mongodb.username=
# spring.data.mongodb.password=
spring.data.mongodb.repositories.enabled=true | repos\tutorials-master\testing-modules\jmeter\src\main\resources\application.properties | 2 |
请在Spring Boot框架中完成以下Java代码 | public class PPRoutingActivityId implements RepoIdAware
{
public static PPRoutingActivityId ofRepoId(final PPRoutingId routingId, final int repoId)
{
return new PPRoutingActivityId(routingId, repoId);
}
public static PPRoutingActivityId ofRepoId(final int AD_Workflow_ID, final int AD_WF_Node_ID)
{
return new PPRoutingActivityId(PPRoutingId.ofRepoId(AD_Workflow_ID), AD_WF_Node_ID);
}
@Nullable
public static PPRoutingActivityId ofRepoIdOrNull(final int AD_Workflow_ID, final int AD_WF_Node_ID)
{
if (AD_WF_Node_ID <= 0)
{
return null;
}
final PPRoutingId routingId = PPRoutingId.ofRepoIdOrNull(AD_Workflow_ID);
if (routingId == null)
{
return null;
}
return new PPRoutingActivityId(routingId, AD_WF_Node_ID);
} | public static int toRepoId(final PPRoutingActivityId id)
{
return id != null ? id.getRepoId() : -1;
}
PPRoutingId routingId;
int repoId;
private PPRoutingActivityId(@NonNull final PPRoutingId routingId, final int repoId)
{
this.routingId = routingId;
this.repoId = Check.assumeGreaterThanZero(repoId, "AD_WF_Node_ID");
}
@JsonValue
public int toJson()
{
return getRepoId();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\planning\src\main\java\de\metas\material\planning\pporder\PPRoutingActivityId.java | 2 |
请完成以下Java代码 | public void setPicked_HU(final de.metas.handlingunits.model.I_M_HU Picked_HU)
{
set_ValueFromPO(COLUMNNAME_Picked_HU_ID, de.metas.handlingunits.model.I_M_HU.class, Picked_HU);
}
@Override
public void setPicked_HU_ID (final int Picked_HU_ID)
{
if (Picked_HU_ID < 1)
set_ValueNoCheck (COLUMNNAME_Picked_HU_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Picked_HU_ID, Picked_HU_ID);
}
@Override
public int getPicked_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_Picked_HU_ID);
}
@Override
public void setPicked_RenderedQRCode (final @Nullable java.lang.String Picked_RenderedQRCode)
{
set_Value (COLUMNNAME_Picked_RenderedQRCode, Picked_RenderedQRCode);
}
@Override
public java.lang.String getPicked_RenderedQRCode()
{
return get_ValueAsString(COLUMNNAME_Picked_RenderedQRCode);
}
@Override
public de.metas.handlingunits.model.I_M_HU getPickFrom_HU()
{
return get_ValueAsPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class);
}
@Override
public void setPickFrom_HU(final de.metas.handlingunits.model.I_M_HU PickFrom_HU)
{
set_ValueFromPO(COLUMNNAME_PickFrom_HU_ID, de.metas.handlingunits.model.I_M_HU.class, PickFrom_HU);
}
@Override
public void setPickFrom_HU_ID (final int PickFrom_HU_ID)
{
if (PickFrom_HU_ID < 1)
set_Value (COLUMNNAME_PickFrom_HU_ID, null);
else | set_Value (COLUMNNAME_PickFrom_HU_ID, PickFrom_HU_ID);
}
@Override
public int getPickFrom_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_PickFrom_HU_ID);
}
@Override
public void setQtyPicked (final BigDecimal QtyPicked)
{
set_Value (COLUMNNAME_QtyPicked, QtyPicked);
}
@Override
public BigDecimal getQtyPicked()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_Picking_Job_Step_PickedHU.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<Parcel> getParcels() {
if (parcels == null) {
parcels = new ArrayList<Parcel>();
}
return this.parcels;
}
/**
* Gets the value of the productAndServiceData property.
*
* @return
* possible object is
* {@link ProductAndServiceData }
*
*/
public ProductAndServiceData getProductAndServiceData() { | return productAndServiceData;
}
/**
* Sets the value of the productAndServiceData property.
*
* @param value
* allowed object is
* {@link ProductAndServiceData }
*
*/
public void setProductAndServiceData(ProductAndServiceData value) {
this.productAndServiceData = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\ShipmentServiceData.java | 2 |
请完成以下Java代码 | public int removeDocumentPrefixAndConvertToInt()
{
if (isInt())
{
return toInt();
}
String idStr = toJson();
if (idStr.startsWith(DOCUMENT_ID_PREFIX))
{
idStr = idStr.substring(DOCUMENT_ID_PREFIX.length());
}
return Integer.parseInt(idStr);
}
public abstract boolean isNew();
public int toIntOr(final int fallbackValue)
{
return isInt() ? toInt() : fallbackValue;
}
public <T extends RepoIdAware> T toId(@NonNull final IntFunction<T> mapper)
{
return mapper.apply(toInt());
}
private static final class IntDocumentId extends DocumentId
{
private final int idInt;
private IntDocumentId(final int idInt)
{
super();
this.idInt = idInt;
}
@Override
public String toJson()
{
if (idInt == NEW_ID)
{
return NEW_ID_STRING;
}
return String.valueOf(idInt);
}
@Override
public int hashCode()
{
return Objects.hash(idInt);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof IntDocumentId))
{
return false;
}
final IntDocumentId other = (IntDocumentId)obj;
return idInt == other.idInt;
}
@Override
public boolean isInt()
{
return true;
}
@Override
public int toInt()
{
return idInt;
}
@Override
public boolean isNew()
{
return idInt == NEW_ID;
}
@Override
public boolean isComposedKey()
{
return false;
}
@Override
public List<Object> toComposedKeyParts()
{
return ImmutableList.of(idInt);
}
}
private static final class StringDocumentId extends DocumentId
{
private final String idStr;
private StringDocumentId(final String idStr)
{
Check.assumeNotEmpty(idStr, "idStr is not empty");
this.idStr = idStr;
}
@Override
public String toJson()
{
return idStr;
}
@Override
public int hashCode()
{
return Objects.hash(idStr);
} | @Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (!(obj instanceof StringDocumentId))
{
return false;
}
final StringDocumentId other = (StringDocumentId)obj;
return Objects.equals(idStr, other.idStr);
}
@Override
public boolean isInt()
{
return false;
}
@Override
public int toInt()
{
if (isComposedKey())
{
throw new AdempiereException("Composed keys cannot be converted to int: " + this);
}
else
{
throw new AdempiereException("String document IDs cannot be converted to int: " + this);
}
}
@Override
public boolean isNew()
{
return false;
}
@Override
public boolean isComposedKey()
{
return idStr.contains(COMPOSED_KEY_SEPARATOR);
}
@Override
public List<Object> toComposedKeyParts()
{
final ImmutableList.Builder<Object> composedKeyParts = ImmutableList.builder();
COMPOSED_KEY_SPLITTER.split(idStr).forEach(composedKeyParts::add);
return composedKeyParts.build();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\DocumentId.java | 1 |
请完成以下Java代码 | private static void addEntryToFeed(SyndFeed feed) {
SyndEntry entry = new SyndEntryImpl();
entry.setTitle("Entry title");
entry.setLink("http://www.somelink.com/entry1");
addDescriptionToEntry(entry);
addCategoryToEntry(entry);
feed.setEntries(Arrays.asList(entry));
}
private static void addDescriptionToEntry(SyndEntry entry) {
SyndContent description = new SyndContentImpl();
description.setType("text/html");
description.setValue("First entry");
entry.setDescription(description);
}
private static void addCategoryToEntry(SyndEntry entry) { | List<SyndCategory> categories = new ArrayList<>();
SyndCategory category = new SyndCategoryImpl();
category.setName("Sophisticated category");
categories.add(category);
entry.setCategories(categories);
}
private static void publishFeed(SyndFeed feed) throws IOException, FeedException {
Writer writer = new FileWriter("xyz.txt");
SyndFeedOutput syndFeedOutput = new SyndFeedOutput();
syndFeedOutput.output(feed, writer);
writer.close();
}
private static SyndFeed readFeed() throws IOException, FeedException, URISyntaxException {
URL feedSource = new URI("http://rssblog.whatisrss.com/feed/").toURL();
SyndFeedInput input = new SyndFeedInput();
return input.build(new XmlReader(feedSource));
}
} | repos\tutorials-master\web-modules\rome\src\main\java\com\baeldung\rome\RSSRomeExample.java | 1 |
请完成以下Java代码 | public boolean isCopy() {
if (copy == null) {
return false;
} else {
return copy;
}
}
/**
* Sets the value of the copy property.
*
* @param value
* allowed object is
* {@link Boolean }
*
*/
public void setCopy(Boolean value) {
this.copy = value;
}
/** | * Gets the value of the responseTimestamp property.
*
*/
public int getResponseTimestamp() {
return responseTimestamp;
}
/**
* Sets the value of the responseTimestamp property.
*
*/
public void setResponseTimestamp(int value) {
this.responseTimestamp = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\response\PayloadType.java | 1 |
请完成以下Java代码 | private static Method getRunAsSubjectMethod() {
if (getRunAsSubject == null) {
getRunAsSubject = getMethod("com.ibm.websphere.security.auth.WSSubject", "getRunAsSubject",
new String[] {});
}
return getRunAsSubject;
}
private static Method getGroupsForUserMethod() {
if (getGroupsForUser == null) {
getGroupsForUser = getMethod("com.ibm.websphere.security.UserRegistry", "getGroupsForUser",
new String[] { "java.lang.String" });
}
return getGroupsForUser;
}
private static Method getSecurityNameMethod() {
if (getSecurityName == null) {
getSecurityName = getMethod("com.ibm.websphere.security.cred.WSCredential", "getSecurityName",
new String[] {});
}
return getSecurityName;
}
private static Method getNarrowMethod() { | if (narrow == null) {
narrow = getMethod(PORTABLE_REMOTE_OBJECT_CLASSNAME, "narrow",
new String[] { Object.class.getName(), Class.class.getName() });
}
return narrow;
}
// SEC-803
private static Class<?> getWSCredentialClass() {
if (wsCredentialClass == null) {
wsCredentialClass = getClass("com.ibm.websphere.security.cred.WSCredential");
}
return wsCredentialClass;
}
private static Class<?> getClass(String className) {
try {
return Class.forName(className);
}
catch (ClassNotFoundException ex) {
logger.error("Required class " + className + " not found");
throw new RuntimeException("Required class " + className + " not found", ex);
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\preauth\websphere\DefaultWASUsernameAndGroupsExtractor.java | 1 |
请完成以下Java代码 | public TreeModel getTreeModel() {
return this.model;
}
/**
* Sets the specified tree model. The current cheking is cleared.
*/
@Override
public void setTreeModel(TreeModel newModel) {
TreeModel oldModel = this.model;
if (oldModel != null) {
oldModel.removeTreeModelListener(this.propagateCheckingListener);
}
this.model = newModel;
if (newModel != null) {
newModel.addTreeModelListener(this.propagateCheckingListener);
}
clearChecking();
}
/**
* Return a string that describes the tree model including the values of
* checking, enabling, greying.
*/
@Override
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 ProcessInstance startProcessInstance(ProcessInstanceBuilderImpl processInstanceBuilder) {
if (processInstanceBuilder.getProcessDefinitionId() != null || processInstanceBuilder.getProcessDefinitionKey() != null) {
return commandExecutor.execute(new StartProcessInstanceCmd<ProcessInstance>(processInstanceBuilder));
} else if (processInstanceBuilder.getMessageName() != null) {
return commandExecutor.execute(new StartProcessInstanceByMessageCmd(processInstanceBuilder));
} else {
throw new FlowableIllegalArgumentException("No processDefinitionId, processDefinitionKey nor messageName provided");
}
}
public ProcessInstance startProcessInstanceAsync(ProcessInstanceBuilderImpl processInstanceBuilder) {
if (processInstanceBuilder.getProcessDefinitionId() != null || processInstanceBuilder.getProcessDefinitionKey() != null) {
return (ProcessInstance) commandExecutor.execute(new StartProcessInstanceAsyncCmd(processInstanceBuilder));
} else {
throw new FlowableIllegalArgumentException("No processDefinitionId, processDefinitionKey provided");
}
}
public EventSubscription registerProcessInstanceStartEventSubscription(ProcessInstanceStartEventSubscriptionBuilderImpl builder) { | return commandExecutor.execute(new RegisterProcessInstanceStartEventSubscriptionCmd(builder));
}
public void migrateProcessInstanceStartEventSubscriptionsToProcessDefinitionVersion(ProcessInstanceStartEventSubscriptionModificationBuilderImpl builder) {
commandExecutor.execute(new ModifyProcessInstanceStartEventSubscriptionCmd(builder));
}
public void deleteProcessInstanceStartEventSubscriptions(ProcessInstanceStartEventSubscriptionDeletionBuilderImpl builder) {
commandExecutor.execute(new DeleteProcessInstanceStartEventSubscriptionCmd(builder));
}
public void changeActivityState(ChangeActivityStateBuilderImpl changeActivityStateBuilder) {
commandExecutor.execute(new ChangeActivityStateCmd(changeActivityStateBuilder));
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\RuntimeServiceImpl.java | 1 |
请完成以下Java代码 | private OrderResponse createOrderResponse(final JpaOrder jpaOrder)
{
return OrderResponse.builder()
.bpartnerId(BPartnerId.of(jpaOrder.getMfBpartnerId(), jpaOrder.getMfBpartnerLocationId()))
.orderId(Id.of(jpaOrder.getDocumentNo()))
.supportId(SupportIDType.of(jpaOrder.getSupportId()))
.nightOperation(jpaOrder.getNightOperation())
.orderPackages(jpaOrder.getOrderPackages().stream()
.map(this::createOrderResponsePackage)
.collect(ImmutableList.toImmutableList()))
.build();
}
private OrderResponsePackage createOrderResponsePackage(final JpaOrderPackage jpaOrderPackage)
{
return OrderResponsePackage.builder()
.id(Id.of(jpaOrderPackage.getDocumentNo()))
.orderType(jpaOrderPackage.getOrderType())
.orderIdentification(jpaOrderPackage.getOrderIdentification())
.supportId(SupportIDType.of(jpaOrderPackage.getSupportId()))
.packingMaterialId(jpaOrderPackage.getPackingMaterialId())
.items(jpaOrderPackage.getItems().stream()
.map(this::createOrderResponsePackageItem)
.collect(ImmutableList.toImmutableList()))
.build();
}
private OrderResponsePackageItem createOrderResponsePackageItem(final JpaOrderPackageItem jpaOrderPackageItem)
{
return OrderResponsePackageItem.builder()
.requestId(OrderCreateRequestPackageItemId.of(jpaOrderPackageItem.getUuid()))
.pzn(PZN.of(jpaOrderPackageItem.getPzn()))
.qty(Quantity.of(jpaOrderPackageItem.getQty()))
.deliverySpecifications(jpaOrderPackageItem.getDeliverySpecifications())
.build();
}
public OrderStatusResponse getOrderStatus(@NonNull final Id orderId, @NonNull final BPartnerId bpartnerId)
{
final JpaOrder jpaOrder = getJpaOrder(orderId, bpartnerId); | return createOrderStatusResponse(jpaOrder);
}
private JpaOrder getJpaOrder(@NonNull final Id orderId, @NonNull final BPartnerId bpartnerId)
{
final JpaOrder jpaOrder = jpaOrdersRepo.findByDocumentNoAndMfBpartnerId(orderId.getValueAsString(), bpartnerId.getBpartnerId());
if (jpaOrder == null)
{
throw new RuntimeException("No order found for id='" + orderId + "' and bpartnerId='" + bpartnerId + "'");
}
return jpaOrder;
}
private OrderStatusResponse createOrderStatusResponse(final JpaOrder jpaOrder)
{
return OrderStatusResponse.builder()
.orderId(Id.of(jpaOrder.getDocumentNo()))
.supportId(SupportIDType.of(jpaOrder.getSupportId()))
.orderStatus(jpaOrder.getOrderStatus())
.orderPackages(jpaOrder.getOrderPackages().stream()
.map(this::createOrderResponsePackage)
.collect(ImmutableList.toImmutableList()))
.build();
}
public List<OrderResponse> getOrders()
{
return jpaOrdersRepo.findAll()
.stream()
.map(this::createOrderResponse)
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\order\OrderService.java | 1 |
请完成以下Java代码 | public void updateProcessDefinitionCache(ParsedDeployment parsedDeployment) {
final ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration();
DeploymentCache<ProcessDefinitionCacheEntry> processDefinitionCache = processEngineConfiguration.getDeploymentManager().getProcessDefinitionCache();
for (ProcessDefinitionEntity processDefinition : parsedDeployment.getAllProcessDefinitions()) {
BpmnModel bpmnModel = parsedDeployment.getBpmnModelForProcessDefinition(processDefinition);
Process process = parsedDeployment.getProcessModelForProcessDefinition(processDefinition);
ProcessDefinitionCacheEntry cacheEntry = new ProcessDefinitionCacheEntry(processDefinition, bpmnModel, process);
processDefinitionCache.add(processDefinition.getId(), cacheEntry);
}
}
protected void addDefinitionInfoToCache(ProcessDefinitionEntity processDefinition,
ProcessEngineConfigurationImpl processEngineConfiguration, CommandContext commandContext) {
if (!processEngineConfiguration.isEnableProcessDefinitionInfoCache()) {
return;
}
DeploymentManager deploymentManager = processEngineConfiguration.getDeploymentManager();
ProcessDefinitionInfoEntityManager definitionInfoEntityManager = CommandContextUtil.getProcessDefinitionInfoEntityManager(commandContext);
ObjectMapper objectMapper = CommandContextUtil.getProcessEngineConfiguration(commandContext).getObjectMapper();
ProcessDefinitionInfoEntity definitionInfoEntity = definitionInfoEntityManager.findProcessDefinitionInfoByProcessDefinitionId(processDefinition.getId());
ObjectNode infoNode = null;
if (definitionInfoEntity != null && definitionInfoEntity.getInfoJsonId() != null) {
byte[] infoBytes = definitionInfoEntityManager.findInfoJsonById(definitionInfoEntity.getInfoJsonId());
if (infoBytes != null) {
try {
infoNode = (ObjectNode) objectMapper.readTree(infoBytes);
} catch (Exception e) {
throw new FlowableException("Error deserializing json info for process definition " + processDefinition.getId(), e); | }
}
}
ProcessDefinitionInfoCacheObject definitionCacheObject = new ProcessDefinitionInfoCacheObject();
if (definitionInfoEntity == null) {
definitionCacheObject.setRevision(0);
} else {
definitionCacheObject.setId(definitionInfoEntity.getId());
definitionCacheObject.setRevision(definitionInfoEntity.getRevision());
}
if (infoNode == null) {
infoNode = objectMapper.createObjectNode();
}
definitionCacheObject.setInfoNode(infoNode);
deploymentManager.getProcessDefinitionInfoCache().add(processDefinition.getId(), definitionCacheObject);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\bpmn\deployer\CachingAndArtifactsManager.java | 1 |
请完成以下Java代码 | public int getTriggerPoolFastMax() {
if (triggerPoolFastMax < 200) {
return 200;
}
return triggerPoolFastMax;
}
public int getTriggerPoolSlowMax() {
if (triggerPoolSlowMax < 100) {
return 100;
}
return triggerPoolSlowMax;
}
public int getLogretentiondays() {
if (logretentiondays < 7) {
return -1; // Limit greater than or equal to 7, otherwise close
}
return logretentiondays;
}
public XxlJobLogDao getXxlJobLogDao() {
return xxlJobLogDao;
}
public XxlJobInfoDao getXxlJobInfoDao() {
return xxlJobInfoDao;
}
public XxlJobRegistryDao getXxlJobRegistryDao() {
return xxlJobRegistryDao;
}
public XxlJobGroupDao getXxlJobGroupDao() { | return xxlJobGroupDao;
}
public XxlJobLogReportDao getXxlJobLogReportDao() {
return xxlJobLogReportDao;
}
public JavaMailSender getMailSender() {
return mailSender;
}
public DataSource getDataSource() {
return dataSource;
}
public JobAlarmer getJobAlarmer() {
return jobAlarmer;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\conf\XxlJobAdminConfig.java | 1 |
请完成以下Java代码 | public int getWarinigCount() {
return warningCount;
}
@Override
public void write(StringWriter writer, ValidationResultFormatter formatter) {
for (Entry<ModelElementInstance, List<ValidationResult>> entry : collectedResults.entrySet()) {
ModelElementInstance element = entry.getKey();
List<ValidationResult> results = entry.getValue();
formatter.formatElement(writer, element);
for (ValidationResult result : results) {
formatter.formatResult(writer, result);
}
}
}
@Override
public void write(StringWriter writer, ValidationResultFormatter formatter, int maxSize) {
int printedCount = 0;
int previousLength = 0;
for (var entry : collectedResults.entrySet()) {
var element = entry.getKey();
var results = entry.getValue();
formatter.formatElement(writer, element);
for (var result : results) {
formatter.formatResult(writer, result); | // Size and Length are not necessarily the same, depending on the encoding of the string.
int currentSize = writer.getBuffer().toString().getBytes().length;
int currentLength = writer.getBuffer().length();
if (!canAccommodateResult(maxSize, currentSize, printedCount, formatter)) {
writer.getBuffer().setLength(previousLength);
int remaining = errorCount + warningCount - printedCount;
formatter.formatSuffixWithOmittedResultsCount(writer, remaining);
return;
}
printedCount++;
previousLength = currentLength;
}
}
}
private boolean canAccommodateResult(
int maxSize, int currentSize, int printedCount, ValidationResultFormatter formatter) {
boolean isLastItemToPrint = printedCount == errorCount + warningCount - 1;
if (isLastItemToPrint && currentSize <= maxSize) {
return true;
}
int remaining = errorCount + warningCount - printedCount;
int suffixLength = formatter.getFormattedSuffixWithOmittedResultsSize(remaining);
return currentSize + suffixLength <= maxSize;
}
@Override
public Map<ModelElementInstance, List<ValidationResult>> getResults() {
return collectedResults;
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\validation\ModelValidationResultsImpl.java | 1 |
请完成以下Java代码 | public java.sql.Timestamp getDateFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateFrom);
}
/** Set Freigegeben.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
} | /** Get Freigegeben.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_CreditLimit.java | 1 |
请完成以下Java代码 | private AlbertaOrderId createAlbertaOrderHeader(@NonNull final AlbertaOrderInfo request)
{
final I_Alberta_Order albertaOrder = InterfaceWrapperHelper.newInstance(I_Alberta_Order.class);
albertaOrder.setAD_Org_ID(request.getOrgId().getRepoId());
albertaOrder.setAnnotation(request.getAnnotation());
albertaOrder.setDeliveryInfo(request.getDeliveryInformation());
albertaOrder.setDeliveryNote(request.getDeliveryNote());
if (request.getDoctorBPartnerId() != null)
{
albertaOrder.setC_Doctor_BPartner_ID(request.getDoctorBPartnerId().getRepoId());
}
if (request.getPharmacyBPartnerId() != null)
{
albertaOrder.setC_Pharmacy_BPartner_ID(request.getPharmacyBPartnerId().getRepoId());
} | albertaOrder.setExternalId(request.getExternalId());
albertaOrder.setRootId(request.getRootId());
albertaOrder.setCreationDate(TimeUtil.asTimestamp(request.getCreationDate()));
albertaOrder.setStartDate(TimeUtil.asTimestamp(request.getStartDate()));
albertaOrder.setEndDate(TimeUtil.asTimestamp(request.getEndDate()));
albertaOrder.setDayOfDelivery(request.getDayOfDelivery());
albertaOrder.setNextDelivery(TimeUtil.asTimestamp(request.getNextDelivery()));
albertaOrder.setIsInitialCare(Boolean.TRUE.equals(request.getIsInitialCare()));
albertaOrder.setIsSeriesOrder(Boolean.TRUE.equals(request.getIsSeriesOrder()));
albertaOrder.setIsArchived(Boolean.TRUE.equals(request.getIsArchived()));
albertaOrder.setExternallyUpdatedAt(TimeUtil.asTimestamp(request.getUpdated()));
saveRecord(albertaOrder);
return AlbertaOrderId.ofRepoId(albertaOrder.getAlberta_Order_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java\de\metas\vertical\healthcare\alberta\order\dao\AlbertaOrderDAO.java | 1 |
请完成以下Java代码 | private Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain,
PrincipalAndSession principalAndSession) {
return Mono.fromRunnable(() -> addExchangeOnCommit(exchange, principalAndSession)).and(chain.filter(exchange));
}
private void addExchangeOnCommit(ServerWebExchange exchange, PrincipalAndSession principalAndSession) {
RecordableServerHttpRequest sourceRequest = new RecordableServerHttpRequest(exchange.getRequest());
HttpExchange.Started startedHttpExchange = HttpExchange.start(sourceRequest);
exchange.getResponse().beforeCommit(() -> {
RecordableServerHttpResponse sourceResponse = new RecordableServerHttpResponse(exchange.getResponse());
HttpExchange finishedExchange = startedHttpExchange.finish(sourceResponse,
principalAndSession::getPrincipal, principalAndSession::getSessionId, this.includes);
this.repository.add(finishedExchange);
return Mono.empty();
});
}
/**
* A {@link Principal} and {@link WebSession}.
*/
private static class PrincipalAndSession { | private final @Nullable Principal principal;
private final @Nullable WebSession session;
PrincipalAndSession(Object[] zipped) {
this.principal = (zipped[0] != NONE) ? (Principal) zipped[0] : null;
this.session = (zipped[1] != NONE) ? (WebSession) zipped[1] : null;
}
@Nullable Principal getPrincipal() {
return this.principal;
}
@Nullable String getSessionId() {
return (this.session != null && this.session.isStarted()) ? this.session.getId() : null;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-webflux\src\main\java\org\springframework\boot\webflux\actuate\web\exchanges\HttpExchangesWebFilter.java | 1 |
请完成以下Java代码 | public void onAfterWindowSave_AssertNoCyclesInWindowCustomizationsChain(@NonNull final I_AD_Window window)
{
customizedWindowInfoMapRepository.assertNoCycles(AdWindowId.ofRepoId(window.getAD_Window_ID()));
}
private void updateWindowFromElement(final I_AD_Window window)
{
// do not copy translations from element to window
if (!IElementTranslationBL.DYNATTR_AD_Window_UpdateTranslations.getValue(window, true))
{
return;
}
final I_AD_Element windowElement = adElementDAO.getById(window.getAD_Element_ID());
if (windowElement == null)
{
// nothing to do. It was not yet set
return;
}
window.setName(windowElement.getName());
window.setDescription(windowElement.getDescription());
window.setHelp(windowElement.getHelp());
}
private void updateTranslationsForElement(final I_AD_Window window)
{
final AdElementId windowElementId = AdElementId.ofRepoIdOrNull(window.getAD_Element_ID());
if (windowElementId == null)
{
// nothing to do. It was not yet set
return;
}
elementTranslationBL.updateWindowTranslationsFromElement(windowElementId); | }
private void recreateElementLinkForWindow(final I_AD_Window window)
{
final AdWindowId adWindowId = AdWindowId.ofRepoIdOrNull(window.getAD_Window_ID());
if (adWindowId != null)
{
final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class);
elementLinksService.recreateADElementLinkForWindowId(adWindowId);
}
}
@ModelChange(timings = { ModelValidator.TYPE_BEFORE_DELETE })
public void onBeforeWindowDelete(final I_AD_Window window)
{
final AdWindowId adWindowId = AdWindowId.ofRepoId(window.getAD_Window_ID());
final IElementLinkBL elementLinksService = Services.get(IElementLinkBL.class);
elementLinksService.deleteExistingADElementLinkForWindowId(adWindowId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\window\model\interceptor\AD_Window.java | 1 |
请完成以下Java代码 | public class SmartEnvironmentAccessor implements PropertyAccessor {
/**
* Factory method used to construct a new instance of {@link SmartEnvironmentAccessor}.
*
* @return a new instance of {@link SmartEnvironmentAccessor}.
*/
public static @NonNull SmartEnvironmentAccessor create() {
return new SmartEnvironmentAccessor();
}
/**
* @inheritDoc
*/
@Nullable @Override
public Class<?>[] getSpecificTargetClasses() {
return new Class[] { Environment.class, EnvironmentCapable.class };
}
private Optional<Environment> asEnvironment(@Nullable Object target) {
Environment environment = target instanceof Environment ? (Environment) target
: target instanceof EnvironmentCapable ? ((EnvironmentCapable) target).getEnvironment()
: null;
return Optional.ofNullable(environment);
}
/**
* @inheritDoc
*/
@Override
public boolean canRead(EvaluationContext context, @Nullable Object target, String name) {
return asEnvironment(target)
.filter(environment -> environment.containsProperty(name))
.isPresent();
}
/**
* @inheritDoc
*/
@Override
public TypedValue read(EvaluationContext context, @Nullable Object target, String name) {
String value = asEnvironment(target)
.map(environment -> environment.getProperty(name)) | .orElse(null);
return new TypedValue(value);
}
/**
* @inheritDoc
* @return {@literal false}.
*/
@Override
public boolean canWrite(EvaluationContext context, @Nullable Object target, String name) {
return false;
}
/**
* @inheritDoc
*/
@Override
public void write(EvaluationContext context, @Nullable Object target, String name, @Nullable Object newValue) { }
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\expression\SmartEnvironmentAccessor.java | 1 |
请完成以下Java代码 | public void addCandidateUser(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink, cmmnEngineConfiguration);
}
@Override
public void addCandidateUsers(Task task, List<IdentityLink> candidateUsers) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
for (IdentityLink identityLink : candidateUsers) {
identityLinks.add((IdentityLinkEntity) identityLink);
}
IdentityLinkUtil.handleTaskIdentityLinkAdditions((TaskEntity) task, identityLinks, cmmnEngineConfiguration);
}
@Override
public void addCandidateGroup(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink, cmmnEngineConfiguration);
}
@Override
public void addCandidateGroups(Task task, List<IdentityLink> candidateGroups) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
for (IdentityLink identityLink : candidateGroups) {
identityLinks.add((IdentityLinkEntity) identityLink);
}
IdentityLinkUtil.handleTaskIdentityLinkAdditions((TaskEntity) task, identityLinks, cmmnEngineConfiguration);
} | @Override
public void addUserIdentityLink(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink, cmmnEngineConfiguration);
}
@Override
public void addGroupIdentityLink(Task task, IdentityLink identityLink) {
IdentityLinkUtil.handleTaskIdentityLinkAddition((TaskEntity) task, (IdentityLinkEntity) identityLink, cmmnEngineConfiguration);
}
@Override
public void deleteUserIdentityLink(Task task, IdentityLink identityLink) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
identityLinks.add((IdentityLinkEntity) identityLink);
IdentityLinkUtil.handleTaskIdentityLinkDeletions((TaskEntity) task, identityLinks, true, cmmnEngineConfiguration);
}
@Override
public void deleteGroupIdentityLink(Task task, IdentityLink identityLink) {
List<IdentityLinkEntity> identityLinks = new ArrayList<>();
identityLinks.add((IdentityLinkEntity) identityLink);
IdentityLinkUtil.handleTaskIdentityLinkDeletions((TaskEntity) task, identityLinks, true, cmmnEngineConfiguration);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cfg\DefaultTaskAssignmentManager.java | 1 |
请完成以下Java代码 | public SuspendedJobEntityManager getSuspendedJobEntityManager() {
return getSession(SuspendedJobEntityManager.class);
}
public DeadLetterJobEntityManager getDeadLetterJobEntityManager() {
return getSession(DeadLetterJobEntityManager.class);
}
public AttachmentEntityManager getAttachmentEntityManager() {
return getSession(AttachmentEntityManager.class);
}
public TableDataManager getTableDataManager() {
return getSession(TableDataManager.class);
}
public CommentEntityManager getCommentEntityManager() {
return getSession(CommentEntityManager.class);
}
public PropertyEntityManager getPropertyEntityManager() {
return getSession(PropertyEntityManager.class);
}
public EventSubscriptionEntityManager getEventSubscriptionEntityManager() {
return getSession(EventSubscriptionEntityManager.class);
}
public Map<Class<?>, SessionFactory> getSessionFactories() {
return sessionFactories;
}
public HistoryManager getHistoryManager() {
return getSession(HistoryManager.class);
}
// getters and setters //////////////////////////////////////////////////////
public TransactionContext getTransactionContext() {
return transactionContext;
} | public Command<?> getCommand() {
return command;
}
public Map<Class<?>, Session> getSessions() {
return sessions;
}
public Throwable getException() {
return exception;
}
public FailedJobCommandFactory getFailedJobCommandFactory() {
return failedJobCommandFactory;
}
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public FlowableEventDispatcher getEventDispatcher() {
return processEngineConfiguration.getEventDispatcher();
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\interceptor\CommandContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class userDao {
@Autowired
private SessionFactory sessionFactory;
public void setSessionFactory(SessionFactory sf) {
this.sessionFactory = sf;
}
@Transactional
public List<User> getAllUser() {
Session session = this.sessionFactory.getCurrentSession();
List<User> userList = session.createQuery("from CUSTOMER").list();
return userList;
}
@Transactional
public User saveUser(User user) {
this.sessionFactory.getCurrentSession().saveOrUpdate(user);
System.out.println("User added" + user.getId());
return user;
}
// public User checkLogin() {
// this.sessionFactory.getCurrentSession().
// }
@Transactional
public User getUser(String username,String password) {
Query query = sessionFactory.getCurrentSession().createQuery("from CUSTOMER where username = :username");
query.setParameter("username",username);
try {
User user = (User) query.getSingleResult();
System.out.println(user.getPassword());
if(password.equals(user.getPassword())) {
return user;
}else {
return new User();
}
}catch(Exception e){
System.out.println(e.getMessage());
User user = new User();
return user;
} | }
@Transactional
public boolean userExists(String username) {
Query query = sessionFactory.getCurrentSession().createQuery("from CUSTOMER where username = :username");
query.setParameter("username",username);
return !query.getResultList().isEmpty();
}
@Transactional
public User getUserByUsername(String username) {
Query<User> query = sessionFactory.getCurrentSession().createQuery("from User where username = :username", User.class);
query.setParameter("username", username);
try {
return query.getSingleResult();
} catch (Exception e) {
System.out.println(e.getMessage());
return null;
}
}
} | repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\dao\userDao.java | 2 |
请完成以下Java代码 | public Optional<Quantity> getWeight()
{
final IWeightable weightable = Weightables.wrap(getAttributeStorage());
if (weightable == null)
{
return Optional.empty();
}
final BigDecimal weightNetOrNull = weightable.getWeightNetOrNull();
if (weightNetOrNull == null)
{
return Optional.empty();
}
return Optional.of(Quantity.of(weightNetOrNull, weightable.getWeightNetUOM()));
}
/**
* The M_QualityNote linked with the HUReceiptLine
*
* @return
*/
public I_M_QualityNote getQualityNote() | {
final IAttributeStorage attributeStorage = getAttributeStorage();
if (!attributeStorage.hasAttribute(attr_QualityNotice))
{
return null;
}
// if the quality notice is set, then take it's name. It must have a qualityDiscount% to be set
final Object qualityNoticeCode = attributeStorage.getValue(attr_QualityNotice);
if (qualityNoticeCode == null)
{
return null;
}
return Services.get(IQualityNoteDAO.class).retrieveQualityNoteForValue(huContext.getCtx(), qualityNoticeCode.toString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\HUReceiptLinePartAttributes.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AlarmAssignmentTriggerProcessor implements NotificationRuleTriggerProcessor<AlarmAssignmentTrigger, AlarmAssignmentNotificationRuleTriggerConfig> {
@Override
public boolean matchesFilter(AlarmAssignmentTrigger trigger, AlarmAssignmentNotificationRuleTriggerConfig triggerConfig) {
Action action = trigger.getActionType() == ActionType.ALARM_ASSIGNED ? Action.ASSIGNED : Action.UNASSIGNED;
if (!triggerConfig.getNotifyOn().contains(action)) {
return false;
}
AlarmInfo alarmInfo = trigger.getAlarmInfo();
return emptyOrContains(triggerConfig.getAlarmTypes(), alarmInfo.getType()) &&
emptyOrContains(triggerConfig.getAlarmSeverities(), alarmInfo.getSeverity()) &&
(isEmpty(triggerConfig.getAlarmStatuses()) || AlarmStatusFilter.from(triggerConfig.getAlarmStatuses()).matches(alarmInfo));
}
@Override
public RuleOriginatedNotificationInfo constructNotificationInfo(AlarmAssignmentTrigger trigger) {
AlarmInfo alarmInfo = trigger.getAlarmInfo();
AlarmAssignee assignee = alarmInfo.getAssignee();
return AlarmAssignmentNotificationInfo.builder()
.action(trigger.getActionType() == ActionType.ALARM_ASSIGNED ? "assigned" : "unassigned")
.assigneeFirstName(assignee != null ? assignee.getFirstName() : null)
.assigneeLastName(assignee != null ? assignee.getLastName() : null) | .assigneeEmail(assignee != null ? assignee.getEmail() : null)
.assigneeId(assignee != null ? assignee.getId() : null)
.userEmail(trigger.getUser().getEmail())
.userFirstName(trigger.getUser().getFirstName())
.userLastName(trigger.getUser().getLastName())
.alarmId(alarmInfo.getUuidId())
.alarmType(alarmInfo.getType())
.alarmOriginator(alarmInfo.getOriginator())
.alarmOriginatorName(alarmInfo.getOriginatorName())
.alarmOriginatorLabel(alarmInfo.getOriginatorLabel())
.alarmSeverity(alarmInfo.getSeverity())
.alarmStatus(alarmInfo.getStatus())
.alarmCustomerId(alarmInfo.getCustomerId())
.dashboardId(alarmInfo.getDashboardId())
.build();
}
@Override
public NotificationRuleTriggerType getTriggerType() {
return NotificationRuleTriggerType.ALARM_ASSIGNMENT;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\AlarmAssignmentTriggerProcessor.java | 2 |
请完成以下Java代码 | public class TriggerCmd extends NeedsActiveExecutionCmd<Object> {
private static final long serialVersionUID = 1L;
protected Map<String, Object> processVariables;
protected Map<String, Object> transientVariables;
protected boolean async;
public TriggerCmd(String executionId, Map<String, Object> processVariables) {
super(executionId);
this.processVariables = processVariables;
}
public TriggerCmd(String executionId, Map<String, Object> processVariables, boolean async) {
super(executionId);
this.processVariables = processVariables;
this.async = async;
}
public TriggerCmd(String executionId, Map<String, Object> processVariables, Map<String, Object> transientVariables) {
this(executionId, processVariables);
this.transientVariables = transientVariables;
}
@Override
protected Object execute(CommandContext commandContext, ExecutionEntity execution) {
if (Flowable5Util.isFlowable5ProcessDefinitionId(commandContext, execution.getProcessDefinitionId())) {
Flowable5CompatibilityHandler compatibilityHandler = Flowable5Util.getFlowable5CompatibilityHandler();
compatibilityHandler.trigger(executionId, processVariables, transientVariables);
return null;
}
if (processVariables != null) {
execution.setVariables(processVariables);
} | if (!async) {
if (transientVariables != null) {
execution.setTransientVariables(transientVariables);
}
ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext);
processEngineConfiguration.getEventDispatcher().dispatchEvent(
FlowableEventBuilder.createSignalEvent(FlowableEngineEventType.ACTIVITY_SIGNALED, execution.getCurrentActivityId(), null,
null, execution.getId(), execution.getProcessInstanceId(), execution.getProcessDefinitionId()),
processEngineConfiguration.getEngineCfgKey());
CommandContextUtil.getAgenda(commandContext).planTriggerExecutionOperation(execution);
} else {
CommandContextUtil.getAgenda(commandContext).planAsyncTriggerExecutionOperation(execution);
}
return null;
}
@Override
protected String getSuspendedExceptionMessagePrefix() {
return "Cannot trigger";
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\TriggerCmd.java | 1 |
请完成以下Java代码 | public void setExternalSystemValue (final String ExternalSystemValue)
{
set_Value (COLUMNNAME_ExternalSystemValue, ExternalSystemValue);
}
@Override
public String getExternalSystemValue()
{
return get_ValueAsString(COLUMNNAME_ExternalSystemValue);
}
@Override
public void setIsPluFileExportAuditEnabled (final boolean IsPluFileExportAuditEnabled)
{
set_Value (COLUMNNAME_IsPluFileExportAuditEnabled, IsPluFileExportAuditEnabled);
}
@Override
public boolean isPluFileExportAuditEnabled()
{
return get_ValueAsBoolean(COLUMNNAME_IsPluFileExportAuditEnabled);
}
/**
* PluFileDestination AD_Reference_ID=541911
* Reference name: PluFileDestination
*/
public static final int PLUFILEDESTINATION_AD_Reference_ID=541911;
/** Disk = 2DSK */
public static final String PLUFILEDESTINATION_Disk = "2DSK";
/** TCP = 1TCP */
public static final String PLUFILEDESTINATION_TCP = "1TCP";
@Override
public void setPluFileDestination (final java.lang.String PluFileDestination)
{
set_Value (COLUMNNAME_PluFileDestination, PluFileDestination);
}
@Override
public java.lang.String getPluFileDestination()
{
return get_ValueAsString(COLUMNNAME_PluFileDestination);
}
@Override
public void setPluFileLocalFolder (final @Nullable java.lang.String PluFileLocalFolder)
{
set_Value (COLUMNNAME_PluFileLocalFolder, PluFileLocalFolder); | }
@Override
public java.lang.String getPluFileLocalFolder()
{
return get_ValueAsString(COLUMNNAME_PluFileLocalFolder);
}
@Override
public void setProduct_BaseFolderName (final String Product_BaseFolderName)
{
set_Value (COLUMNNAME_Product_BaseFolderName, Product_BaseFolderName);
}
@Override
public String getProduct_BaseFolderName()
{
return get_ValueAsString(COLUMNNAME_Product_BaseFolderName);
}
@Override
public void setTCP_Host (final String TCP_Host)
{
set_Value (COLUMNNAME_TCP_Host, TCP_Host);
}
@Override
public String getTCP_Host()
{
return get_ValueAsString(COLUMNNAME_TCP_Host);
}
@Override
public void setTCP_PortNumber (final int TCP_PortNumber)
{
set_Value (COLUMNNAME_TCP_PortNumber, TCP_PortNumber);
}
@Override
public int getTCP_PortNumber()
{
return get_ValueAsInt(COLUMNNAME_TCP_PortNumber);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl.java | 1 |
请完成以下Java代码 | public void init(JavaType baseType) {
this.delegate.init(baseType);
}
@Override
public String idFromValue(Object value) {
return this.delegate.idFromValue(value);
}
@Override
public String idFromValueAndType(Object value, Class<?> suggestedType) {
return this.delegate.idFromValueAndType(value, suggestedType);
}
@Override
public String idFromBaseType() {
return this.delegate.idFromBaseType();
}
@Override
public JavaType typeFromId(DatabindContext context, String id) throws IOException {
DeserializationConfig config = (DeserializationConfig) context.getConfig();
JavaType result = this.delegate.typeFromId(context, id);
String className = result.getRawClass().getName();
if (isInAllowlist(className)) {
return result;
}
boolean isExplicitMixin = config.findMixInClassFor(result.getRawClass()) != null;
if (isExplicitMixin) {
return result;
}
JacksonAnnotation jacksonAnnotation = AnnotationUtils.findAnnotation(result.getRawClass(),
JacksonAnnotation.class);
if (jacksonAnnotation != null) {
return result;
}
throw new IllegalArgumentException("The class with " + id + " and name of " + className
+ " is not in the allowlist. "
+ "If you believe this class is safe to deserialize, please provide an explicit mapping using Jackson annotations or by providing a Mixin. "
+ "If the serialization is only done by a trusted source, you can also enable default typing. "
+ "See https://github.com/spring-projects/spring-security/issues/4370 for details");
} | private boolean isInAllowlist(String id) {
return ALLOWLIST_CLASS_NAMES.contains(id);
}
@Override
public String getDescForKnownTypeIds() {
return this.delegate.getDescForKnownTypeIds();
}
@Override
public JsonTypeInfo.Id getMechanism() {
return this.delegate.getMechanism();
}
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\jackson2\SecurityJackson2Modules.java | 1 |
请完成以下Java代码 | public int getSubProducer_BPartner_ID()
{
final IAttributeStorage attributeStorage = getAttributeStorage();
if (!attributeStorage.hasAttribute(attr_SubProducerBPartner))
{
return -1;
}
final int subProducerBPartnerId = attributeStorage.getValueAsInt(attr_SubProducerBPartner);
return subProducerBPartnerId <= 0 ? -1 : subProducerBPartnerId; // make sure we use same value for N/A
}
public Optional<Quantity> getWeight()
{
final IWeightable weightable = Weightables.wrap(getAttributeStorage());
if (weightable == null)
{
return Optional.empty();
}
final BigDecimal weightNetOrNull = weightable.getWeightNetOrNull();
if (weightNetOrNull == null)
{
return Optional.empty();
}
return Optional.of(Quantity.of(weightNetOrNull, weightable.getWeightNetUOM()));
}
/**
* The M_QualityNote linked with the HUReceiptLine | *
* @return
*/
public I_M_QualityNote getQualityNote()
{
final IAttributeStorage attributeStorage = getAttributeStorage();
if (!attributeStorage.hasAttribute(attr_QualityNotice))
{
return null;
}
// if the quality notice is set, then take it's name. It must have a qualityDiscount% to be set
final Object qualityNoticeCode = attributeStorage.getValue(attr_QualityNotice);
if (qualityNoticeCode == null)
{
return null;
}
return Services.get(IQualityNoteDAO.class).retrieveQualityNoteForValue(huContext.getCtx(), qualityNoticeCode.toString());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\inoutcandidate\spi\impl\HUReceiptLinePartAttributes.java | 1 |
请完成以下Java代码 | private IQueryBuilder<I_M_InOut> toSqlQuery(@NonNull final InOutQuery query)
{
final IQueryBuilder<I_M_InOut> sqlQueryBuilder = queryBL.createQueryBuilder(I_M_InOut.class)
.setLimit(query.getLimit())
.addOnlyActiveRecordsFilter();
if (query.getMovementDateFrom() != null)
{
sqlQueryBuilder.addCompareFilter(I_M_InOut.COLUMNNAME_MovementDate, Operator.GREATER_OR_EQUAL, query.getMovementDateFrom());
}
if (query.getMovementDateTo() != null)
{
sqlQueryBuilder.addCompareFilter(I_M_InOut.COLUMNNAME_MovementDate, Operator.LESS_OR_EQUAL, query.getMovementDateTo());
}
if (query.getDocStatus() != null) | {
sqlQueryBuilder.addEqualsFilter(I_M_InOut.COLUMNNAME_DocStatus, query.getDocStatus());
}
if (query.getExcludeDocStatuses() != null && !query.getExcludeDocStatuses().isEmpty())
{
sqlQueryBuilder.addNotInArrayFilter(I_M_InOut.COLUMNNAME_DocStatus, query.getExcludeDocStatuses());
}
if (!query.getOrderIds().isEmpty())
{
sqlQueryBuilder.addInArrayFilter(I_M_InOut.COLUMNNAME_C_Order_ID, query.getOrderIds());
}
return sqlQueryBuilder;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inout\impl\InOutDAO.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.