instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public Iterator<I_C_Dunning_Candidate_Invoice_v1> retrieveDunningCandidateInvoices(final IDunningContext context)
{
final Properties ctx = context.getCtx();
final String trxName = context.getTrxName();
final IQueryBL queryBL = Services.get(IQueryBL.class);
final I_C_DunningLevel dunningLevel = context.getC_DunningLevel();
Check.assumeNotNull(dunningLevel, "Context shall have DuningLevel set: {}", context);
Check.assumeNotNull(context.getDunningDate(), "Context shall have DunningDate set: {}", context);
final Date dunningDate = TimeUtil.getDay(context.getDunningDate());
final ICompositeQueryFilter<I_C_Dunning_Candidate_Invoice_v1> dunningGraceFilter = queryBL
.createCompositeQueryFilter(I_C_Dunning_Candidate_Invoice_v1.class)
.setJoinOr()
.addEqualsFilter(I_C_Dunning_Candidate_Invoice_v1.COLUMN_DunningGrace, null)
.addCompareFilter(I_C_Dunning_Candidate_Invoice_v1.COLUMN_DunningGrace, Operator.LESS, dunningDate);
return queryBL.createQueryBuilder(I_C_Dunning.class, ctx, trxName)
.addOnlyActiveRecordsFilter() | .addOnlyContextClient(ctx)
.addEqualsFilter(I_C_Dunning.COLUMNNAME_C_Dunning_ID, dunningLevel.getC_Dunning_ID()) // Dunning Level is for current assigned Dunning
.andCollectChildren(I_C_Dunning_Candidate_Invoice_v1.COLUMN_C_Dunning_ID)
.addOnlyActiveRecordsFilter()
.addOnlyContextClient(ctx)
.filter(dunningGraceFilter) // Validate Dunning Grace (if any)
.orderBy()
.addColumn(I_C_Dunning_Candidate_Invoice_v1.COLUMN_C_Invoice_ID).endOrderBy()
.setOption(IQuery.OPTION_IteratorBufferSize, 1000 /* iterator shall load 1000 records at a time */)
.setOption(IQuery.OPTION_GuaranteedIteratorRequired, false /* the result is not changing while the iterator is iterated */)
.create()
.iterate(I_C_Dunning_Candidate_Invoice_v1.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dunning\src\main\java\de\metas\dunning\invoice\api\impl\InvoiceSourceDAO.java | 1 |
请完成以下Java代码 | public String getGroupId() {
return this.groupId;
}
public void setGroupId(String groupId) {
this.groupId = groupId;
}
public String getArtifactId() {
return this.artifactId;
}
public void setArtifactId(String artifactId) {
this.artifactId = artifactId;
}
public String getVersion() {
return this.version;
}
public void setVersion(String version) {
this.version = version;
}
public Boolean getStarter() {
return this.starter;
}
public void setStarter(Boolean starter) {
this.starter = starter;
}
public String getBom() {
return this.bom;
}
public void setBom(String bom) {
this.bom = bom; | }
public String getRepository() {
return this.repository;
}
public void setRepository(String repository) {
this.repository = repository;
}
public VersionRange getRange() {
return this.range;
}
public String getCompatibilityRange() {
return this.compatibilityRange;
}
public void setCompatibilityRange(String compatibilityRange) {
this.compatibilityRange = compatibilityRange;
}
public static Mapping create(String range, String groupId, String artifactId, String version, Boolean starter,
String bom, String repository) {
Mapping mapping = new Mapping();
mapping.compatibilityRange = range;
mapping.groupId = groupId;
mapping.artifactId = artifactId;
mapping.version = version;
mapping.starter = starter;
mapping.bom = bom;
mapping.repository = repository;
return mapping;
}
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Dependency.java | 1 |
请完成以下Java代码 | public int getMSV3_Bestellung_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Bestellung_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set MSV3_BestellungAuftrag.
@param MSV3_BestellungAuftrag_ID MSV3_BestellungAuftrag */
@Override
public void setMSV3_BestellungAuftrag_ID (int MSV3_BestellungAuftrag_ID)
{
if (MSV3_BestellungAuftrag_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAuftrag_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAuftrag_ID, Integer.valueOf(MSV3_BestellungAuftrag_ID));
}
/** Get MSV3_BestellungAuftrag.
@return MSV3_BestellungAuftrag */
@Override
public int getMSV3_BestellungAuftrag_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAuftrag_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set GebindeId.
@param MSV3_GebindeId GebindeId */
@Override
public void setMSV3_GebindeId (java.lang.String MSV3_GebindeId)
{
set_Value (COLUMNNAME_MSV3_GebindeId, MSV3_GebindeId);
}
/** Get GebindeId.
@return GebindeId */
@Override
public java.lang.String getMSV3_GebindeId () | {
return (java.lang.String)get_Value(COLUMNNAME_MSV3_GebindeId);
}
/** Set Id.
@param MSV3_Id Id */
@Override
public void setMSV3_Id (java.lang.String MSV3_Id)
{
set_Value (COLUMNNAME_MSV3_Id, MSV3_Id);
}
/** Get Id.
@return Id */
@Override
public java.lang.String getMSV3_Id ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_Id);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungAuftrag.java | 1 |
请完成以下Java代码 | private void updateDebitorCreditorIdsAndSave(@NonNull final AcctSchema acctSchema, @NonNull final I_C_BPartner bpartner)
{
Services.get(ITrxManager.class).runInNewTrx(localTrxName -> {
try
{
updateDebitorCreditorIds(acctSchema, bpartner);
InterfaceWrapperHelper.save(bpartner);
}
catch (final RuntimeException runException)
{
final ILoggable loggable = Loggables.withLogger(logger, Level.WARN);
loggable.addLog("AcctSchemaBL.updateDebitorCreditorIdsAndSave, for bpartnerId {} - caught {} with message={}",
bpartner.getC_BPartner_ID(),
runException.getClass(),
runException.getMessage(),
runException);
}
});
}
@Override
public void updateDebitorCreditorIds(@NonNull final AcctSchema acctSchema, @NonNull final I_C_BPartner bpartner)
{
if (acctSchema.isAutoSetDebtoridAndCreditorid())
{
String value = bpartner.getValue();
//as per c_bpartner_datev_no_generate.sql, we should be updating only values with length between 5 and 7
if (Check.isNotBlank(value)) | {
if (value.startsWith("<") && value.endsWith(">"))
{
value = value.substring(1, value.length() - 1);
}
if (value.length() >= 5 && value.length() <= 7 && StringUtils.isNumber(value))
{
final String valueAsString = Strings.padStart(value, 7, '0').substring(0, 7);
bpartner.setCreditorId(Integer.parseInt(acctSchema.getCreditorIdPrefix() + valueAsString));
bpartner.setDebtorId(Integer.parseInt(acctSchema.getDebtorIdPrefix() + valueAsString));
}
else
{
Loggables.withLogger(logger, Level.DEBUG).addLog("value {} for bpartnerId {} must be a number with 5 to 7 digits", value, bpartner.getC_BPartner_ID());
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\acct\api\impl\AcctSchemaBL.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AttributesIncludedTabId implements RepoIdAware
{
int repoId;
private AttributesIncludedTabId(final int repoId)
{
this.repoId = Check.assumeGreaterOrEqualToZero(repoId, I_M_AttributeSet_IncludedTab.COLUMNNAME_M_AttributeSet_IncludedTab_ID);
}
@JsonCreator
public static AttributesIncludedTabId ofRepoId(final int repoId)
{
final AttributesIncludedTabId id = ofRepoIdOrNull(repoId);
if (id == null)
{
throw new AdempiereException("Invalid repoId: " + repoId);
} | return id;
}
public static AttributesIncludedTabId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new AttributesIncludedTabId(repoId) : null;
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\attributes_included_tab\descriptor\AttributesIncludedTabId.java | 2 |
请完成以下Java代码 | protected boolean isUpdateReceiptScheduleDefaultConfiguration()
{
return p_IsSaveLUTUConfiguration;
}
@Override
protected I_M_HU_LUTU_Configuration createM_HU_LUTU_Configuration(final I_M_HU_LUTU_Configuration template)
{
// Validate parameters
final int M_LU_HU_PI_ID = p_M_LU_HU_PI_ID;
final int M_HU_PI_Item_Product_ID = p_M_HU_PI_Item_Product_ID;
final BigDecimal qtyCUsPerTU = p_QtyCUsPerTU;
final BigDecimal qtyTU = p_QtyTU;
final BigDecimal qtyLU = p_QtyLU;
if (M_HU_PI_Item_Product_ID <= 0)
{
throw new FillMandatoryException(PARAM_M_HU_PI_Item_Product_ID);
}
if (qtyCUsPerTU == null || qtyCUsPerTU.signum() <= 0)
{
throw new FillMandatoryException(PARAM_QtyCUsPerTU);
}
if (qtyTU == null || qtyTU.signum() <= 0)
{
throw new FillMandatoryException(PARAM_QtyTU);
}
if (M_LU_HU_PI_ID > 0 && qtyLU.signum() <= 0)
{
throw new FillMandatoryException(PARAM_QtyLU); | }
final ILUTUConfigurationFactory.CreateLUTUConfigRequest lutuConfigRequest = ILUTUConfigurationFactory.CreateLUTUConfigRequest.builder()
.baseLUTUConfiguration(template)
.qtyLU(qtyLU)
.qtyTU(qtyTU)
.qtyCUsPerTU(qtyCUsPerTU)
.tuHUPIItemProductID(M_HU_PI_Item_Product_ID)
.luHUPIID(M_LU_HU_PI_ID)
.build();
return lutuConfigurationFactory.createNewLUTUConfigWithParams(lutuConfigRequest);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_ReceiveHUs_UsingConfig.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class OrderCostCreateRequest
{
@Nullable BPartnerId bpartnerId;
@NonNull OrderCostTypeId costTypeId;
@Nullable CostCalculationMethodParams costCalculationMethodParams;
@NonNull ImmutableSet<OrderAndLineId> orderAndLineIds;
@Nullable OrderLine addOrderLine;
@Builder
private OrderCostCreateRequest(
@Nullable final BPartnerId bpartnerId,
@NonNull final OrderCostTypeId costTypeId,
@Nullable final CostCalculationMethodParams costCalculationMethodParams,
@NonNull final ImmutableSet<OrderAndLineId> orderAndLineIds,
@Nullable final OrderLine addOrderLine)
{
this.bpartnerId = bpartnerId;
if (orderAndLineIds.isEmpty())
{
throw new AdempiereException("No order lines");
}
this.costTypeId = costTypeId;
this.costCalculationMethodParams = costCalculationMethodParams;
this.orderAndLineIds = orderAndLineIds; | this.addOrderLine = addOrderLine;
}
public OrderId getOrderId()
{
return CollectionUtils.extractSingleElement(orderAndLineIds, OrderAndLineId::getOrderId);
}
@Value
@Builder
public static class OrderLine
{
@NonNull ProductId productId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostCreateRequest.java | 2 |
请完成以下Java代码 | public void info(int WindowNo, String AD_Message)
{
logger.info(AD_Message);
}
@Override
public void info(int WindowNo, String AD_Message, String message)
{
logger.info("" + AD_Message + ": " + message);
}
@Override
public IAskDialogBuilder ask()
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public boolean ask(int WindowNo, String AD_Message)
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public boolean ask(int WindowNo, String AD_Message, String message)
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public void warn(int WindowNo, String AD_Message)
{
logger.warn(AD_Message);
}
@Override
public void warn(int WindowNo, String AD_Message, String message)
{
logger.warn("" + AD_Message + ": " + message);
}
@Override
public void error(int WIndowNo, String AD_Message)
{
logger.warn("" + AD_Message);
}
@Override
public void error(int WIndowNo, String AD_Message, String message)
{
logger.error("" + AD_Message + ": " + message);
}
@Override
public void download(byte[] data, String contentType, String filename)
{
throw new UnsupportedOperationException("not implemented");
} | @Override
public void downloadNow(InputStream content, String contentType, String filename)
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public String getClientInfo()
{
// implementation basically copied from SwingClientUI
final String javaVersion = System.getProperty("java.version");
return new StringBuilder("!! NO UI REGISTERED YET !!, java.version=").append(javaVersion).toString();
}
@Override
public void showWindow(Object model)
{
throw new UnsupportedOperationException("Not implemented: ClientUI.showWindow()");
}
@Override
public IClientUIInvoker invoke()
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public IClientUIAsyncInvoker invokeAsync()
{
throw new UnsupportedOperationException("not implemented");
}
@Override
public void showURL(String url)
{
System.err.println("Showing URL is not supported on server side: " + url);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\adempiere\form\impl\ClientUI.java | 1 |
请完成以下Java代码 | boolean isWhiteSpace() {
return !this.escaped && (this.character == ' ' || this.character == '\t' || this.character == '\f');
}
boolean isEndOfFile() {
return this.character == -1;
}
boolean isEndOfLine() {
return this.character == -1 || (!this.escaped && this.character == '\n');
}
boolean isListDelimiter() {
return !this.escaped && this.character == ',';
}
boolean isPropertyDelimiter() {
return !this.escaped && (this.character == '=' || this.character == ':');
}
char getCharacter() {
return (char) this.character;
}
Location getLocation() {
return new Location(this.reader.getLineNumber(), this.columnNumber);
}
boolean isSameLastLineCommentPrefix() {
return this.lastLineCommentPrefixCharacter == this.character;
}
boolean isCommentPrefixCharacter() {
return this.character == '#' || this.character == '!';
}
boolean isHyphenCharacter() {
return this.character == '-';
}
}
/**
* A single document within the properties file.
*/ | static class Document {
private final Map<String, OriginTrackedValue> values = new LinkedHashMap<>();
void put(String key, OriginTrackedValue value) {
if (!key.isEmpty()) {
this.values.put(key, value);
}
}
boolean isEmpty() {
return this.values.isEmpty();
}
Map<String, OriginTrackedValue> asMap() {
return this.values;
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\OriginTrackedPropertiesLoader.java | 1 |
请完成以下Java代码 | public final class OAuth2AuthorizationManagers {
private OAuth2AuthorizationManagers() {
}
/**
* Create an {@link AuthorizationManager} that requires an {@link Authentication} to
* have a {@code SCOPE_scope} authority.
*
* <p>
* For example, if you call {@code hasScope("read")}, then this will require that each
* authentication have a {@link org.springframework.security.core.GrantedAuthority}
* whose value is {@code SCOPE_read}.
*
* <p>
* This would equivalent to calling
* {@code AuthorityAuthorizationManager#hasAuthority("SCOPE_read")}.
* @param scope the scope value to require
* @param <T> the secure object
* @return an {@link AuthorizationManager} that requires a {@code "SCOPE_scope"}
* authority
*/
public static <T> AuthorizationManager<T> hasScope(String scope) {
assertScope(scope);
return AuthorityAuthorizationManager.hasAuthority("SCOPE_" + scope);
}
/**
* Create an {@link AuthorizationManager} that requires an {@link Authentication} to
* have at least one authority among {@code SCOPE_scope1}, {@code SCOPE_scope2}, ...
* {@code SCOPE_scopeN}.
*
* <p>
* For example, if you call {@code hasAnyScope("read", "write")}, then this will
* require that each authentication have at least a
* {@link org.springframework.security.core.GrantedAuthority} whose value is either
* {@code SCOPE_read} or {@code SCOPE_write}.
*
* <p> | * This would equivalent to calling
* {@code AuthorityAuthorizationManager#hasAnyAuthority("SCOPE_read", "SCOPE_write")}.
* @param scopes the scope values to allow
* @param <T> the secure object
* @return an {@link AuthorizationManager} that requires at least one authority among
* {@code "SCOPE_scope1"}, {@code SCOPE_scope2}, ... {@code SCOPE_scopeN}.
*
*/
public static <T> AuthorizationManager<T> hasAnyScope(String... scopes) {
String[] mappedScopes = new String[scopes.length];
for (int i = 0; i < scopes.length; i++) {
assertScope(scopes[i]);
mappedScopes[i] = "SCOPE_" + scopes[i];
}
return AuthorityAuthorizationManager.hasAnyAuthority(mappedScopes);
}
private static void assertScope(String scope) {
Assert.isTrue(!scope.startsWith("SCOPE_"),
() -> scope + " should not start with SCOPE_ since SCOPE_"
+ " is automatically prepended when using hasScope and hasAnyScope. Consider using "
+ " AuthorityAuthorizationManager#hasAuthority or #hasAnyAuthority instead.");
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\authorization\OAuth2AuthorizationManagers.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static final class PostgresqlFlywayConfigurationCustomizer implements FlywayConfigurationCustomizer {
private final FlywayProperties properties;
PostgresqlFlywayConfigurationCustomizer(FlywayProperties properties) {
this.properties = properties;
}
@Override
public void customize(FluentConfiguration configuration) {
Extension<PostgreSQLConfigurationExtension> extension = new Extension<>(configuration,
PostgreSQLConfigurationExtension.class, "PostgreSQL");
Postgresql properties = this.properties.getPostgresql();
PropertyMapper map = PropertyMapper.get();
map.from(properties::getTransactionalLock)
.to(extension.via((ext, transactionalLock) -> ext.setTransactionalLock(transactionalLock)));
}
}
@Order(Ordered.HIGHEST_PRECEDENCE)
static final class SqlServerFlywayConfigurationCustomizer implements FlywayConfigurationCustomizer {
private final FlywayProperties properties;
SqlServerFlywayConfigurationCustomizer(FlywayProperties properties) {
this.properties = properties;
}
@Override
public void customize(FluentConfiguration configuration) {
Extension<SQLServerConfigurationExtension> extension = new Extension<>(configuration,
SQLServerConfigurationExtension.class, "SQL Server");
Sqlserver properties = this.properties.getSqlserver();
PropertyMapper map = PropertyMapper.get();
map.from(properties::getKerberosLoginFile).to(extension.via(this::setKerberosLoginFile)); | }
private void setKerberosLoginFile(SQLServerConfigurationExtension configuration, String file) {
configuration.getKerberos().getLogin().setFile(file);
}
}
/**
* Helper class used to map properties to a {@link ConfigurationExtension}.
*
* @param <E> the extension type
*/
static class Extension<E extends ConfigurationExtension> {
private final Supplier<E> extension;
Extension(FluentConfiguration configuration, Class<E> type, String name) {
this.extension = SingletonSupplier.of(() -> {
E extension = configuration.getPluginRegister().getExact(type);
Assert.state(extension != null, () -> "Flyway %s extension missing".formatted(name));
return extension;
});
}
<T> Consumer<T> via(BiConsumer<E, T> action) {
return (value) -> action.accept(this.extension.get(), value);
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-flyway\src\main\java\org\springframework\boot\flyway\autoconfigure\FlywayAutoConfiguration.java | 2 |
请完成以下Java代码 | public class MInvoiceBatchLine extends X_C_InvoiceBatchLine
{
/**
*
*/
private static final long serialVersionUID = -4022629343631759064L;
/**
* Standard Constructor
* @param ctx context
* @param C_InvoiceBatchLine_ID id
* @param trxName trx
*/
public MInvoiceBatchLine (Properties ctx, int C_InvoiceBatchLine_ID,
String trxName)
{
super (ctx, C_InvoiceBatchLine_ID, trxName);
if (C_InvoiceBatchLine_ID == 0)
{
// setC_InvoiceBatch_ID (0);
/**
setC_BPartner_ID (0);
setC_BPartner_Location_ID (0);
setC_Charge_ID (0);
setC_DocType_ID (0); // @C_DocType_ID@
setC_Tax_ID (0);
setDocumentNo (null);
setLine (0); // @SQL=SELECT COALESCE(MAX(Line),0)+10 AS DefaultValue FROM C_InvoiceBatchLine WHERE C_InvoiceBatch_ID=@C_InvoiceBatch_ID@
**/
setDateAcct (new Timestamp(System.currentTimeMillis())); // @DateDoc@
setDateInvoiced (new Timestamp(System.currentTimeMillis())); // @DateDoc@
setIsTaxIncluded (false);
setLineNetAmt (Env.ZERO);
setLineTotalAmt (Env.ZERO);
setPriceEntered (Env.ZERO);
setQtyEntered (Env.ONE); // 1
setTaxAmt (Env.ZERO);
setProcessed (false);
}
} // MInvoiceBatchLine
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName trx
*/
public MInvoiceBatchLine (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName); | } // MInvoiceBatchLine
/**
* Before Save
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave (boolean newRecord)
{
// Amount
if (getPriceEntered().signum() == 0)
{
throw new FillMandatoryException("PriceEntered");
}
return true;
} // beforeSave
/**
* After Save.
* Update Header
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
if (success)
{
String sql = "UPDATE C_InvoiceBatch h "
+ "SET DocumentAmt = COALESCE((SELECT SUM(LineTotalAmt) FROM C_InvoiceBatchLine l "
+ "WHERE h.C_InvoiceBatch_ID=l.C_InvoiceBatch_ID AND l.IsActive='Y'),0) "
+ "WHERE C_InvoiceBatch_ID=" + getC_InvoiceBatch_ID();
DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
}
return success;
} // afterSave
} // MInvoiceBatchLine | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MInvoiceBatchLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class EmailTwoFaProvider extends OtpBasedTwoFaProvider<EmailTwoFaProviderConfig, EmailTwoFaAccountConfig> {
private final MailService mailService;
protected EmailTwoFaProvider(CacheManager cacheManager, MailService mailService) {
super(cacheManager);
this.mailService = mailService;
}
@Override
public EmailTwoFaAccountConfig generateNewAccountConfig(User user, EmailTwoFaProviderConfig providerConfig) {
EmailTwoFaAccountConfig config = new EmailTwoFaAccountConfig();
config.setEmail(user.getEmail());
return config;
}
@Override
public void check(TenantId tenantId) throws ThingsboardException {
try {
mailService.testConnection(tenantId);
} catch (Exception e) {
throw new ThingsboardException("Mail service is not set up", ThingsboardErrorCode.BAD_REQUEST_PARAMS);
}
} | @Override
protected void sendVerificationCode(SecurityUser user, String verificationCode, EmailTwoFaProviderConfig providerConfig, EmailTwoFaAccountConfig accountConfig) throws ThingsboardException {
try {
mailService.sendTwoFaVerificationEmail(accountConfig.getEmail(), verificationCode, providerConfig.getVerificationCodeLifetime());
} catch (Exception e) {
throw new ThingsboardException("Couldn't send 2FA verification email", ThingsboardErrorCode.GENERAL);
}
}
@Override
public TwoFaProviderType getType() {
return TwoFaProviderType.EMAIL;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\mfa\provider\impl\EmailTwoFaProvider.java | 2 |
请在Spring Boot框架中完成以下Java代码 | static LazyInitializationExcludeFilter eagerlyInitializeJmxEndpointExporter() {
return LazyInitializationExcludeFilter.forBeanTypes(JmxEndpointExporter.class);
}
@Bean
OperationFilter<JmxOperation> jmxAccessPropertiesOperationFilter(EndpointAccessResolver endpointAccessResolver) {
return OperationFilter.byAccess(endpointAccessResolver);
}
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(JsonMapper.class)
static class JmxJacksonEndpointConfiguration {
@Bean
@ConditionalOnSingleCandidate(MBeanServer.class)
JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer,
EndpointObjectNameFactory endpointObjectNameFactory, ObjectProvider<JsonMapper> jsonMapper,
JmxEndpointsSupplier jmxEndpointsSupplier) {
JmxOperationResponseMapper responseMapper = new JacksonJmxOperationResponseMapper(
jsonMapper.getIfAvailable());
return new JmxEndpointExporter(mBeanServer, endpointObjectNameFactory, responseMapper,
jmxEndpointsSupplier.getEndpoints());
} | }
@Configuration(proxyBeanMethods = false)
@ConditionalOnClass(ObjectMapper.class)
@ConditionalOnMissingClass("tools.jackson.databind.json.JsonMapper")
@Deprecated(since = "4.0.0", forRemoval = true)
@SuppressWarnings("removal")
static class JmxJackson2EndpointConfiguration {
@Bean
@ConditionalOnSingleCandidate(MBeanServer.class)
JmxEndpointExporter jmxMBeanExporter(MBeanServer mBeanServer,
EndpointObjectNameFactory endpointObjectNameFactory, ObjectProvider<ObjectMapper> objectMapper,
JmxEndpointsSupplier jmxEndpointsSupplier) {
JmxOperationResponseMapper responseMapper = new org.springframework.boot.actuate.endpoint.jmx.Jackson2JmxOperationResponseMapper(
objectMapper.getIfAvailable());
return new JmxEndpointExporter(mBeanServer, endpointObjectNameFactory, responseMapper,
jmxEndpointsSupplier.getEndpoints());
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\jmx\JmxEndpointAutoConfiguration.java | 2 |
请完成以下Java代码 | public int compare(CmmnEngineLookup o1, CmmnEngineLookup o2) {
return (-1) * ((Integer) o1.getPrecedence()).compareTo(o2.getPrecedence());
}
});
CmmnEngine cmmnEngine = null;
for (CmmnEngineLookup cmmnEngineLookup : discoveredLookups) {
cmmnEngine = cmmnEngineLookup.getCmmnEngine();
if (cmmnEngine != null) {
this.cmmnEngineLookup = cmmnEngineLookup;
LOGGER.debug("CmmnEngineLookup service {} returned cmmn engine.", cmmnEngineLookup.getClass());
break;
} else {
LOGGER.debug("CmmnEngineLookup service {} returned 'null' value.", cmmnEngineLookup.getClass());
}
}
if (cmmnEngineLookup == null) {
throw new FlowableException(
"Could not find an implementation of the " + CmmnEngineLookup.class.getName() + " service returning a non-null cmmnEngine. Giving up.");
} | Bean<FlowableCmmnServices> flowableCmmnServicesBean = (Bean<FlowableCmmnServices>) beanManager.getBeans(FlowableCmmnServices.class).stream()
.findAny()
.orElseThrow(
() -> new IllegalStateException("CDI BeanManager cannot find an instance of requested type " + FlowableCmmnServices.class.getName()));
FlowableCmmnServices services = (FlowableCmmnServices) beanManager
.getReference(flowableCmmnServicesBean, FlowableCmmnServices.class, beanManager.createCreationalContext(flowableCmmnServicesBean));
services.setCmmnEngine(cmmnEngine);
return cmmnEngine;
}
public void beforeShutdown(@Observes BeforeShutdown event) {
if (cmmnEngineLookup != null) {
cmmnEngineLookup.ungetCmmnEngine();
cmmnEngineLookup = null;
}
LOGGER.info("Shutting down flowable-cmmn-cdi");
}
} | repos\flowable-engine-main\modules\flowable-cmmn-cdi\src\main\java\org\flowable\cdi\impl\FlowableCmmnExtension.java | 1 |
请完成以下Java代码 | public java.lang.String getDK_Sender_Name2 ()
{
return (java.lang.String)get_Value(COLUMNNAME_DK_Sender_Name2);
}
/** Set Absender Name3.
@param DK_Sender_Name3 Absender Name3 */
@Override
public void setDK_Sender_Name3 (java.lang.String DK_Sender_Name3)
{
set_Value (COLUMNNAME_DK_Sender_Name3, DK_Sender_Name3);
}
/** Get Absender Name3.
@return Absender Name3 */
@Override
public java.lang.String getDK_Sender_Name3 ()
{
return (java.lang.String)get_Value(COLUMNNAME_DK_Sender_Name3);
}
/** Set Absender Strasse.
@param DK_Sender_Street Absender Strasse */
@Override
public void setDK_Sender_Street (java.lang.String DK_Sender_Street)
{
set_Value (COLUMNNAME_DK_Sender_Street, DK_Sender_Street);
}
/** Get Absender Strasse.
@return Absender Strasse */
@Override
public java.lang.String getDK_Sender_Street ()
{
return (java.lang.String)get_Value(COLUMNNAME_DK_Sender_Street);
}
/** Set Absender PLZ.
@param DK_Sender_ZipCode
Postleitzahl
*/
@Override
public void setDK_Sender_ZipCode (java.lang.String DK_Sender_ZipCode)
{
set_Value (COLUMNNAME_DK_Sender_ZipCode, DK_Sender_ZipCode);
}
/** Get Absender PLZ.
@return Postleitzahl
*/
@Override
public java.lang.String getDK_Sender_ZipCode ()
{
return (java.lang.String)get_Value(COLUMNNAME_DK_Sender_ZipCode);
}
@Override
public org.compiere.model.I_M_Shipper getM_Shipper() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class);
}
@Override
public void setM_Shipper(org.compiere.model.I_M_Shipper M_Shipper)
{
set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper);
}
/** Set Lieferweg.
@param M_Shipper_ID
Methode oder Art der Warenlieferung
*/
@Override
public void setM_Shipper_ID (int M_Shipper_ID)
{ | if (M_Shipper_ID < 1)
set_Value (COLUMNNAME_M_Shipper_ID, null);
else
set_Value (COLUMNNAME_M_Shipper_ID, Integer.valueOf(M_Shipper_ID));
}
/** Get Lieferweg.
@return Methode oder Art der Warenlieferung
*/
@Override
public int getM_Shipper_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipper_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Transport Auftrag.
@param M_ShipperTransportation_ID Transport Auftrag */
@Override
public void setM_ShipperTransportation_ID (int M_ShipperTransportation_ID)
{
if (M_ShipperTransportation_ID < 1)
set_Value (COLUMNNAME_M_ShipperTransportation_ID, null);
else
set_Value (COLUMNNAME_M_ShipperTransportation_ID, Integer.valueOf(M_ShipperTransportation_ID));
}
/** Get Transport Auftrag.
@return Transport Auftrag */
@Override
public int getM_ShipperTransportation_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_ShipperTransportation_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java-gen\de\metas\shipper\gateway\derkurier\model\X_DerKurier_DeliveryOrder.java | 1 |
请完成以下Java代码 | public V get(String key)
{
return trie.get(key);
}
/**
* 由参数构造一个词条
*
* @param line
* @return
*/
protected abstract Map.Entry<String, V> onGenerateEntry(String line);
/**
* 以我为主词典,合并一个副词典,我有的词条不会被副词典覆盖
* @param other 副词典
*/
public void combine(SimpleDictionary<V> other)
{
if (other.trie == null)
{
Predefine.logger.warning("有个词典还没加载");
return;
}
for (Map.Entry<String, V> entry : other.trie.entrySet())
{
if (trie.containsKey(entry.getKey())) continue;
trie.put(entry.getKey(), entry.getValue());
}
}
/**
* 获取键值对集合
* @return
*/
public Set<Map.Entry<String, V>> entrySet()
{
return trie.entrySet();
}
/**
* 键集合
* @return
*/
public Set<String> keySet()
{
TreeSet<String> keySet = new TreeSet<String>();
for (Map.Entry<String, V> entry : entrySet())
{
keySet.add(entry.getKey());
}
return keySet;
}
/**
* 过滤部分词条
* @param filter 过滤器
* @return 删除了多少条
*/
public int remove(Filter filter) | {
int size = trie.size();
for (Map.Entry<String, V> entry : entrySet())
{
if (filter.remove(entry))
{
trie.remove(entry.getKey());
}
}
return size - trie.size();
}
public interface Filter<V>
{
boolean remove(Map.Entry<String, V> entry);
}
/**
* 向中加入单词
* @param key
* @param value
*/
public void add(String key, V value)
{
trie.put(key, value);
}
public int size()
{
return trie.size();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\SimpleDictionary.java | 1 |
请完成以下Java代码 | public Vector add(Vector other)
{
float[] result = new float[size()];
for (int i = 0; i < result.length; i++)
{
result[i] = elementArray[i] + other.elementArray[i];
}
return new Vector(result);
}
public Vector addToSelf(Vector other)
{
for (int i = 0; i < elementArray.length; i++)
{
elementArray[i] = elementArray[i] + other.elementArray[i];
}
return this;
}
public Vector divideToSelf(int n)
{
for (int i = 0; i < elementArray.length; i++)
{
elementArray[i] = elementArray[i] / n;
}
return this;
}
public Vector divideToSelf(float f)
{
for (int i = 0; i < elementArray.length; i++)
{
elementArray[i] = elementArray[i] / f;
} | return this;
}
/**
* 自身归一化
*
* @return
*/
public Vector normalize()
{
divideToSelf(norm());
return this;
}
public float[] getElementArray()
{
return elementArray;
}
public void setElementArray(float[] elementArray)
{
this.elementArray = elementArray;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\mining\word2vec\Vector.java | 1 |
请完成以下Java代码 | private List<I_C_Invoice_Candidate> retrieveInvoiceCandidatesForGroup(@NonNull final GroupId groupId)
{
return retrieveInvoiceCandidatesForGroupQuery(groupId).create().list(I_C_Invoice_Candidate.class);
}
private IQueryBuilder<I_C_Invoice_Candidate> retrieveInvoiceCandidatesForGroupQuery(@NonNull final GroupId groupId)
{
final OrderId orderId = OrderGroupRepository.extractOrderIdFromGroupId(groupId);
final int orderCompensationGroupId = groupId.getOrderCompensationGroupId();
return queryBL.createQueryBuilder(I_C_Invoice_Candidate.class)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMN_C_Order_ID, orderId)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMN_C_Order_CompensationGroup_ID, orderCompensationGroupId);
}
private InvoiceCandidatesStorage retrieveStorage(final GroupId groupId)
{
final List<I_C_Invoice_Candidate> invoiceCandidates = retrieveInvoiceCandidatesForGroupQuery(groupId)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMN_IsGroupCompensationLine, true)
.create()
.list(I_C_Invoice_Candidate.class);
return InvoiceCandidatesStorage.builder()
.groupId(groupId)
.invoiceCandidates(invoiceCandidates)
.performDatabaseChanges(true)
.build();
}
public Group createPartialGroupFromCompensationLine(@NonNull final I_C_Invoice_Candidate invoiceCandidate)
{
InvoiceCandidateCompensationGroupUtils.assertCompensationLine(invoiceCandidate);
final GroupCompensationLine compensationLine = createCompensationLine(invoiceCandidate);
final GroupRegularLine aggregatedRegularLine = GroupRegularLine.builder()
.lineNetAmt(compensationLine.getBaseAmt())
.build();
final I_C_Order order = invoiceCandidate.getC_Order(); | if (order == null)
{
throw new AdempiereException("Invoice candidate has no order: " + invoiceCandidate);
}
return Group.builder()
.groupId(extractGroupId(invoiceCandidate))
.pricePrecision(orderBL.getPricePrecision(order))
.amountPrecision(orderBL.getAmountPrecision(order))
.regularLine(aggregatedRegularLine)
.compensationLine(compensationLine)
.build();
}
public InvoiceCandidatesStorage createNotSaveableSingleOrderLineStorage(@NonNull final I_C_Invoice_Candidate invoiceCandidate)
{
return InvoiceCandidatesStorage.builder()
.groupId(extractGroupId(invoiceCandidate))
.invoiceCandidate(invoiceCandidate)
.performDatabaseChanges(false)
.build();
}
public void invalidateCompensationInvoiceCandidatesOfGroup(final GroupId groupId)
{
final IQuery<I_C_Invoice_Candidate> query = retrieveInvoiceCandidatesForGroupQuery(groupId)
.addEqualsFilter(I_C_Invoice_Candidate.COLUMN_IsGroupCompensationLine, true) // only compensation lines
.create();
invoiceCandDAO.invalidateCandsFor(query);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\compensationGroup\InvoiceCandidateGroupRepository.java | 1 |
请完成以下Java代码 | public boolean isDead() {
if (DashboardConfig.getAutoRemoveMachineMillis() > 0) {
long delta = System.currentTimeMillis() - lastHeartbeat;
return delta > DashboardConfig.getAutoRemoveMachineMillis();
}
return false;
}
public long getLastHeartbeat() {
return lastHeartbeat;
}
public void setLastHeartbeat(long lastHeartbeat) {
this.lastHeartbeat = lastHeartbeat;
}
@Override
public int compareTo(MachineInfo o) {
if (this == o) {
return 0;
}
if (!port.equals(o.getPort())) {
return port.compareTo(o.getPort());
}
if (!StringUtil.equals(app, o.getApp())) {
return app.compareToIgnoreCase(o.getApp());
}
return ip.compareToIgnoreCase(o.getIp());
}
@Override
public String toString() {
return new StringBuilder("MachineInfo {")
.append("app='").append(app).append('\'')
.append(",appType='").append(appType).append('\'')
.append(", hostname='").append(hostname).append('\'')
.append(", ip='").append(ip).append('\'')
.append(", port=").append(port)
.append(", heartbeatVersion=").append(heartbeatVersion)
.append(", lastHeartbeat=").append(lastHeartbeat)
.append(", version='").append(version).append('\'')
.append(", healthy=").append(isHealthy())
.append('}').toString(); | }
@Override
public boolean equals(Object o) {
if (this == o) { return true; }
if (!(o instanceof MachineInfo)) { return false; }
MachineInfo that = (MachineInfo)o;
return Objects.equals(app, that.app) &&
Objects.equals(ip, that.ip) &&
Objects.equals(port, that.port);
}
@Override
public int hashCode() {
return Objects.hash(app, ip, port);
}
/**
* Information for log
*
* @return
*/
public String toLogString() {
return app + "|" + ip + "|" + port + "|" + version;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\discovery\MachineInfo.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AcquireTimerJobsCmd implements Command<List<TimerJobEntity>> {
protected AsyncExecutor asyncExecutor;
public AcquireTimerJobsCmd(AsyncExecutor asyncExecutor) {
this.asyncExecutor = asyncExecutor;
}
@Override
public List<TimerJobEntity> execute(CommandContext commandContext) {
JobServiceConfiguration jobServiceConfiguration = asyncExecutor.getJobServiceConfiguration();
List<String> enabledCategories = jobServiceConfiguration.getEnabledJobCategories();
List<TimerJobEntity> timerJobs = jobServiceConfiguration.getTimerJobEntityManager()
.findJobsToExecute(enabledCategories, new Page(0, asyncExecutor.getMaxTimerJobsPerAcquisition()));
for (TimerJobEntity job : timerJobs) {
lockJob(commandContext, job, asyncExecutor.getTimerLockTimeInMillis(), jobServiceConfiguration);
}
return timerJobs;
}
protected void lockJob(CommandContext commandContext, TimerJobEntity job, int lockTimeInMillis, JobServiceConfiguration jobServiceConfiguration) { | // This will use the regular updates flush in the DbSqlSession
// This will trigger an optimistic locking exception when two concurrent executors
// try to lock, as the revision will not match.
GregorianCalendar jobExpirationTime = calculateLockExpirationTime(lockTimeInMillis, jobServiceConfiguration);
job.setLockOwner(asyncExecutor.getLockOwner());
job.setLockExpirationTime(jobExpirationTime.getTime());
}
protected GregorianCalendar calculateLockExpirationTime(int lockTimeInMillis, JobServiceConfiguration jobServiceConfiguration) {
GregorianCalendar gregorianCalendar = new GregorianCalendar();
gregorianCalendar.setTime(jobServiceConfiguration.getClock().getCurrentTime());
gregorianCalendar.add(Calendar.MILLISECOND, lockTimeInMillis);
return gregorianCalendar;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\cmd\AcquireTimerJobsCmd.java | 2 |
请完成以下Java代码 | public int getJobId() {
return jobId;
}
public void setJobId(int jobId) {
this.jobId = jobId;
}
public String getExecutorAddress() {
return executorAddress;
}
public void setExecutorAddress(String executorAddress) {
this.executorAddress = executorAddress;
}
public String getExecutorHandler() {
return executorHandler;
}
public void setExecutorHandler(String executorHandler) {
this.executorHandler = executorHandler;
}
public String getExecutorParam() {
return executorParam;
}
public void setExecutorParam(String executorParam) {
this.executorParam = executorParam;
}
public String getExecutorShardingParam() {
return executorShardingParam;
}
public void setExecutorShardingParam(String executorShardingParam) {
this.executorShardingParam = executorShardingParam;
}
public int getExecutorFailRetryCount() {
return executorFailRetryCount;
}
public void setExecutorFailRetryCount(int executorFailRetryCount) {
this.executorFailRetryCount = executorFailRetryCount;
}
public Date getTriggerTime() {
return triggerTime;
}
public void setTriggerTime(Date triggerTime) {
this.triggerTime = triggerTime;
}
public int getTriggerCode() {
return triggerCode;
}
public void setTriggerCode(int triggerCode) {
this.triggerCode = triggerCode;
}
public String getTriggerMsg() {
return triggerMsg;
}
public void setTriggerMsg(String triggerMsg) {
this.triggerMsg = triggerMsg;
} | public Date getHandleTime() {
return handleTime;
}
public void setHandleTime(Date handleTime) {
this.handleTime = handleTime;
}
public int getHandleCode() {
return handleCode;
}
public void setHandleCode(int handleCode) {
this.handleCode = handleCode;
}
public String getHandleMsg() {
return handleMsg;
}
public void setHandleMsg(String handleMsg) {
this.handleMsg = handleMsg;
}
public int getAlarmStatus() {
return alarmStatus;
}
public void setAlarmStatus(int alarmStatus) {
this.alarmStatus = alarmStatus;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobLog.java | 1 |
请完成以下Java代码 | protected BooleanStringExpression createConstant(final ExpressionContext context, final String expressionStr, final Boolean constantValue)
{
if (constantValue == null)
{
// shall not happen
return nullExpression;
}
return constantValue ? TRUE : FALSE;
}
@Override
protected BooleanStringExpression createSingleParamaterExpression(final ExpressionContext context, final String expressionStr, final CtxName parameter)
{
return new SingleParameterExpression(context, this, expressionStr, parameter);
}
@Override
protected BooleanStringExpression createGeneralExpression(final ExpressionContext context, final String expressionStr, final List<Object> expressionChunks)
{
return new GeneralExpression(context, this, expressionStr, expressionChunks);
}
});
}
private static final class BooleanValueConverter implements ValueConverter<Boolean, BooleanStringExpression>
{
public static final transient BooleanStringExpressionSupport.BooleanValueConverter instance = new BooleanStringExpressionSupport.BooleanValueConverter();
private BooleanValueConverter()
{
super();
}
@Override
public Boolean convertFrom(final Object valueObj, final ExpressionContext options)
{
if (valueObj == null)
{
return null;
}
final Boolean defaultValue = null;
return DisplayType.toBoolean(valueObj, defaultValue);
}
}
private static final class NullExpression extends NullExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression
{
public NullExpression(final Compiler<Boolean, BooleanStringExpression> compiler) | {
super(compiler);
}
}
private static final class ConstantExpression extends ConstantExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression
{
private ConstantExpression(final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final Boolean constantValue)
{
super(ExpressionContext.EMPTY, compiler, expressionStr, constantValue);
}
}
private static final class SingleParameterExpression extends SingleParameterExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression
{
private SingleParameterExpression(final ExpressionContext context, final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final CtxName parameter)
{
super(context, compiler, expressionStr, parameter);
}
@Override
protected Boolean extractParameterValue(Evaluatee ctx)
{
return parameter.getValueAsBoolean(ctx);
}
}
private static final class GeneralExpression extends GeneralExpressionTemplate<Boolean, BooleanStringExpression>implements BooleanStringExpression
{
private GeneralExpression(final ExpressionContext context, final Compiler<Boolean, BooleanStringExpression> compiler, final String expressionStr, final List<Object> expressionChunks)
{
super(context, compiler, expressionStr, expressionChunks);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\BooleanStringExpressionSupport.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class AdminUserServiceImpl implements AdminUserService {
@Autowired
private AdminUserDao adminUserDao;
@Override
public PageResult getAdminUserPage(PageUtil pageUtil) {
//当前页码中的数据列表
List<AdminUser> users = adminUserDao.findAdminUsers(pageUtil);
//数据总条数 用于计算分页数据
int total = adminUserDao.getTotalAdminUser(pageUtil);
PageResult pageResult = new PageResult(users, total, pageUtil.getLimit(), pageUtil.getPage());
return pageResult;
}
@Override
public AdminUser updateTokenAndLogin(String userName, String password) {
AdminUser adminUser = adminUserDao.getAdminUserByUserNameAndPassword(userName, MD5Util.MD5Encode(password, "UTF-8"));
if (adminUser != null) {
//登录后即执行修改token的操作
String token = getNewToken(System.currentTimeMillis() + "", adminUser.getId());
if (adminUserDao.updateUserToken(adminUser.getId(), token) > 0) {
//返回数据时带上token
adminUser.setUserToken(token);
return adminUser;
}
}
return null;
}
/**
* 获取token值
*
* @param sessionId
* @param userId
* @return
*/
private String getNewToken(String sessionId, Long userId) {
String src = sessionId + userId + NumberUtil.genRandomNum(4); | return SystemUtil.genToken(src);
}
@Override
public AdminUser selectById(Long id) {
return adminUserDao.getAdminUserById(id);
}
@Override
public AdminUser selectByUserName(String userName) {
return adminUserDao.getAdminUserByUserName(userName);
}
@Override
public int save(AdminUser user) {
//密码加密
user.setPassword(MD5Util.MD5Encode(user.getPassword(), "UTF-8"));
return adminUserDao.addUser(user);
}
@Override
public int updatePassword(AdminUser user) {
return adminUserDao.updateUserPassword(user.getId(), MD5Util.MD5Encode(user.getPassword(), "UTF-8"));
}
@Override
public int deleteBatch(Integer[] ids) {
return adminUserDao.deleteBatch(ids);
}
@Override
public AdminUser getAdminUserByToken(String userToken) {
return adminUserDao.getAdminUserByToken(userToken);
}
} | repos\spring-boot-projects-main\SpringBoot前后端分离实战项目源码\spring-boot-project-front-end&back-end\src\main\java\cn\lanqiao\springboot3\service\impl\AdminUserServiceImpl.java | 2 |
请完成以下Java代码 | public BigDecimal getQtyInvoiced()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoiced);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyInvoicedInOrderedUOM (final @Nullable BigDecimal QtyInvoicedInOrderedUOM)
{
set_ValueNoCheck (COLUMNNAME_QtyInvoicedInOrderedUOM, QtyInvoicedInOrderedUOM);
}
@Override
public BigDecimal getQtyInvoicedInOrderedUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyInvoicedInOrderedUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setRate (final @Nullable BigDecimal Rate)
{
set_Value (COLUMNNAME_Rate, Rate);
}
@Override
public BigDecimal getRate()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Rate);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSupplier_GTIN_CU (final @Nullable java.lang.String Supplier_GTIN_CU)
{
set_ValueNoCheck (COLUMNNAME_Supplier_GTIN_CU, Supplier_GTIN_CU);
}
@Override
public java.lang.String getSupplier_GTIN_CU()
{
return get_ValueAsString(COLUMNNAME_Supplier_GTIN_CU);
}
@Override
public void setTaxAmtInfo (final @Nullable BigDecimal TaxAmtInfo)
{
set_Value (COLUMNNAME_TaxAmtInfo, TaxAmtInfo);
}
@Override
public BigDecimal getTaxAmtInfo()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmtInfo);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void settaxfree (final boolean taxfree)
{
set_Value (COLUMNNAME_taxfree, taxfree);
} | @Override
public boolean istaxfree()
{
return get_ValueAsBoolean(COLUMNNAME_taxfree);
}
@Override
public void setUPC_CU (final @Nullable java.lang.String UPC_CU)
{
set_ValueNoCheck (COLUMNNAME_UPC_CU, UPC_CU);
}
@Override
public java.lang.String getUPC_CU()
{
return get_ValueAsString(COLUMNNAME_UPC_CU);
}
@Override
public void setUPC_TU (final @Nullable java.lang.String UPC_TU)
{
set_ValueNoCheck (COLUMNNAME_UPC_TU, UPC_TU);
}
@Override
public java.lang.String getUPC_TU()
{
return get_ValueAsString(COLUMNNAME_UPC_TU);
}
@Override
public void setValue (final @Nullable java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_invoic_500_v.java | 1 |
请完成以下Java代码 | public CardAggregated1 getAggtdNtry() {
return aggtdNtry;
}
/**
* Sets the value of the aggtdNtry property.
*
* @param value
* allowed object is
* {@link CardAggregated1 }
*
*/
public void setAggtdNtry(CardAggregated1 value) {
this.aggtdNtry = value;
}
/**
* Gets the value of the prePdAcct property.
*
* @return
* possible object is
* {@link CashAccount24 }
* | */
public CashAccount24 getPrePdAcct() {
return prePdAcct;
}
/**
* Sets the value of the prePdAcct property.
*
* @param value
* allowed object is
* {@link CashAccount24 }
*
*/
public void setPrePdAcct(CashAccount24 value) {
this.prePdAcct = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java-xjc_camt054_001_06\de\metas\payment\camt054_001_06\CardEntry2.java | 1 |
请完成以下Java代码 | public class Survey {
private String id;
private String title;
private String description;
private List<Question> questions;
public Survey(String id, String title, String description,
List<Question> questions) {
super();
this.id = id;
this.title = title;
this.description = description;
this.questions = questions;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title; | }
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public List<Question> getQuestions() {
return questions;
}
public void setQuestions(List<Question> questions) {
this.questions = questions;
}
@Override
public String toString() {
return "Survey [id=" + id + ", title=" + title + ", description="
+ description + ", questions=" + questions + "]";
}
} | repos\SpringBootForBeginners-master\05.Spring-Boot-Advanced\src\main\java\com\in28minutes\springboot\model\Survey.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static ImmutableSet<InOutLineId> extractInOutLineIds(final List<MatchInv> matchInvs)
{
return matchInvs.stream()
.map(matchInv -> matchInv.getInoutLineId().getInOutLineId())
.collect(ImmutableSet.toImmutableSet());
}
public boolean hasMatchInvs(
@NonNull final InvoiceAndLineId invoiceAndLineId,
@NonNull final InOutLineId inoutLineId,
@Nullable final InOutCostId inoutCostId)
{
return matchInvoiceRepository.anyMatch(
MatchInvQuery.builder()
.type(inoutCostId == null ? MatchInvType.Material : MatchInvType.Cost)
.invoiceAndLineId(invoiceAndLineId)
.inoutLineId(inoutLineId)
.inoutCostId(inoutCostId)
.build()
);
}
public Optional<OrderLineId> getOrderLineId(final MatchInv matchInv)
{
final I_C_InvoiceLine invoiceLine = invoiceBL.getLineById(matchInv.getInvoiceAndLineId());
OrderLineId orderLineId = OrderLineId.ofRepoIdOrNull(invoiceLine.getC_OrderLine_ID());
if (orderLineId == null)
{
final InOutLineId inoutLineId = matchInv.getInoutLineId().getInOutLineId();
final I_M_InOutLine ioLine = inoutBL.getLineByIdInTrx(inoutLineId);
orderLineId = OrderLineId.ofRepoIdOrNull(ioLine.getC_OrderLine_ID());
}
return Optional.ofNullable(orderLineId);
}
public Optional<Money> getCostAmountMatched(@NonNull final InOutCostId inoutCostId)
{ | final List<MatchInv> matchInvs = matchInvoiceRepository.list(
MatchInvQuery.builder()
.type(MatchInvType.Cost)
.inoutCostId(inoutCostId)
.build());
return matchInvs.stream()
.map(matchInv -> matchInv.getCostPartNotNull().getCostAmountInOut())
.reduce(Money::add);
}
public Optional<Money> getCostAmountMatched(final InvoiceAndLineId invoiceAndLineId)
{
final List<MatchInv> matchInvs = matchInvoiceRepository.list(MatchInvQuery.builder()
.type(MatchInvType.Cost)
.invoiceAndLineId(invoiceAndLineId)
.build());
return matchInvs.stream()
.map(matchInv -> matchInv.getCostPartNotNull().getCostAmountInvoiced())
.reduce(Money::add);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\matchinv\service\MatchInvoiceService.java | 2 |
请完成以下Java代码 | public void setPreload(boolean preload) {
this.preload = preload;
updateHstsHeaderValue();
}
private void updateHstsHeaderValue() {
String headerValue = "max-age=" + this.maxAgeInSeconds;
if (this.includeSubDomains) {
headerValue += " ; includeSubDomains";
}
if (this.preload) {
headerValue += " ; preload";
}
this.hstsHeaderValue = headerValue;
} | private static final class SecureRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
return request.isSecure();
}
@Override
public String toString() {
return "Is Secure";
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\HstsHeaderWriter.java | 1 |
请完成以下Java代码 | public static long getLongSessionAttr(HttpServletRequest request, String key) {
String value = getSessionAttr(request, key);
if (value == null) {
return 0;
}
return Long.parseLong(value);
}
/**
* session 中设置属性
* @param request 请求
* @param key 属性名
*/
public static void setSessionAttr(HttpServletRequest request, String key, Object value) {
HttpSession session = request.getSession();
if (session == null) {
return; | }
session.setAttribute(key, value);
}
/**
* 移除 session 中的属性
* @param request 请求
* @param key 属性名
*/
public static void removeSessionAttr(HttpServletRequest request, String key) {
HttpSession session = request.getSession();
if (session == null) {
return;
}
session.removeAttribute(key);
}
} | repos\kkFileView-master\server\src\main\java\cn\keking\utils\WebUtils.java | 1 |
请完成以下Java代码 | public class UserImportListener extends AnalysisEventListener<UserExcel> {
/**
* 默认每隔3000条存储数据库
*/
private int batchCount = 3000;
/**
* 缓存的数据列表
*/
private List<UserExcel> list = new ArrayList<>();
/**
* 用户service
*/
private final IUserService userService;
@Override
public void invoke(UserExcel data, AnalysisContext context) {
list.add(data);
// 达到BATCH_COUNT,则调用importer方法入库,防止数据几万条数据在内存,容易OOM
if (list.size() >= batchCount) {
// 调用importer方法 | userService.importUser(list);
// 存储完成清理list
list.clear();
}
}
@Override
public void doAfterAllAnalysed(AnalysisContext analysisContext) {
// 调用importer方法
userService.importUser(list);
// 存储完成清理list
list.clear();
}
} | repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\excel\UserImportListener.java | 1 |
请完成以下Java代码 | public void setNm(String value) {
this.nm = value;
}
/**
* Gets the value of the pstlAdr property.
*
* @return
* possible object is
* {@link PostalAddress6 }
*
*/
public PostalAddress6 getPstlAdr() {
return pstlAdr;
}
/**
* Sets the value of the pstlAdr property.
*
* @param value
* allowed object is
* {@link PostalAddress6 }
*
*/
public void setPstlAdr(PostalAddress6 value) {
this.pstlAdr = value;
}
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link Party6Choice }
*
*/
public Party6Choice getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link Party6Choice }
*
*/
public void setId(Party6Choice value) {
this.id = value;
}
/**
* Gets the value of the ctryOfRes property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCtryOfRes() {
return ctryOfRes;
}
/** | * Sets the value of the ctryOfRes property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCtryOfRes(String value) {
this.ctryOfRes = value;
}
/**
* Gets the value of the ctctDtls property.
*
* @return
* possible object is
* {@link ContactDetails2 }
*
*/
public ContactDetails2 getCtctDtls() {
return ctctDtls;
}
/**
* Sets the value of the ctctDtls property.
*
* @param value
* allowed object is
* {@link ContactDetails2 }
*
*/
public void setCtctDtls(ContactDetails2 value) {
this.ctctDtls = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\PartyIdentification32.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private List<String> extractTherapyTypes(@NonNull final Order order)
{
if (order.getTherapyTypeIds() == null)
{
return null;
}
return order.getTherapyTypeIds().stream()
.filter(Objects::nonNull)
.map(String::valueOf)
.collect(Collectors.toList());
}
@NonNull
private static JsonMetasfreshId extractDeliveryAddressMFId(@NonNull final JsonResponseUpsert deliveryAddressUpsertResponse)
{
final JsonResponseUpsertItem responseUpsertItem = Check.singleElement(deliveryAddressUpsertResponse.getResponseItems());
if (responseUpsertItem.getMetasfreshId() == null)
{
throw new RuntimeException("Delivery address wasn't successfully persisted! ExternalId: " + responseUpsertItem.getIdentifier());
}
return responseUpsertItem.getMetasfreshId();
}
private void computeNextImportDate(@NonNull final Exchange exchange, @NonNull final Order orderCandidate)
{
final Instant nextImportSinceDateCandidate = AlbertaUtil.asInstant(orderCandidate.getCreationDate());
if (nextImportSinceDateCandidate == null)
{
return;
}
final NextImportSinceTimestamp currentNextImportSinceDate =
ProcessorHelper.getPropertyOrThrowError(exchange, GetOrdersRouteConstants.ROUTE_PROPERTY_UPDATED_AFTER, NextImportSinceTimestamp.class);
if (nextImportSinceDateCandidate.isAfter(currentNextImportSinceDate.getDate()))
{ | currentNextImportSinceDate.setDate(nextImportSinceDateCandidate);
}
}
@NonNull
private static Optional<JsonRequestBPartnerLocationAndContact> getBillToBPartner(@NonNull final JsonResponseComposite jsonResponseComposite)
{
final Optional<JsonResponseLocation> billingAddressLocation = jsonResponseComposite.getLocations()
.stream()
.filter(JsonResponseLocation::isBillTo)
.findFirst();
if (billingAddressLocation.isEmpty())
{
return Optional.empty();
}
return Optional.of(JsonRequestBPartnerLocationAndContact.builder()
.bPartnerIdentifier(JsonMetasfreshId.toValueStr(jsonResponseComposite.getBpartner().getMetasfreshId()))
.bPartnerLocationIdentifier(JsonMetasfreshId.toValueStr(billingAddressLocation.get().getMetasfreshId()))
.build());
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\ordercandidate\processor\JsonOLCandCreateRequestProcessor.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class EmployeeRepository {
private List<Employee> employees = new ArrayList<>();
public Employee add(Employee employee) {
employee.setId((long) (employees.size()+1));
employees.add(employee);
return employee;
}
public Employee findById(Long id) {
return employees.stream()
.filter(a -> a.getId().equals(id))
.findFirst()
.orElseThrow();
} | public List<Employee> findAll() {
return employees;
}
public List<Employee> findByDepartment(Long departmentId) {
return employees.stream()
.filter(a -> a.getDepartmentId().equals(departmentId))
.toList();
}
public List<Employee> findByOrganization(Long organizationId) {
return employees.stream()
.filter(a -> a.getOrganizationId().equals(organizationId))
.toList();
}
} | repos\sample-spring-microservices-new-master\employee-service\src\main\java\pl\piomin\services\employee\repository\EmployeeRepository.java | 2 |
请完成以下Java代码 | private static String parameterPlaceholder(final int parameterIndex, final String nonce)
{
return "<--" + parameterIndex + "-" + nonce + "-->";
}
/**
* hook for database specific escape of quoted string ( if needed )
* @param in
* @return string
*/
protected String escapeQuotedString(String in)
{
return in;
}
/**
* Convert simple SQL Statement. Based on ConvertMap
*
* @param sqlStatement
* @return converted Statement
*/
private final String applyConvertMap(String sqlStatement) {
// Error Checks
if (sqlStatement.toUpperCase().indexOf("EXCEPTION WHEN") != -1) {
String error = "Exception clause needs to be converted: "
+ sqlStatement;
log.info(error);
m_conversionError = error;
return sqlStatement;
}
// Carlos Ruiz - globalqss
// Standard Statement -- change the keys in ConvertMap
String retValue = sqlStatement;
// for each iteration in the conversion map
final ConvertMap convertMap = getConvertMap();
if (convertMap != null)
{
// final Iterator<Pattern> iter = convertMap.keySet().iterator();
for (final Map.Entry<Pattern, String> pattern2replacement : convertMap.getPattern2ReplacementEntries())
// while (iter.hasNext())
{
// replace the key on convertmap (i.e.: number by numeric)
final Pattern regex = pattern2replacement.getKey();
final String replacement = pattern2replacement.getValue();
try
{
final Matcher matcher = regex.matcher(retValue);
retValue = matcher.replaceAll(replacement);
}
catch (Exception e)
{
String error = "Error expression: " + regex + " - " + e;
log.info(error);
m_conversionError = error;
}
}
}
return retValue;
} // convertSimpleStatement
/**
* do convert map base conversion
* @param sqlStatement
* @return string
*/
protected final String convertWithConvertMap(String sqlStatement)
{
try
{
sqlStatement = applyConvertMap(cleanUpStatement(sqlStatement));
}
catch (RuntimeException e)
{
log.warn("Failed converting {}", sqlStatement, e);
} | return sqlStatement;
}
/**
* Get convert map for use in sql convertion
* @return map
*/
protected ConvertMap getConvertMap()
{
return null;
}
/**
* Convert single Statements.
* - remove comments
* - process FUNCTION/TRIGGER/PROCEDURE
* - process Statement
* @param sqlStatement
* @return converted statement
*/
protected abstract List<String> convertStatement (String sqlStatement);
/**
* Mark given keyword as native.
*
* Some prefixes/suffixes can be added, but this depends on implementation.
*
* @param keyword
* @return keyword with some prefix/suffix markers.
*/
public String markNative(String keyword)
{
return keyword;
}
} // Convert | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\dbPort\Convert.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static class ConditionAndOutcomes implements Iterable<ConditionAndOutcome> {
private final Set<ConditionAndOutcome> outcomes = new LinkedHashSet<>();
public void add(Condition condition, ConditionOutcome outcome) {
this.outcomes.add(new ConditionAndOutcome(condition, outcome));
}
/**
* Return {@code true} if all outcomes match.
* @return {@code true} if a full match
*/
public boolean isFullMatch() {
for (ConditionAndOutcome conditionAndOutcomes : this) {
if (!conditionAndOutcomes.getOutcome().isMatch()) {
return false;
}
}
return true;
}
/**
* Return a {@link Stream} of the {@link ConditionAndOutcome} items.
* @return a stream of the {@link ConditionAndOutcome} items.
* @since 3.5.0
*/
public Stream<ConditionAndOutcome> stream() {
return StreamSupport.stream(spliterator(), false);
}
@Override
public Iterator<ConditionAndOutcome> iterator() {
return Collections.unmodifiableSet(this.outcomes).iterator();
}
}
/**
* Provides access to a single {@link Condition} and {@link ConditionOutcome}.
*/
public static class ConditionAndOutcome {
private final Condition condition;
private final ConditionOutcome outcome;
public ConditionAndOutcome(Condition condition, ConditionOutcome outcome) {
this.condition = condition;
this.outcome = outcome;
}
public Condition getCondition() {
return this.condition;
}
public ConditionOutcome getOutcome() { | return this.outcome;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ConditionAndOutcome other = (ConditionAndOutcome) obj;
return (ObjectUtils.nullSafeEquals(this.condition.getClass(), other.condition.getClass())
&& ObjectUtils.nullSafeEquals(this.outcome, other.outcome));
}
@Override
public int hashCode() {
return this.condition.getClass().hashCode() * 31 + this.outcome.hashCode();
}
@Override
public String toString() {
return this.condition.getClass() + " " + this.outcome;
}
}
private static final class AncestorsMatchedCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
throw new UnsupportedOperationException();
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\condition\ConditionEvaluationReport.java | 2 |
请完成以下Java代码 | protected void dispatchNormalEventListener(FlowableEvent event, FlowableEventListener listener) {
try {
listener.onEvent(event);
} catch (Throwable t) {
if (listener.isFailOnException()) {
throw t;
} else {
// Ignore the exception and continue notifying remaining listeners. The listener
// explicitly states that the exception should not bubble up
LOGGER.warn("Exception while executing event-listener, which was ignored", t);
}
}
}
protected void dispatchTransactionEventListener(FlowableEvent event, FlowableEventListener listener) {
TransactionContext transactionContext = Context.getTransactionContext();
if (transactionContext == null) {
return;
}
ExecuteEventListenerTransactionListener transactionListener = new ExecuteEventListenerTransactionListener(listener, event);
if (listener.getOnTransaction().equalsIgnoreCase(TransactionState.COMMITTING.name())) {
transactionContext.addTransactionListener(TransactionState.COMMITTING, transactionListener);
} else if (listener.getOnTransaction().equalsIgnoreCase(TransactionState.COMMITTED.name())) {
transactionContext.addTransactionListener(TransactionState.COMMITTED, transactionListener);
} else if (listener.getOnTransaction().equalsIgnoreCase(TransactionState.ROLLINGBACK.name())) {
transactionContext.addTransactionListener(TransactionState.ROLLINGBACK, transactionListener);
} else if (listener.getOnTransaction().equalsIgnoreCase(TransactionState.ROLLED_BACK.name())) {
transactionContext.addTransactionListener(TransactionState.ROLLED_BACK, transactionListener);
} else {
LOGGER.warn("Unrecognised TransactionState {}", listener.getOnTransaction()); | }
}
protected synchronized void addTypedEventListener(FlowableEventListener listener, FlowableEventType type) {
List<FlowableEventListener> listeners = typedListeners.get(type);
if (listeners == null) {
// Add an empty list of listeners for this type
listeners = new CopyOnWriteArrayList<>();
typedListeners.put(type, listeners);
}
if (!listeners.contains(listener)) {
listeners.add(listener);
}
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\event\FlowableEventSupport.java | 1 |
请完成以下Java代码 | public String getCookieName() {
return cookieName;
}
public void setCookieName(String cookieName) {
this.cookieName = cookieName;
}
public Map<String, String> getInitParams() {
Map<String, String> initParams = new HashMap<>();
if (StringUtils.isNotBlank(targetOrigin)) {
initParams.put("targetOrigin", targetOrigin);
}
if (denyStatus != null) {
initParams.put("denyStatus", denyStatus.toString());
}
if (StringUtils.isNotBlank(randomClass)) {
initParams.put("randomClass", randomClass);
}
if (!entryPoints.isEmpty()) {
initParams.put("entryPoints", StringUtils.join(entryPoints, ","));
}
if (enableSecureCookie) { // only add param if it's true; default is false
initParams.put("enableSecureCookie", String.valueOf(enableSecureCookie));
}
if (!enableSameSiteCookie) { // only add param if it's false; default is true
initParams.put("enableSameSiteCookie", String.valueOf(enableSameSiteCookie));
}
if (StringUtils.isNotBlank(sameSiteCookieOption)) {
initParams.put("sameSiteCookieOption", sameSiteCookieOption);
} | if (StringUtils.isNotBlank(sameSiteCookieValue)) {
initParams.put("sameSiteCookieValue", sameSiteCookieValue);
}
if (StringUtils.isNotBlank(cookieName)) {
initParams.put("cookieName", cookieName);
}
return initParams;
}
@Override
public String toString() {
return joinOn(this.getClass())
.add("targetOrigin=" + targetOrigin)
.add("denyStatus='" + denyStatus + '\'')
.add("randomClass='" + randomClass + '\'')
.add("entryPoints='" + entryPoints + '\'')
.add("enableSecureCookie='" + enableSecureCookie + '\'')
.add("enableSameSiteCookie='" + enableSameSiteCookie + '\'')
.add("sameSiteCookieOption='" + sameSiteCookieOption + '\'')
.add("sameSiteCookieValue='" + sameSiteCookieValue + '\'')
.add("cookieName='" + cookieName + '\'')
.toString();
}
} | repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\property\CsrfProperties.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getKeystore() {
return keystore;
}
public void setKeystore(String keystore) {
this.keystore = keystore;
}
public KeyStoreProperties getKeystoreConfig() {
return this.keystoreConfig;
}
public String[] getProtocols() {
return this.protocols;
}
public void setProtocols(String[] protocols) {
this.protocols = protocols;
}
public boolean isRequireAuthentication() {
return this.requireAuthentication;
}
public void setRequireAuthentication(boolean requireAuthentication) {
this.requireAuthentication = requireAuthentication;
}
public String getTruststore() {
return this.truststore;
}
public void setTruststore(String truststore) {
this.truststore = truststore;
}
public KeyStoreProperties getTruststoreConfig() {
return this.truststoreConfig;
}
public boolean isWebRequireAuthentication() {
return this.webRequireAuthentication;
}
public void setWebRequireAuthentication(boolean webRequireAuthentication) {
this.webRequireAuthentication = webRequireAuthentication;
}
public static class KeyStoreProperties {
private String password;
private String type;
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
}
public static class SslCertificateProperties {
@NestedConfigurationProperty
private SslCertificateAliasProperties alias = new SslCertificateAliasProperties();
public SslCertificateAliasProperties getAlias() {
return this.alias;
}
}
public static class SslCertificateAliasProperties {
private String all;
private String cluster;
private String defaultAlias;
private String gateway;
private String jmx; | private String locator;
private String server;
private String web;
public String getAll() {
return this.all;
}
public void setAll(String all) {
this.all = all;
}
public String getCluster() {
return this.cluster;
}
public void setCluster(String cluster) {
this.cluster = cluster;
}
public String getDefaultAlias() {
return this.defaultAlias;
}
public void setDefaultAlias(String defaultAlias) {
this.defaultAlias = defaultAlias;
}
public String getGateway() {
return this.gateway;
}
public void setGateway(String gateway) {
this.gateway = gateway;
}
public String getJmx() {
return this.jmx;
}
public void setJmx(String jmx) {
this.jmx = jmx;
}
public String getLocator() {
return this.locator;
}
public void setLocator(String locator) {
this.locator = locator;
}
public String getServer() {
return this.server;
}
public void setServer(String server) {
this.server = server;
}
public String getWeb() {
return this.web;
}
public void setWeb(String web) {
this.web = web;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-autoconfigure\src\main\java\org\springframework\geode\boot\autoconfigure\configuration\support\SslProperties.java | 2 |
请在Spring Boot框架中完成以下Java代码 | static BeanMetadataElement getAuthenticationRequestRepository(Element element) {
String authenticationRequestRepositoryRef = element.getAttribute(ATT_AUTHENTICATION_REQUEST_REPOSITORY_REF);
if (StringUtils.hasText(authenticationRequestRepositoryRef)) {
return new RuntimeBeanReference(authenticationRequestRepositoryRef);
}
return BeanDefinitionBuilder.rootBeanDefinition(HttpSessionSaml2AuthenticationRequestRepository.class)
.getBeanDefinition();
}
static BeanMetadataElement getAuthenticationRequestResolver(Element element) {
String authenticationRequestContextResolver = element.getAttribute(ATT_AUTHENTICATION_REQUEST_RESOLVER_REF);
if (StringUtils.hasText(authenticationRequestContextResolver)) {
return new RuntimeBeanReference(authenticationRequestContextResolver);
}
return null;
}
static BeanMetadataElement createDefaultAuthenticationRequestResolver(
BeanMetadataElement relyingPartyRegistrationRepository) {
BeanMetadataElement defaultRelyingPartyRegistrationResolver = BeanDefinitionBuilder
.rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class)
.addConstructorArgValue(relyingPartyRegistrationRepository)
.getBeanDefinition();
if (USE_OPENSAML_5) {
return BeanDefinitionBuilder.rootBeanDefinition(OpenSaml5AuthenticationRequestResolver.class)
.addConstructorArgValue(defaultRelyingPartyRegistrationResolver)
.getBeanDefinition();
}
throw new IllegalArgumentException(
"Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5");
}
static BeanDefinition createAuthenticationProvider() {
if (USE_OPENSAML_5) {
return BeanDefinitionBuilder.rootBeanDefinition(OpenSaml5AuthenticationProvider.class).getBeanDefinition();
} | throw new IllegalArgumentException(
"Spring Security does not support OpenSAML " + Version.getVersion() + ". Please use OpenSAML 5");
}
static BeanMetadataElement getAuthenticationConverter(Element element) {
String authenticationConverter = element.getAttribute(ATT_AUTHENTICATION_CONVERTER);
if (StringUtils.hasText(authenticationConverter)) {
return new RuntimeBeanReference(authenticationConverter);
}
return null;
}
static BeanDefinition createDefaultAuthenticationConverter(BeanMetadataElement relyingPartyRegistrationRepository) {
AbstractBeanDefinition resolver = BeanDefinitionBuilder
.rootBeanDefinition(DefaultRelyingPartyRegistrationResolver.class)
.addConstructorArgValue(relyingPartyRegistrationRepository)
.getBeanDefinition();
return BeanDefinitionBuilder.rootBeanDefinition(Saml2AuthenticationTokenConverter.class)
.addConstructorArgValue(resolver)
.getBeanDefinition();
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\Saml2LoginBeanDefinitionParserUtils.java | 2 |
请完成以下Java代码 | public XMLGregorianCalendar getDateEnd() {
return dateEnd;
}
/**
* Sets the value of the dateEnd property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setDateEnd(XMLGregorianCalendar value) {
this.dateEnd = value;
}
/**
* Gets the value of the canton property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getCanton() {
return canton;
}
/**
* Sets the value of the canton property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setCanton(String value) {
this.canton = value;
}
/**
* Gets the value of the reason property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getReason() {
return reason;
}
/**
* Sets the value of the reason property.
*
* @param value | * allowed object is
* {@link String }
*
*/
public void setReason(String value) {
this.reason = value;
}
/**
* Gets the value of the apid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getApid() {
return apid;
}
/**
* Sets the value of the apid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setApid(String value) {
this.apid = value;
}
/**
* Gets the value of the acid property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAcid() {
return acid;
}
/**
* Sets the value of the acid property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAcid(String value) {
this.acid = value;
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\TreatmentType.java | 1 |
请完成以下Java代码 | public UserAuthToken getOrCreateNewToken(@NonNull final CreateUserAuthTokenRequest request)
{
return userAuthTokenRepo.getOrCreateNew(request);
}
private UserInfo getUserInfo(@NonNull final UserId userId)
{
return userInfoById.getOrLoad(userId, this::retrieveUserInfo);
}
private UserInfo retrieveUserInfo(@NonNull final UserId userId)
{
final I_AD_User user = userDAO.getById(userId);
return UserInfo.builder()
.userId(userId) | .adLanguage(StringUtils.trimBlankToOptional(user.getAD_Language()).orElseGet(Language::getBaseAD_Language))
.build();
}
//
//
//
@Value
@Builder
private static class UserInfo
{
@NonNull UserId userId;
@NonNull String adLanguage;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\util\web\security\UserAuthTokenService.java | 1 |
请完成以下Java代码 | private BPartnerId extractBPartnerId(final Object record)
{
final Object bpartnerIdObj = InterfaceWrapperHelper.getValueOrNull(record, "C_BPartner_ID");
if (!(bpartnerIdObj instanceof Integer))
{
return null;
}
final int bpartnerRepoId = (Integer)bpartnerIdObj;
return BPartnerId.ofRepoIdOrNull(bpartnerRepoId);
}
private UserId extractBPartnerContactId(final Object record)
{
final Integer userIdObj = InterfaceWrapperHelper.getValueOrNull(record, "AD_User_ID");
if (!(userIdObj instanceof Integer))
{
return null;
}
final int userRepoId = userIdObj.intValue();
return UserId.ofRepoIdOrNull(userRepoId);
} | private Object getRecord()
{
return _record;
}
public MailTextBuilder customVariable(@NonNull final String name, @Nullable final String value)
{
return customVariable(name, TranslatableStrings.anyLanguage(value));
}
public MailTextBuilder customVariable(@NonNull final String name, @NonNull final ITranslatableString value)
{
_customVariables.put(name, value);
invalidateCache();
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\templates\MailTextBuilder.java | 1 |
请完成以下Java代码 | public abstract class ContactBased<I extends UUIDBased> extends BaseDataWithAdditionalInfo<I> implements HasEmail {
private static final long serialVersionUID = 5047448057830660988L;
@Length(fieldName = "country")
@NoXss
protected String country;
@Length(fieldName = "state")
@NoXss
protected String state;
@Length(fieldName = "city")
@NoXss
protected String city;
@NoXss
protected String address;
@NoXss
protected String address2;
@Length(fieldName = "zip or postal code")
@NoXss
protected String zip;
@Length(fieldName = "phone")
@NoXss
protected String phone;
@Length(fieldName = "email")
@NoXss
protected String email;
public ContactBased() {
super();
}
public ContactBased(I id) {
super(id);
}
public ContactBased(ContactBased<I> contact) {
super(contact);
this.country = contact.getCountry();
this.state = contact.getState();
this.city = contact.getCity();
this.address = contact.getAddress();
this.address2 = contact.getAddress2();
this.zip = contact.getZip();
this.phone = contact.getPhone();
this.email = contact.getEmail();
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getAddress() {
return address; | }
public void setAddress(String address) {
this.address = address;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\ContactBased.java | 1 |
请完成以下Java代码 | public class BusinessRuleTask extends Task {
protected String resultVariableName;
protected boolean exclude;
protected List<String> ruleNames = new ArrayList<String>();
protected List<String> inputVariables = new ArrayList<String>();
protected String className;
public boolean isExclude() {
return exclude;
}
public void setExclude(boolean exclude) {
this.exclude = exclude;
}
public String getResultVariableName() {
return resultVariableName;
}
public void setResultVariableName(String resultVariableName) {
this.resultVariableName = resultVariableName;
}
public List<String> getRuleNames() {
return ruleNames;
}
public void setRuleNames(List<String> ruleNames) {
this.ruleNames = ruleNames;
}
public List<String> getInputVariables() {
return inputVariables;
} | public void setInputVariables(List<String> inputVariables) {
this.inputVariables = inputVariables;
}
public String getClassName() {
return className;
}
public void setClassName(String className) {
this.className = className;
}
public BusinessRuleTask clone() {
BusinessRuleTask clone = new BusinessRuleTask();
clone.setValues(this);
return clone;
}
public void setValues(BusinessRuleTask otherElement) {
super.setValues(otherElement);
setResultVariableName(otherElement.getResultVariableName());
setExclude(otherElement.isExclude());
setClassName(otherElement.getClassName());
ruleNames = new ArrayList<String>(otherElement.getRuleNames());
inputVariables = new ArrayList<String>(otherElement.getInputVariables());
}
} | repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\BusinessRuleTask.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void configureContentNegotiation(final ContentNegotiationConfigurer configurer) {
configurer.favorParameter(true)
.parameterName("mediaType")
.ignoreAcceptHeader(false)
.useRegisteredExtensionsOnly(false)
.defaultContentType(MediaType.APPLICATION_JSON)
.mediaType("xml", MediaType.APPLICATION_XML)
.mediaType("json", MediaType.APPLICATION_JSON);
}
@Bean
public WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> enableDefaultServlet() {
return factory -> factory.setRegisterDefaultServlet(true);
}
@Bean
public Greeting greeting() {
Greeting greeting = new Greeting();
greeting.setMessage("Hello World !!");
return greeting;
}
@Bean
public ObjectMapper objectMapper() {
return new ObjectMapper();
}
@Bean
public ViewResolver viewResolver() {
final InternalResourceViewResolver bean = new InternalResourceViewResolver();
bean.setViewClass(JstlView.class);
bean.setPrefix("/WEB-INF/view/");
bean.setSuffix(".jsp"); | bean.setOrder(2);
return bean;
}
@Bean
public BeanNameViewResolver beanNameViewResolver(){
BeanNameViewResolver beanNameViewResolver = new BeanNameViewResolver();
beanNameViewResolver.setOrder(1);
return beanNameViewResolver;
}
@Bean
public View sample() {
return new JstlView("/WEB-INF/view/sample.jsp");
}
@Bean
public View sample2() {
return new JstlView("/WEB-INF/view2/sample2.jsp");
}
@Bean
public View sample3(){
return new JstlView("/WEB-INF/view3/sample3.jsp");
}
} | repos\tutorials-master\spring-web-modules\spring-mvc-basics-4\src\main\java\com\baeldung\config\WebConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static ShipmentScheduleAndJobScheduleId extractScheduleId(final I_M_Picking_Job_Step step)
{
return ShipmentScheduleAndJobScheduleId.ofRepoIds(step.getM_ShipmentSchedule_ID(), step.getM_Picking_Job_Schedule_ID());
}
private ImmutableSetMultimap<PickingJobId, ShipmentScheduleAndJobScheduleId> getScheduleIds(final Set<PickingJobId> pickingJobIds)
{
final ImmutableSetMultimap.Builder<PickingJobId, ShipmentScheduleAndJobScheduleId> result = ImmutableSetMultimap.builder();
for (final PickingJobId pickingJobId : pickingJobIds)
{
final ShipmentScheduleAndJobScheduleIdSet scheduleIds = getScheduleIds(pickingJobId);
result.putAll(pickingJobId, scheduleIds);
}
return result.build();
}
private Map<PickingJobId, Boolean> computePickingJobHasLocks(@NonNull final Set<PickingJobId> pickingJobIds)
{
if (pickingJobIds.isEmpty())
{
return ImmutableMap.of();
}
final ImmutableSetMultimap<PickingJobId, ShipmentScheduleAndJobScheduleId> scheduleIdsByPickingJobId = getScheduleIds(pickingJobIds);
final ShipmentScheduleAndJobScheduleIdSet scheduleIds = ShipmentScheduleAndJobScheduleIdSet.ofCollection(scheduleIdsByPickingJobId.values());
final ScheduledPackageableLocks existingLocks = loadingSupportingServices.getLocks(scheduleIds);
final ImmutableMap.Builder<PickingJobId, Boolean> result = ImmutableMap.builder();
for (final PickingJobId pickingJobId : pickingJobIds)
{
final boolean hasLocks = existingLocks.isLockedAnyOf(scheduleIdsByPickingJobId.get(pickingJobId)); | result.put(pickingJobId, hasLocks);
}
return result.build();
}
private OptionalBoolean getShipmentSchedulesIsLocked(@NonNull final PickingJobId pickingJobId)
{
return OptionalBoolean.ofNullableBoolean(hasLocks.get(pickingJobId));
}
private PickingUnit computePickingUnit(@Nullable final UomId catchUomId, @NonNull final HUPIItemProduct packingInfo, @NonNull final PickingJobOptions options)
{
// If catch weight, always pick at CU level because user has to weight the products
if (!options.isCatchWeightTUPickingEnabled() && catchUomId != null)
{
return PickingUnit.CU;
}
return packingInfo.isFiniteTU() ? PickingUnit.TU : PickingUnit.CU;
}
private PickingJobOptions getPickingJobOptions(@Nullable final BPartnerId customerId)
{
return loadingSupportingServices.getPickingJobOptions(customerId);
}
private PickingJobOptions getPickingJobOptions(@Nullable final BPartnerLocationId deliveryLocationId)
{
return loadingSupportingServices.getPickingJobOptions(deliveryLocationId != null ? deliveryLocationId.getBpartnerId() : null);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\job\repository\PickingJobLoaderAndSaver.java | 2 |
请完成以下Java代码 | public LookupDescriptor productAttributes()
{
return sql()
.setCtxTableName(null) // tableName
.setCtxColumnName(I_M_AttributeSetInstance.COLUMNNAME_M_AttributeSetInstance_ID)
.setDisplayType(DisplayType.PAttribute)
.setReadOnlyAccess()
.build()
.provide()
.orElseThrow(() -> new AdempiereException("No lookup descriptor found for Product Attributes"));
}
/**
* @return provider which returns given {@link LookupDescriptor} for any scope
*/
public static LookupDescriptorProvider singleton(@NonNull final LookupDescriptor lookupDescriptor)
{
return new SingletonLookupDescriptorProvider(lookupDescriptor);
}
public static LookupDescriptorProvider ofNullableInstance(@Nullable final LookupDescriptor lookupDescriptor)
{
return lookupDescriptor != null ? singleton(lookupDescriptor) : NULL;
}
/**
* @return provider which calls the given function (memoized)
*/
public static LookupDescriptorProvider fromMemoizingFunction(final Function<LookupScope, LookupDescriptor> providerFunction)
{
return new MemoizingFunctionLookupDescriptorProvider(providerFunction);
}
//
//
//
private static class NullLookupDescriptorProvider implements LookupDescriptorProvider
{
@Override
public Optional<LookupDescriptor> provideForScope(final LookupScope scope)
{
return Optional.empty();
}
}
@SuppressWarnings("OptionalUsedAsFieldOrParameterType")
@ToString | private static class SingletonLookupDescriptorProvider implements LookupDescriptorProvider
{
private final Optional<LookupDescriptor> lookupDescriptor;
private SingletonLookupDescriptorProvider(@NonNull final LookupDescriptor lookupDescriptor)
{
this.lookupDescriptor = Optional.of(lookupDescriptor);
}
@Override
public Optional<LookupDescriptor> provideForScope(final LookupScope scope)
{
return lookupDescriptor;
}
}
@ToString
private static class MemoizingFunctionLookupDescriptorProvider implements LookupDescriptorProvider
{
private final MemoizingFunction<LookupScope, LookupDescriptor> providerFunctionMemoized;
private MemoizingFunctionLookupDescriptorProvider(@NonNull final Function<LookupScope, LookupDescriptor> providerFunction)
{
providerFunctionMemoized = Functions.memoizing(providerFunction);
}
@Override
public Optional<LookupDescriptor> provideForScope(final LookupScope scope)
{
return Optional.ofNullable(providerFunctionMemoized.apply(scope));
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\LookupDescriptorProviders.java | 1 |
请完成以下Java代码 | public List<VariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new VariableInitializingList();
}
return queryVariables;
}
public void setQueryVariables(List<VariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
@Override
public String getState() {
return null;
}
@Override
public Date getInProgressStartTime() {
return null;
}
@Override
public String getInProgressStartedBy() {
return null;
}
@Override
public Date getClaimTime() {
return null; | }
@Override
public String getClaimedBy() {
return null;
}
@Override
public Date getSuspendedTime() {
return null;
}
@Override
public String getSuspendedBy() {
return null;
}
@Override
public Date getInProgressStartDueDate() {
return null;
}
@Override
public void setInProgressStartDueDate(Date inProgressStartDueDate) {
// nothing
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntity.java | 1 |
请完成以下Java代码 | public boolean isReleasesEnabled() {
return this.releasesEnabled;
}
public void setReleasesEnabled(boolean releasesEnabled) {
this.releasesEnabled = releasesEnabled;
}
public boolean isSnapshotsEnabled() {
return this.snapshotsEnabled;
}
public void setSnapshotsEnabled(boolean snapshotsEnabled) {
this.snapshotsEnabled = snapshotsEnabled;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Repository other = (Repository) obj;
if (this.name == null) {
if (other.name != null) {
return false;
}
}
else if (!this.name.equals(other.name)) {
return false;
}
if (this.releasesEnabled != other.releasesEnabled) { | return false;
}
if (this.snapshotsEnabled != other.snapshotsEnabled) {
return false;
}
if (this.url == null) {
if (other.url != null) {
return false;
}
}
else if (!this.url.equals(other.url)) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((this.name == null) ? 0 : this.name.hashCode());
result = prime * result + (this.releasesEnabled ? 1231 : 1237);
result = prime * result + (this.snapshotsEnabled ? 1231 : 1237);
result = prime * result + ((this.url == null) ? 0 : this.url.hashCode());
return result;
}
@Override
public String toString() {
return new StringJoiner(", ", Repository.class.getSimpleName() + "[", "]").add("name='" + this.name + "'")
.add("url=" + this.url)
.add("releasesEnabled=" + this.releasesEnabled)
.add("snapshotsEnabled=" + this.snapshotsEnabled)
.toString();
}
} | repos\initializr-main\initializr-metadata\src\main\java\io\spring\initializr\metadata\Repository.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Comment {
@GeneratedValue(strategy = IDENTITY)
@Id
private Long id;
@JoinColumn(name = "article_id", referencedColumnName = "id", nullable = false)
@ManyToOne(fetch = EAGER)
private Article article;
@JoinColumn(name = "author_id", referencedColumnName = "id", nullable = false)
@ManyToOne(fetch = EAGER)
private User author;
@Column(name = "created_at")
@CreatedDate
private Instant createdAt;
@Column(name = "updated_at")
@LastModifiedDate
private Instant updatedAt;
@Column(name = "body", nullable = false)
private String body;
public Comment(Article article, User author, String body) {
this.article = article;
this.author = author;
this.body = body;
}
protected Comment() {
}
public Long getId() {
return id;
}
public User getAuthor() {
return author; | }
public Instant getCreatedAt() {
return createdAt;
}
public Instant getUpdatedAt() {
return updatedAt;
}
public String getBody() {
return body;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
var comment = (Comment) o;
return article.equals(comment.article) && author.equals(comment.author) && Objects.equals(createdAt, comment.createdAt) && body.equals(comment.body);
}
@Override
public int hashCode() {
return Objects.hash(article, author, createdAt, body);
}
} | repos\realworld-springboot-java-master\src\main\java\io\github\raeperd\realworld\domain\article\comment\Comment.java | 2 |
请完成以下Java代码 | public String getReferenceType() {
return referenceType;
}
@Override
public void setReferenceType(String referenceType) {
this.referenceType = referenceType;
}
@Override
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
@Override
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
@Override
public Map<String, Object> getProcessVariables() {
Map<String, Object> variables = new HashMap<>();
if (queryVariables != null) {
for (HistoricVariableInstanceEntity variableInstance : queryVariables) {
if (variableInstance.getId() != null && variableInstance.getTaskId() == null) {
variables.put(variableInstance.getName(), variableInstance.getValue());
}
}
}
return variables;
}
@Override
public List<HistoricVariableInstanceEntity> getQueryVariables() {
if (queryVariables == null && Context.getCommandContext() != null) {
queryVariables = new HistoricVariableInitializingList();
}
return queryVariables;
} | @Override
public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
// common methods //////////////////////////////////////////////////////////
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("HistoricProcessInstanceEntity[id=").append(getId())
.append(", definition=").append(getProcessDefinitionId());
if (superProcessInstanceId != null) {
sb.append(", superProcessInstanceId=").append(superProcessInstanceId);
}
if (referenceId != null) {
sb.append(", referenceId=").append(referenceId)
.append(", referenceType=").append(referenceType);
}
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricProcessInstanceEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setDetailValue (java.lang.String DetailValue)
{
set_Value (COLUMNNAME_DetailValue, DetailValue);
}
/** Get Value.
@return Value */
@Override
public java.lang.String getDetailValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_DetailValue);
}
/** Set External issue details.
@param S_ExternalIssueDetail_ID External issue details */
@Override
public void setS_ExternalIssueDetail_ID (int S_ExternalIssueDetail_ID)
{
if (S_ExternalIssueDetail_ID < 1)
set_ValueNoCheck (COLUMNNAME_S_ExternalIssueDetail_ID, null);
else
set_ValueNoCheck (COLUMNNAME_S_ExternalIssueDetail_ID, Integer.valueOf(S_ExternalIssueDetail_ID));
}
/** Get External issue details.
@return External issue details */
@Override
public int getS_ExternalIssueDetail_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_ExternalIssueDetail_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.serviceprovider.model.I_S_Issue getS_Issue()
{
return get_ValueAsPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class);
}
@Override | public void setS_Issue(de.metas.serviceprovider.model.I_S_Issue S_Issue)
{
set_ValueFromPO(COLUMNNAME_S_Issue_ID, de.metas.serviceprovider.model.I_S_Issue.class, S_Issue);
}
/** Set Issue.
@param S_Issue_ID Issue */
@Override
public void setS_Issue_ID (int S_Issue_ID)
{
if (S_Issue_ID < 1)
set_Value (COLUMNNAME_S_Issue_ID, null);
else
set_Value (COLUMNNAME_S_Issue_ID, Integer.valueOf(S_Issue_ID));
}
/** Get Issue.
@return Issue */
@Override
public int getS_Issue_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_S_Issue_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Art.
@param Type Art */
@Override
public void setType (java.lang.String Type)
{
set_ValueNoCheck (COLUMNNAME_Type, Type);
}
/** Get Art.
@return Art */
@Override
public java.lang.String getType ()
{
return (java.lang.String)get_Value(COLUMNNAME_Type);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_ExternalIssueDetail.java | 2 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.add("inoutCount", inoutCount)
.add("storeInOuts", storeInOuts)
.add("inouts", inoutsRO)
.toString();
}
@Override
public void addInOut(final I_M_InOut inOut)
{
if (storeInOuts)
{
// Avoid an internal transaction name to slip out to external world
InterfaceWrapperHelper.setTrxName(inOut, ITrx.TRXNAME_ThreadInherited);
inouts.add(inOut);
}
inoutCount++;
}
@Override
public List<I_M_InOut> getInOuts()
{
if (!storeInOuts) | {
throw new AdempiereException("Cannot provide the generated shipments because the result was not configured to retain them");
}
return inoutsRO;
}
@Override
public int getInOutCount()
{
if (storeInOuts)
{
return inouts.size();
}
return inoutCount;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\api\impl\DefaultInOutGenerateResult.java | 1 |
请完成以下Java代码 | public Class<? extends BaseElement> getHandledType() {
return StartEvent.class;
}
@Override
protected void executeParse(BpmnParse bpmnParse, StartEvent element) {
if (element.getSubProcess() != null && element.getSubProcess() instanceof EventSubProcess) {
if (CollectionUtil.isNotEmpty(element.getEventDefinitions())) {
EventDefinition eventDefinition = element.getEventDefinitions().get(0);
if (eventDefinition instanceof MessageEventDefinition) {
MessageEventDefinition messageDefinition = (MessageEventDefinition) eventDefinition;
BpmnModel bpmnModel = bpmnParse.getBpmnModel();
String messageRef = messageDefinition.getMessageRef();
if (bpmnModel.containsMessageId(messageRef)) {
Message message = bpmnModel.getMessage(messageRef);
messageDefinition.setMessageRef(message.getName());
messageDefinition.setExtensionElements(message.getExtensionElements());
}
element.setBehavior(
bpmnParse
.getActivityBehaviorFactory()
.createEventSubProcessMessageStartEventActivityBehavior(element, messageDefinition)
);
} else if (eventDefinition instanceof ErrorEventDefinition) {
element.setBehavior(
bpmnParse
.getActivityBehaviorFactory()
.createEventSubProcessErrorStartEventActivityBehavior(element)
);
}
}
} else if (CollectionUtil.isEmpty(element.getEventDefinitions())) {
element.setBehavior(bpmnParse.getActivityBehaviorFactory().createNoneStartEventActivityBehavior(element));
} | if (
element.getSubProcess() == null &&
(CollectionUtil.isEmpty(element.getEventDefinitions()) ||
bpmnParse.getCurrentProcess().getInitialFlowElement() == null)
) {
bpmnParse.getCurrentProcess().setInitialFlowElement(element);
}
checkStartFormKey(bpmnParse.getCurrentProcessDefinition(), element);
}
private void checkStartFormKey(ProcessDefinitionEntity processDefinition, StartEvent startEvent) {
if (StringUtils.isNotEmpty(startEvent.getFormKey())) {
processDefinition.setStartFormKey(true);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\StartEventParseHandler.java | 1 |
请完成以下Java代码 | public class UnArchiveRecordHandler implements INoDataFoundHandler
{
private static final transient Logger logger = LogManager.getLogger(UnArchiveRecordHandler.class);
public static UnArchiveRecordHandler INSTANCE = new UnArchiveRecordHandler();
private UnArchiveRecordHandler()
{
}
/**
* This method attempts to load the record using {@link DLMConnectionCustomizer#seeThemAllCustomizer()}.
* If this succeeds and the record's {@code DLM_Level} is not {@link IMigratorService#DLM_Level_LIVE}, it will set the record's level to that value and save the record.
*
* @param tableName the table name to load from. May be empty or null. In that case, the metohd will return {@code false}.
* @param ids the IDs to load. May be {@code null}, not-int or the size might be not equal to one. In those cases, the method returns {@code false}.
*/
@Override
public boolean invoke(final String tableName, final Object[] ids, final IContextAware ctx)
{
// do some basic checking
if (Check.isEmpty(tableName, true))
{
return false;
}
if (ids == null || ids.length != 1 || ids[0] == null)
{
return false;
}
if (!(ids[0] instanceof Integer))
{
return false;
}
final Mutable<Boolean> unArchiveWorked = new Mutable<>(false);
// attempt to load the record
final IConnectionCustomizerService connectionCustomizerService = Services.get(IConnectionCustomizerService.class);
try (final AutoCloseable customizer = connectionCustomizerService.registerTemporaryCustomizer(DLMConnectionCustomizer.seeThemAllCustomizer()))
{
Services.get(ITrxManager.class).runInNewTrx(new TrxRunnable()
{ | @Override
public void run(final String localTrxName) throws Exception
{
final PlainContextAware localCtx = PlainContextAware.newWithTrxName(ctx.getCtx(), localTrxName);
final TableRecordReference reference = TableRecordReference.of(tableName, (int)ids[0]);
final IDLMAware model = reference.getModel(localCtx, IDLMAware.class);
if (model == null)
{
logger.info("Unable to load record for reference={}; returning false.", reference);
return;
}
if (model.getDLM_Level() == IMigratorService.DLM_Level_LIVE)
{
logger.info("The record could be loaded, but already had DLM_Level={}; returning false; reference={}; ", IMigratorService.DLM_Level_LIVE, reference);
return;
}
logger.info("Setting DLM_Level to {} for {}", IMigratorService.DLM_Level_LIVE, reference);
model.setDLM_Level(IMigratorService.DLM_Level_LIVE);
InterfaceWrapperHelper.save(model);
unArchiveWorked.setValue(true);
}
});
return unArchiveWorked.getValue();
}
catch (final Exception e)
{
throw AdempiereException.wrapIfNeeded(e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\po\UnArchiveRecordHandler.java | 1 |
请完成以下Java代码 | public void setC_Country_ID (int C_Country_ID)
{
if (C_Country_ID < 1)
set_Value (COLUMNNAME_C_Country_ID, null);
else
set_Value (COLUMNNAME_C_Country_ID, Integer.valueOf(C_Country_ID));
}
/** Get Land.
@return Land
*/
@Override
public int getC_Country_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Country_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Country area assign.
@param C_CountryArea_Assign_ID Country area assign */
@Override
public void setC_CountryArea_Assign_ID (int C_CountryArea_Assign_ID)
{
if (C_CountryArea_Assign_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_CountryArea_Assign_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CountryArea_Assign_ID, Integer.valueOf(C_CountryArea_Assign_ID));
}
/** Get Country area assign.
@return Country area assign */
@Override
public int getC_CountryArea_Assign_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CountryArea_Assign_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_C_CountryArea getC_CountryArea() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_C_CountryArea_ID, org.compiere.model.I_C_CountryArea.class);
}
@Override
public void setC_CountryArea(org.compiere.model.I_C_CountryArea C_CountryArea)
{
set_ValueFromPO(COLUMNNAME_C_CountryArea_ID, org.compiere.model.I_C_CountryArea.class, C_CountryArea);
}
/** Set Country Area.
@param C_CountryArea_ID Country Area */
@Override
public void setC_CountryArea_ID (int C_CountryArea_ID)
{
if (C_CountryArea_ID < 1) | set_ValueNoCheck (COLUMNNAME_C_CountryArea_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_CountryArea_ID, Integer.valueOf(C_CountryArea_ID));
}
/** Get Country Area.
@return Country Area */
@Override
public int getC_CountryArea_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_CountryArea_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Gültig ab.
@param ValidFrom
Gültig ab inklusiv (erster Tag)
*/
@Override
public void setValidFrom (java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Gültig ab.
@return Gültig ab inklusiv (erster Tag)
*/
@Override
public java.sql.Timestamp getValidFrom ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Gültig bis.
@param ValidTo
Gültig bis inklusiv (letzter Tag)
*/
@Override
public void setValidTo (java.sql.Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Gültig bis.
@return Gültig bis inklusiv (letzter Tag)
*/
@Override
public java.sql.Timestamp getValidTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CountryArea_Assign.java | 1 |
请完成以下Java代码 | public ChangePlanItemStateBuilder childInstanceTaskVariable(String planItemDefinitionId, String name, Object value) {
if (!this.childInstanceTaskVariables.containsKey(planItemDefinitionId)) {
this.childInstanceTaskVariables.put(planItemDefinitionId, new HashMap<>());
}
this.childInstanceTaskVariables.get(planItemDefinitionId).put(name, value);
return this;
}
@Override
public ChangePlanItemStateBuilder childInstanceTaskVariables(String planItemDefinitionId, Map<String, Object> variables) {
if (!this.childInstanceTaskVariables.containsKey(planItemDefinitionId)) {
this.childInstanceTaskVariables.put(planItemDefinitionId, new HashMap<>());
}
this.childInstanceTaskVariables.get(planItemDefinitionId).putAll(variables);
return this;
}
@Override
public void changeState() {
if (runtimeService == null) {
throw new FlowableException("CmmnRuntimeService cannot be null, Obtain your builder instance from the CmmnRuntimeService to access this feature");
}
runtimeService.changePlanItemState(this);
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public Set<ActivatePlanItemDefinitionMapping> getActivatePlanItemDefinitions() {
return activatePlanItemDefinitions;
}
public Set<MoveToAvailablePlanItemDefinitionMapping> getChangeToAvailableStatePlanItemDefinitions() {
return changeToAvailableStatePlanItemDefinitions;
}
public Set<TerminatePlanItemDefinitionMapping> getTerminatePlanItemDefinitions() {
return terminatePlanItemDefinitions; | }
public Set<WaitingForRepetitionPlanItemDefinitionMapping> getWaitingForRepetitionPlanItemDefinitions() {
return waitingForRepetitionPlanItemDefinitions;
}
public Set<RemoveWaitingForRepetitionPlanItemDefinitionMapping> getRemoveWaitingForRepetitionPlanItemDefinitions() {
return removeWaitingForRepetitionPlanItemDefinitions;
}
public Set<ChangePlanItemIdMapping> getChangePlanItemIds() {
return changePlanItemIds;
}
public Set<ChangePlanItemIdWithDefinitionIdMapping> getChangePlanItemIdsWithDefinitionId() {
return changePlanItemIdsWithDefinitionId;
}
public Set<ChangePlanItemDefinitionWithNewTargetIdsMapping> getChangePlanItemDefinitionWithNewTargetIds() {
return changePlanItemDefinitionWithNewTargetIds;
}
public Map<String, Object> getCaseVariables() {
return caseVariables;
}
public Map<String, Map<String, Object>> getChildInstanceTaskVariables() {
return childInstanceTaskVariables;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\ChangePlanItemStateBuilderImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<BatchPart> findBatchPartsByBatchIdAndStatus(String batchId, String status) {
return dataManager.findBatchPartsByBatchIdAndStatus(batchId, status);
}
@Override
public List<BatchPart> findBatchPartsByScopeIdAndType(String scopeId, String scopeType) {
return dataManager.findBatchPartsByScopeIdAndType(scopeId, scopeType);
}
@Override
public List<BatchPart> findBatchPartsByQueryCriteria(BatchPartQuery batchPartQuery) {
return dataManager.findBatchPartsByQueryCriteria((BatchPartQueryImpl) batchPartQuery);
}
@Override
public long findBatchPartCountByQueryCriteria(BatchPartQuery batchPartQuery) {
return dataManager.findBatchPartCountByQueryCriteria((BatchPartQueryImpl) batchPartQuery);
}
@Override
public BatchPartEntity createBatchPart(BatchEntity parentBatch, String status, String scopeId, String subScopeId, String scopeType) {
BatchPartEntity batchPartEntity = dataManager.create();
batchPartEntity.setBatchId(parentBatch.getId());
batchPartEntity.setType(parentBatch.getBatchType());
batchPartEntity.setBatchType(parentBatch.getBatchType());
batchPartEntity.setScopeId(scopeId);
batchPartEntity.setSubScopeId(subScopeId);
batchPartEntity.setScopeType(scopeType);
batchPartEntity.setSearchKey(parentBatch.getBatchSearchKey());
batchPartEntity.setSearchKey2(parentBatch.getBatchSearchKey2());
batchPartEntity.setBatchSearchKey(parentBatch.getBatchSearchKey());
batchPartEntity.setBatchSearchKey2(parentBatch.getBatchSearchKey2());
batchPartEntity.setStatus(status);
if (parentBatch.getTenantId() != null) {
batchPartEntity.setTenantId(parentBatch.getTenantId());
}
batchPartEntity.setCreateTime(getClock().getCurrentTime());
insert(batchPartEntity); | return batchPartEntity;
}
@Override
public BatchPartEntity completeBatchPart(String batchPartId, String status, String resultJson) {
BatchPartEntity batchPartEntity = getBatchPartEntityManager().findById(batchPartId);
batchPartEntity.setCompleteTime(getClock().getCurrentTime());
batchPartEntity.setStatus(status);
batchPartEntity.setResultDocumentJson(resultJson, serviceConfiguration.getEngineName());
return batchPartEntity;
}
@Override
public void deleteBatchPartEntityAndResources(BatchPartEntity batchPartEntity) {
ByteArrayRef resultDocRefId = batchPartEntity.getResultDocRefId();
if (resultDocRefId != null && resultDocRefId.getId() != null) {
resultDocRefId.delete(serviceConfiguration.getEngineName());
}
delete(batchPartEntity);
}
protected BatchPartEntityManager getBatchPartEntityManager() {
return serviceConfiguration.getBatchPartEntityManager();
}
} | repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\impl\persistence\entity\BatchPartEntityManagerImpl.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private File geImageFile(@NonNull final PrintFormatId printFormatId)
{
final AttachmentEntryId attachmentEntryId = getFirstAttachmentEntryIdByPrintFormatId(printFormatId);
if(attachmentEntryId == null)
{
logger.warn("Cannot find image for {}, please add a file to the Print format. Returning empty PNG file", this);
return ImageUtils.getEmptyPNGFile();
}
else
{
final byte[] data = attachmentEntryService.retrieveData(attachmentEntryId);
return ImageUtils.createTempPNGFile("attachmentEntry", data);
}
}
/**
* get one attachment entry; does not matter if are several
*/
@Nullable
private AttachmentEntryId getFirstAttachmentEntryIdByPrintFormatId(@NonNull final PrintFormatId printFormatId)
{
final List<AttachmentEntry> entries = attachmentEntryService.getByReferencedRecord(TableRecordReference.of(I_AD_PrintFormat.Table_Name, printFormatId));
if (!entries.isEmpty())
{
final AttachmentEntry entry = entries.get(0);
return entry.getId();
}
else
{
return null;
}
}
/**
* @return true if given resourceName is an attachment image | */
private boolean isAttachmentImageResourceName(final String resourceName)
{
// Skip if no resourceName
if (resourceName == null || resourceName.isEmpty())
{
return false;
}
// Check if our resource name ends with one of our predefined matchers
for (final String resourceNameEndsWithMatcher : resourceNameEndsWithMatchers)
{
if (resourceName.endsWith(resourceNameEndsWithMatcher))
{
return true;
}
}
// Fallback: not a attachment resource
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\class_loader\images\attachment\AttachmentImageFileClassLoaderHook.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class User {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
@Column(unique = true)
private String username;
private String email;
private String password;
private String role;
private String address;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) { | this.password = password;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
} | repos\E-commerce-project-springBoot-master2\JtProject\src\main\java\com\jtspringproject\JtSpringProject\models\User.java | 2 |
请完成以下Java代码 | protected Void execute(CommandContext commandContext, TaskEntity task) {
boolean assignedToNoOne = false;
if (IdentityLinkType.ASSIGNEE.equals(identityType)) {
commandContext.getTaskEntityManager().changeTaskAssignee(task, identityId);
assignedToNoOne = identityId == null;
} else if (IdentityLinkType.OWNER.equals(identityType)) {
commandContext.getTaskEntityManager().changeTaskOwner(task, identityId);
} else if (IDENTITY_USER == identityIdType) {
task.addUserIdentityLink(identityId, identityType, details);
} else if (IDENTITY_GROUP == identityIdType) {
task.addGroupIdentityLink(identityId, identityType);
}
boolean forceNullUserId = false;
if (assignedToNoOne) {
// ACT-1317: Special handling when assignee is set to NULL, a | // CommentEntity notifying of assignee-delete should be created
forceNullUserId = true;
}
if (IDENTITY_USER == identityIdType) {
commandContext
.getHistoryManager()
.createUserIdentityLinkComment(taskId, identityId, identityType, true, forceNullUserId);
} else {
commandContext.getHistoryManager().createGroupIdentityLinkComment(taskId, identityId, identityType, true);
}
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\AddIdentityLinkCmd.java | 1 |
请完成以下Java代码 | private static ProductId getSingleProductId(final HuId huId)
{
final I_M_HU hu = Services.get(IHandlingUnitsDAO.class).getById(huId);
final Set<ProductId> productIds = Services.get(IHUContextFactory.class)
.createMutableHUContext()
.getHUStorageFactory()
.getStorage(hu)
.getProductStorages()
.stream()
.map(IHUProductStorage::getProductId)
.distinct()
.collect(ImmutableSet.toImmutableSet());
if (productIds.isEmpty())
{
throw new AdempiereException("Empty HUs are not allowed");
}
if (productIds.size() > 1)
{
throw new AdempiereException("Multi product HUs are not allowed");
}
return productIds.iterator().next();
}
public LookupValuesList getPickingSlotValues(@NonNull final LookupDataSourceContext context)
{
if (shipmentScheduleId == null)
{
return LookupValuesList.EMPTY;
}
final IShipmentScheduleEffectiveBL shipmentScheduleEffectiveBL = Services.get(IShipmentScheduleEffectiveBL.class);
final I_M_ShipmentSchedule shipmentSchedule = Services.get(IShipmentSchedulePA.class).getById(shipmentScheduleId);
final PickingSlotQuery pickingSlotQuery = PickingSlotQuery.builder()
.availableForBPartnerId(shipmentScheduleEffectiveBL.getBPartnerId(shipmentSchedule))
.availableForBPartnerLocationId(shipmentScheduleEffectiveBL.getBPartnerLocationId(shipmentSchedule))
.build();
final List<I_M_PickingSlot> availablePickingSlots = Services.get(IPickingSlotDAO.class).retrievePickingSlots(pickingSlotQuery);
return availablePickingSlots.stream()
.map(pickingSlot -> IntegerLookupValue.of(pickingSlot.getM_PickingSlot_ID(), createPickingSlotLabel(pickingSlot)))
.collect(LookupValuesList.collect());
}
private String createPickingSlotLabel(@NonNull final I_M_PickingSlot pickingslot)
{
final StringBuilder result = new StringBuilder(pickingslot.getPickingSlot());
final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(pickingslot.getC_BPartner_ID());
if (bpartnerId != null)
{
final IBPartnerDAO bpartnersRepo = Services.get(IBPartnerDAO.class);
final I_C_BPartner bpartner = bpartnersRepo.getById(bpartnerId);
result.append("_").append(bpartner.getName()).append("_").append(bpartner.getValue());
}
return result.toString();
} | public Object getDefaultValue(final IProcessDefaultParameter parameter)
{
if (PARAM_M_ShipmentSchedule_ID.equals(parameter.getColumnName()))
{
final ShipmentScheduleId defaultShipmentScheduleId = getDefaultShipmentScheduleId();
if (defaultShipmentScheduleId != null)
{
return defaultShipmentScheduleId.getRepoId();
}
}
// Fallback
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
private ShipmentScheduleId getDefaultShipmentScheduleId()
{
if (salesOrderLineId == null)
{
return null;
}
return Services.get(IShipmentSchedulePA.class).getShipmentScheduleIdByOrderLineId(salesOrderLineId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_Pick_ParametersFiller.java | 1 |
请完成以下Java代码 | public HuId getHUId()
{
return huId;
}
@Override
public BPartnerId getBPartnerId()
{
return partnerId;
}
@Override
public HuUnitType getHUUnitType()
{
return huUnitType;
} | @Override
public boolean isTopLevel()
{
return topLevel;
}
@Override
public List<HUToReport> getIncludedHUs()
{
return row.streamIncludedHUReportAwareRows()
.map(HUReportAwareViewRowAsHUToReport::of)
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\report\HUReportAwareViewRowAsHUToReport.java | 1 |
请完成以下Java代码 | private Set<ShipmentScheduleId> extractShipmentScheduleIds(final TableRecordReferenceSet recordRefs)
{
if (recordRefs.isEmpty())
{
return ImmutableSet.of();
}
final Set<ShipmentScheduleId> shipmentScheduleIds = new HashSet<>();
final Set<PickingCandidateId> pickingCandidateIds = new HashSet<>();
for (TableRecordReference recordRef : recordRefs)
{
final String tableName = recordRef.getTableName();
if (I_M_ShipmentSchedule.Table_Name.equals(tableName))
{
shipmentScheduleIds.add(ShipmentScheduleId.ofRepoId(recordRef.getRecord_ID())); | }
else if (I_M_Picking_Candidate.Table_Name.equals(tableName))
{
pickingCandidateIds.add(PickingCandidateId.ofRepoId(recordRef.getRecord_ID()));
}
}
if (!pickingCandidateIds.isEmpty())
{
shipmentScheduleIds.addAll(pickingCandidateRepository.getShipmentScheduleIdsByPickingCandidateIds(pickingCandidateIds));
}
return shipmentScheduleIds;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\PickingTerminalViewInvalidationAdvisor.java | 1 |
请完成以下Java代码 | public boolean addAll(Collection<? extends DmnDecisionResultEntries> c) {
throw new UnsupportedOperationException("decision result is immutable");
}
@Override
public boolean addAll(int index, Collection<? extends DmnDecisionResultEntries> c) {
throw new UnsupportedOperationException("decision result is immutable");
}
@Override
public boolean removeAll(Collection<?> c) {
throw new UnsupportedOperationException("decision result is immutable");
}
@Override
public boolean retainAll(Collection<?> c) {
throw new UnsupportedOperationException();
}
@Override
public void clear() {
throw new UnsupportedOperationException("decision result is immutable");
}
@Override
public DmnDecisionResultEntries set(int index, DmnDecisionResultEntries element) {
throw new UnsupportedOperationException("decision result is immutable");
}
@Override
public void add(int index, DmnDecisionResultEntries element) {
throw new UnsupportedOperationException("decision result is immutable");
}
@Override
public DmnDecisionResultEntries remove(int index) {
throw new UnsupportedOperationException("decision result is immutable");
} | @Override
public int indexOf(Object o) {
return ruleResults.indexOf(o);
}
@Override
public int lastIndexOf(Object o) {
return ruleResults.lastIndexOf(o);
}
@Override
public ListIterator<DmnDecisionResultEntries> listIterator() {
return asUnmodifiableList().listIterator();
}
@Override
public ListIterator<DmnDecisionResultEntries> listIterator(int index) {
return asUnmodifiableList().listIterator(index);
}
@Override
public List<DmnDecisionResultEntries> subList(int fromIndex, int toIndex) {
return asUnmodifiableList().subList(fromIndex, toIndex);
}
@Override
public String toString() {
return ruleResults.toString();
}
protected List<DmnDecisionResultEntries> asUnmodifiableList() {
return Collections.unmodifiableList(ruleResults);
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultImpl.java | 1 |
请完成以下Java代码 | public abstract class LabelImpl extends NodeImpl implements Label {
protected static ChildElement<Bounds> boundsChild;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Label.class, DI_ELEMENT_LABEL)
.namespaceUri(DI_NS)
.extendsType(Node.class)
.abstractType();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
boundsChild = sequenceBuilder.element(Bounds.class)
.build(); | typeBuilder.build();
}
public LabelImpl(ModelTypeInstanceContext instanceContext) {
super(instanceContext);
}
public Bounds getBounds() {
return boundsChild.getChild(this);
}
public void setBounds(Bounds bounds) {
boundsChild.setChild(this, bounds);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\di\LabelImpl.java | 1 |
请完成以下Java代码 | public void setKafkaHeaderMapper(KafkaHeaderMapper headerMapper) {
Assert.notNull(headerMapper, "'headerMapper' cannot be null");
this.headerMapper = headerMapper;
}
@Override
public MessageListener getDelegate() {
return this.delegate;
}
@Override
@SuppressWarnings("unchecked")
public void onMessage(ConsumerRecord receivedRecord, @Nullable Acknowledgment acknowledgment, @Nullable Consumer consumer) {
ConsumerRecord convertedConsumerRecord = convertConsumerRecord(receivedRecord);
if (this.delegate instanceof AcknowledgingConsumerAwareMessageListener) {
this.delegate.onMessage(convertedConsumerRecord, acknowledgment, consumer);
}
else if (this.delegate instanceof ConsumerAwareMessageListener) {
this.delegate.onMessage(convertedConsumerRecord, consumer);
}
else if (this.delegate instanceof AcknowledgingMessageListener) {
this.delegate.onMessage(convertedConsumerRecord, acknowledgment);
}
else {
this.delegate.onMessage(convertedConsumerRecord);
}
}
private ConsumerRecord convertConsumerRecord(ConsumerRecord receivedRecord) {
Map<String, Object> headerMap = new HashMap<>();
if (this.headerMapper != null) {
this.headerMapper.toHeaders(receivedRecord.headers(), headerMap); | }
Message message = new GenericMessage<>(receivedRecord.value(), headerMap);
Object convertedPayload = this.messageConverter.fromMessage(message, this.desiredValueType);
if (convertedPayload == null) {
throw new MessageConversionException(message, "Message cannot be converted by used MessageConverter");
}
return rebuildConsumerRecord(receivedRecord, convertedPayload);
}
@SuppressWarnings("unchecked")
private static ConsumerRecord rebuildConsumerRecord(ConsumerRecord receivedRecord, Object convertedPayload) {
return new ConsumerRecord(
receivedRecord.topic(),
receivedRecord.partition(),
receivedRecord.offset(),
receivedRecord.timestamp(),
receivedRecord.timestampType(),
receivedRecord.serializedKeySize(),
receivedRecord.serializedValueSize(),
receivedRecord.key(),
convertedPayload,
receivedRecord.headers(),
receivedRecord.leaderEpoch()
);
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\ConvertingMessageListener.java | 1 |
请完成以下Java代码 | public String toString()
{
return getClass().getSimpleName() + "["
+ children
+ "]";
}
public CompositeScriptScanner addScriptScanner(final IScriptScanner scriptScanner)
{
if (scriptScanner == null)
{
throw new IllegalArgumentException("scriptScanner is null");
}
if (children.contains(scriptScanner))
{
return this;
}
children.add(scriptScanner);
return this; | }
@Override
protected IScriptScanner retrieveNextChildScriptScanner()
{
final int nextIndex = currentIndex + 1;
if (nextIndex >= children.size())
{
return null;
}
final IScriptScanner nextScanner = children.get(nextIndex);
currentIndex = nextIndex;
return nextScanner;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\CompositeScriptScanner.java | 1 |
请完成以下Java代码 | private void readValues(DSLContext context) {
Result<Record> authors = getAll(
context,
Author.AUTHOR
);
authors.forEach(author -> {
Integer id = author.getValue(Author.AUTHOR.ID);
String firstName = author.getValue(Author.AUTHOR.FIRST_NAME);
String lastName = author.getValue(Author.AUTHOR.LAST_NAME);
Integer age = author.getValue(Author.AUTHOR.AGE);
System.out.printf("Author %s %s has id: %d and age: %d%n", firstName, lastName, id, age);
});
Result<Record> articles = getFields(
context,
Author.AUTHOR,
Article.ARTICLE.ID, Article.ARTICLE.TITLE
);
AuthorRecord author = getOne(
context,
Author.AUTHOR,
Author.AUTHOR.ID.eq(1)
);
} | private void updateValues(DSLContext context) {
HashMap<Field<String>, String> fieldsToUpdate = new HashMap<>();
fieldsToUpdate.put(Author.AUTHOR.FIRST_NAME, "David");
fieldsToUpdate.put(Author.AUTHOR.LAST_NAME, "Brown");
update(
context,
Author.AUTHOR,
fieldsToUpdate,
Author.AUTHOR.ID.eq(1)
);
ArticleRecord article = context.fetchOne(Article.ARTICLE, Article.ARTICLE.ID.eq(1));
article.setTitle("A New Article Title");
update(article);
}
private void deleteValues(DSLContext context) {
delete(
context,
Article.ARTICLE,
Article.ARTICLE.ID.eq(1)
);
AuthorRecord author = context.fetchOne(Author.AUTHOR, Author.AUTHOR.ID.eq(1));
delete(author);
}
} | repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\CrudExamples.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected String getEngineName() {
return asyncExecutor.getJobServiceConfiguration().getEngineName();
}
protected void unlockTimerJobs(Collection<TimerJobEntity> timerJobs) {
try {
if (!timerJobs.isEmpty()) {
commandExecutor.execute(new UnlockTimerJobsCmd(timerJobs, asyncExecutor.getJobServiceConfiguration()));
}
} catch (Throwable e) {
if (LOGGER.isDebugEnabled()) {
LOGGER.debug("Failed to unlock timer jobs during acquiring for engine {}. This is OK since they will be unlocked when the reset expired jobs thread runs", getEngineName(), e);
}
}
} | public void stop() {
synchronized (MONITOR) {
isInterrupted = true;
if (isWaiting.compareAndSet(true, false)) {
MONITOR.notifyAll();
}
}
}
public void setConfiguration(AcquireJobsRunnableConfiguration configuration) {
this.configuration = configuration;
}
} | repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\AcquireTimerJobsRunnable.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class ComputeNameAndGreetingRequest
{
@Nullable
String adLanguage;
@Value
@Builder
public static class Contact
{
@Nullable
GreetingId greetingId;
@Nullable
String firstName;
@Nullable
String lastName;
int seqNo;
boolean isDefaultContact;
boolean isMembershipContact;
}
@Singular @NonNull ImmutableList<Contact> contacts; | public Optional<Contact> getPrimaryContact()
{
final List<Contact> contactsOrderedPrimaryFirst = getContactsOrderedPrimaryFirst();
return !contactsOrderedPrimaryFirst.isEmpty()
? Optional.of(contactsOrderedPrimaryFirst.get(0))
: Optional.empty();
}
public List<Contact> getContactsOrderedPrimaryFirst()
{
return contacts.stream()
.sorted(Comparator.<Contact, Integer>comparing(contact -> contact.isDefaultContact() ? 0 : 1)
.thenComparing(Contact::getSeqNo))
.collect(ImmutableList.toImmutableList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\name\strategy\ComputeNameAndGreetingRequest.java | 2 |
请完成以下Java代码 | public void checkUnregisterDeployment() {
getAuthorizationManager().checkAuthorization(SystemPermissions.SET, Resources.SYSTEM);
}
@Override
public void checkDeleteMetrics() {
getAuthorizationManager().checkAuthorization(SystemPermissions.DELETE, Resources.SYSTEM);
}
@Override
public void checkDeleteTaskMetrics() {
getAuthorizationManager().checkAuthorization(SystemPermissions.DELETE, Resources.SYSTEM);
}
@Override
public void checkReadSchemaLog() {
getAuthorizationManager().checkAuthorization(SystemPermissions.READ, Resources.SYSTEM);
}
// helper ////////////////////////////////////////
protected AuthorizationManager getAuthorizationManager() {
return Context.getCommandContext().getAuthorizationManager(); | }
protected ProcessDefinitionEntity findLatestProcessDefinitionById(String processDefinitionId) {
return Context.getCommandContext().getProcessDefinitionManager().findLatestProcessDefinitionById(processDefinitionId);
}
protected DecisionDefinitionEntity findLatestDecisionDefinitionById(String decisionDefinitionId) {
return Context.getCommandContext().getDecisionDefinitionManager().findDecisionDefinitionById(decisionDefinitionId);
}
protected ExecutionEntity findExecutionById(String processInstanceId) {
return Context.getCommandContext().getExecutionManager().findExecutionById(processInstanceId);
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\auth\AuthorizationCommandChecker.java | 1 |
请完成以下Java代码 | public BigDecimal getMeasureActual ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MeasureActual);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_PA_SLA_Goal getPA_SLA_Goal() throws RuntimeException
{
return (I_PA_SLA_Goal)MTable.get(getCtx(), I_PA_SLA_Goal.Table_Name)
.getPO(getPA_SLA_Goal_ID(), get_TrxName()); }
/** Set SLA Goal.
@param PA_SLA_Goal_ID
Service Level Agreement Goal
*/
public void setPA_SLA_Goal_ID (int PA_SLA_Goal_ID)
{
if (PA_SLA_Goal_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_SLA_Goal_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_SLA_Goal_ID, Integer.valueOf(PA_SLA_Goal_ID));
}
/** Get SLA Goal.
@return Service Level Agreement Goal
*/
public int getPA_SLA_Goal_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Goal_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set SLA Measure.
@param PA_SLA_Measure_ID
Service Level Agreement Measure
*/
public void setPA_SLA_Measure_ID (int PA_SLA_Measure_ID)
{
if (PA_SLA_Measure_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_SLA_Measure_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_SLA_Measure_ID, Integer.valueOf(PA_SLA_Measure_ID));
}
/** Get SLA Measure.
@return Service Level Agreement Measure
*/
public int getPA_SLA_Measure_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_SLA_Measure_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
} | return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID.
@return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_SLA_Measure.java | 1 |
请完成以下Java代码 | public void append(final I_M_HU item)
{
list.add(item);
}
public I_M_HU current()
{
Check.assume(currentItemSet, "has current item");
return currentItem;
}
public void closeCurrent()
{
currentItemSet = false;
currentItem = null;
}
public boolean hasCurrent()
{
return currentItemSet;
}
public boolean hasNext()
{
final int size = list.size();
if (currentIndex < 0)
{
return size > 0;
}
else
{
return currentIndex + 1 < size;
}
}
public I_M_HU next()
{
// Calculate the next index | final int nextIndex;
if (currentIndex < 0)
{
nextIndex = 0;
}
else
{
nextIndex = currentIndex + 1;
}
// Make sure the new index is valid
final int size = list.size();
if (nextIndex >= size)
{
throw new NoSuchElementException("index=" + nextIndex + ", size=" + size);
}
// Update status
this.currentIndex = nextIndex;
this.currentItem = list.get(nextIndex);
this.currentItemSet = true;
return currentItem;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\util\HUListCursor.java | 1 |
请完成以下Java代码 | protected BigDecimal retrieveQtyInitial()
{
checkStaled();
//
// Calculate the initial Qty (i.e. Qty To Pick) as target Qty minus how much was picked and not delivered, minus how much was delivered
// NOTE: we cannot rely on QtyToDeliver because that one is about what it needs to be delivered *and* we are able to deliver it.
// But in our case we need to have how much is Picked but not delivered because we want to let the API/user to "un-pick" that quantity if they want.
final Capacity capacityTotal = getTotalCapacity();
final BigDecimal qtyTarget = capacityTotal.toBigDecimal();
BigDecimal qtyToPick = qtyTarget;
// NOTE: we shall consider QtyDelivered and QtyPickedNotDelivered only if the QtyToDeliver_Override is not set,
// because if it's set this is what we actually want to deliver, no matter what!
final boolean hasQtyToDeliverOverride = !InterfaceWrapperHelper.isNull(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver_Override);
if (!hasQtyToDeliverOverride)
{
final IShipmentScheduleAllocDAO shipmentScheduleAllocDAO = Services.get(IShipmentScheduleAllocDAO.class);
final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoId(shipmentSchedule.getM_ShipmentSchedule_ID());
final BigDecimal qtyPickedNotDelivered = shipmentScheduleAllocDAO.retrieveNotOnShipmentLineQty(shipmentScheduleId);
final BigDecimal qtyDelivered = shipmentSchedule.getQtyDelivered();
qtyToPick = qtyToPick.subtract(qtyPickedNotDelivered).subtract(qtyDelivered);
}
// NOTE: Qty to Pick is the actual storage qty
return qtyToPick;
}
@Override
protected Capacity retrieveTotalCapacity()
{
checkStaled();
//
// Get shipment schedule's target quantity (i.e. how much we need to deliver in total)
// * in case we have QtyToDeliver_Override we consider this right away
// * else we consider the QtyOrdered
final BigDecimal qtyTarget;
if (!InterfaceWrapperHelper.isNull(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_QtyToDeliver_Override))
{
qtyTarget = shipmentSchedule.getQtyToDeliver_Override();
}
else
{ | // task 09005: make sure the correct qtyOrdered is taken from the shipmentSchedule
final BigDecimal qtyOrdered = Services.get(IShipmentScheduleEffectiveBL.class).computeQtyOrdered(shipmentSchedule);
qtyTarget = qtyOrdered;
}
//
// Create the total capacity based on qtyTarget
final ProductId productId = ProductId.ofRepoId(shipmentSchedule.getM_Product_ID());
final I_C_UOM uom = shipmentScheduleBL.getUomOfProduct(shipmentSchedule);
return Capacity.createCapacity(
qtyTarget, // qty
productId, // product
uom, // uom
false // allowNegativeCapacity
);
}
@Override
protected void beforeMarkingStalled()
{
staled = true;
}
private final void checkStaled()
{
if (!staled)
{
return;
}
InterfaceWrapperHelper.refresh(shipmentSchedule);
staled = false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\impl\ShipmentScheduleQtyPickedProductStorage.java | 1 |
请完成以下Java代码 | public ServiceTaskBuilder builder() {
return new ServiceTaskBuilder((BpmnModelInstance) modelInstance, this);
}
public String getImplementation() {
return implementationAttribute.getValue(this);
}
public void setImplementation(String implementation) {
implementationAttribute.setValue(this, implementation);
}
public Operation getOperation() {
return operationRefAttribute.getReferenceTargetElement(this);
}
public void setOperation(Operation operation) {
operationRefAttribute.setReferenceTargetElement(this, operation);
}
/** camunda extensions */
public String getCamundaClass() {
return camundaClassAttribute.getValue(this);
}
public void setCamundaClass(String camundaClass) {
camundaClassAttribute.setValue(this, camundaClass);
}
public String getCamundaDelegateExpression() {
return camundaDelegateExpressionAttribute.getValue(this);
}
public void setCamundaDelegateExpression(String camundaExpression) {
camundaDelegateExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaExpression() {
return camundaExpressionAttribute.getValue(this);
} | public void setCamundaExpression(String camundaExpression) {
camundaExpressionAttribute.setValue(this, camundaExpression);
}
public String getCamundaResultVariable() {
return camundaResultVariableAttribute.getValue(this);
}
public void setCamundaResultVariable(String camundaResultVariable) {
camundaResultVariableAttribute.setValue(this, camundaResultVariable);
}
public String getCamundaTopic() {
return camundaTopicAttribute.getValue(this);
}
public void setCamundaTopic(String camundaTopic) {
camundaTopicAttribute.setValue(this, camundaTopic);
}
public String getCamundaType() {
return camundaTypeAttribute.getValue(this);
}
public void setCamundaType(String camundaType) {
camundaTypeAttribute.setValue(this, camundaType);
}
@Override
public String getCamundaTaskPriority() {
return camundaTaskPriorityAttribute.getValue(this);
}
@Override
public void setCamundaTaskPriority(String taskPriority) {
camundaTaskPriorityAttribute.setValue(this, taskPriority);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ServiceTaskImpl.java | 1 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_Channel[")
.append(get_ID()).append("]");
return sb.toString();
}
public I_AD_PrintColor getAD_PrintColor() throws RuntimeException
{
return (I_AD_PrintColor)MTable.get(getCtx(), I_AD_PrintColor.Table_Name)
.getPO(getAD_PrintColor_ID(), get_TrxName()); }
/** Set Print Color.
@param AD_PrintColor_ID
Color used for printing and display
*/
public void setAD_PrintColor_ID (int AD_PrintColor_ID)
{
if (AD_PrintColor_ID < 1)
set_Value (COLUMNNAME_AD_PrintColor_ID, null);
else
set_Value (COLUMNNAME_AD_PrintColor_ID, Integer.valueOf(AD_PrintColor_ID));
}
/** Get Print Color.
@return Color used for printing and display
*/
public int getAD_PrintColor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_PrintColor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Channel.
@param C_Channel_ID
Sales Channel
*/
public void setC_Channel_ID (int C_Channel_ID)
{
if (C_Channel_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Channel_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Channel_ID, Integer.valueOf(C_Channel_ID)); | }
/** Get Channel.
@return Sales Channel
*/
public int getC_Channel_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Channel_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Channel.java | 1 |
请完成以下Java代码 | public BigDecimal getTotalOpenBalance ()
{
final BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalOpenBalance);
if (bd == null)
{
return BigDecimal.ZERO;
}
return bd;
}
/** Set V_BPartnerCockpit_ID.
@param V_BPartnerCockpit_ID V_BPartnerCockpit_ID */
@Override
public void setV_BPartnerCockpit_ID (final int V_BPartnerCockpit_ID)
{
if (V_BPartnerCockpit_ID < 1)
{
set_ValueNoCheck (COLUMNNAME_V_BPartnerCockpit_ID, null);
}
else
{
set_ValueNoCheck (COLUMNNAME_V_BPartnerCockpit_ID, Integer.valueOf(V_BPartnerCockpit_ID));
}
}
/** Get V_BPartnerCockpit_ID.
@return V_BPartnerCockpit_ID */
@Override
public int getV_BPartnerCockpit_ID ()
{ | final Integer ii = (Integer)get_Value(COLUMNNAME_V_BPartnerCockpit_ID);
if (ii == null)
{
return 0;
}
return ii.intValue();
}
/** Set Suchschlüssel.
@param value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public void setvalue (final java.lang.String value)
{
set_Value (COLUMNNAME_value, value);
}
/** Get Suchschlüssel.
@return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein
*/
@Override
public java.lang.String getvalue ()
{
return (java.lang.String)get_Value(COLUMNNAME_value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_V_BPartnerCockpit.java | 1 |
请完成以下Java代码 | public void setLocalizedName(String localizedName) {
this.localizedName = localizedName;
}
@Override
public String getDescription() {
if (localizedDescription != null && localizedDescription.length() > 0) {
return localizedDescription;
} else {
return description;
}
}
public void setDescription(String description) {
this.description = description;
}
@Override
public Object getValue() {
return value;
}
public void setValue(Object value) {
this.value = value;
}
@Override
public String getType() { | return type;
}
public void setType(String type) {
this.type = type;
}
@Override
public String getDataObjectDefinitionKey() {
return dataObjectDefinitionKey;
}
public void setDataObjectDefinitionKey(String dataObjectDefinitionKey) {
this.dataObjectDefinitionKey = dataObjectDefinitionKey;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\DataObjectImpl.java | 1 |
请完成以下Java代码 | public boolean add(E e)
{
if (queue.size() < maxSize)
{ // 未达到最大容量,直接添加
queue.add(e);
return true;
}
else
{ // 队列已满
E peek = queue.peek();
if (queue.comparator().compare(e, peek) > 0)
{ // 将新元素与当前堆顶元素比较,保留较小的元素
queue.poll();
queue.add(e);
return true;
}
}
return false;
}
/**
* 添加许多元素
* @param collection
*/
public MaxHeap<E> addAll(Collection<E> collection)
{
for (E e : collection)
{
add(e);
}
return this;
}
/**
* 转为有序列表,自毁性操作
* @return
*/
public List<E> toList()
{
ArrayList<E> list = new ArrayList<E>(queue.size());
while (!queue.isEmpty()) | {
list.add(0, queue.poll());
}
return list;
}
@Override
public Iterator<E> iterator()
{
return queue.iterator();
}
public int size()
{
return queue.size();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\algorithm\MaxHeap.java | 1 |
请完成以下Java代码 | public synchronized void stop() {
if (started) {
started = false;
if (cleanerTask != null) {
cleanerTask.cancel(false);
cleanerTask = null;
}
}
}
/**
* Destroy "cleanup" scheduler.
*/
@Override
public synchronized void destroy() {
started = false;
schedExecutor.shutdownNow();
try {
schedExecutor.awaitTermination(5, TimeUnit.SECONDS);
} catch (InterruptedException e) {
log.warn("Destroying InMemoryRegistrationStore was interrupted.", e);
}
}
private class Cleaner implements Runnable {
@Override
public void run() {
try {
Collection<Registration> allRegs = new ArrayList<>();
try { | lock.readLock().lock();
allRegs.addAll(regsByEp.values());
} finally {
lock.readLock().unlock();
}
for (Registration reg : allRegs) {
if (!reg.isAlive()) {
// force de-registration
Deregistration removedRegistration = removeRegistration(reg.getId());
expirationListener.registrationExpired(removedRegistration.getRegistration(),
removedRegistration.getObservations());
}
}
} catch (Exception e) {
log.warn("Unexpected Exception while registration cleaning", e);
}
}
}
// boolean remove(Object key, Object value) exist only since java8
// So this method is here only while we want to support java 7
protected <K, V> boolean removeFromMap(Map<K, V> map, K key, V value) {
if (map.containsKey(key) && Objects.equals(map.get(key), value)) {
map.remove(key);
return true;
} else
return false;
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbInMemoryRegistrationStore.java | 1 |
请完成以下Java代码 | public Optional<I_C_BPartner_Location> getBPLocationById(@NonNull final BPartnerLocationId bpLocationId)
{
final int bpLocationRepoId = bpLocationId.getRepoId();
return getFirstBPLocationMatching(bplRecord -> bplRecord.getC_BPartner_Location_ID() == bpLocationRepoId);
}
public Optional<I_C_BPartner_Location> getFirstBPLocationMatching(@NonNull final BPartnerLocationMatchingKey matchingKey)
{
return getFirstBPLocationMatching(bpLocation -> isBPartnerLocationMatching(bpLocation, matchingKey));
}
private boolean isBPartnerLocationMatching(@NonNull final I_C_BPartner_Location bpLocation, @NonNull final BPartnerLocationMatchingKey matchingKey)
{
final BPartnerLocationMatchingKey bpLocationKey = BPartnerLocationMatchingKey.of(bpLocation.getC_Location());
return bpLocationKey.equals(matchingKey);
}
public Optional<I_C_BPartner_Location> getFirstBPLocationMatching(@NonNull final Predicate<I_C_BPartner_Location> filter)
{
return getOrLoadBPLocations()
.stream()
.filter(filter)
.findFirst();
}
private ArrayList<I_C_BPartner_Location> getOrLoadBPLocations()
{
if (bpLocations == null)
{
if (record.getC_BPartner_ID() > 0)
{
bpLocations = new ArrayList<>(bpartnersRepo.retrieveBPartnerLocations(record));
}
else
{
bpLocations = new ArrayList<>();
}
}
return bpLocations;
}
public void addAndSaveLocation(final I_C_BPartner_Location bpartnerLocation)
{
bpartnersRepo.save(bpartnerLocation);
final BPartnerLocationId bpartnerLocationId = BPartnerLocationId.ofRepoId(bpartnerLocation.getC_BPartner_ID(), bpartnerLocation.getC_BPartner_Location_ID());
if (!getBPLocationById(bpartnerLocationId).isPresent())
{
getOrLoadBPLocations().add(bpartnerLocation);
}
} | public Optional<I_AD_User> getContactById(final BPartnerContactId contactId)
{
return getOrLoadContacts()
.stream()
.filter(contact -> contact.getAD_User_ID() == contactId.getRepoId())
.findFirst();
}
private ArrayList<I_AD_User> getOrLoadContacts()
{
if (contacts == null)
{
if (record.getC_BPartner_ID() > 0)
{
contacts = new ArrayList<>(bpartnersRepo.retrieveContacts(record));
}
else
{
contacts = new ArrayList<>();
}
}
return contacts;
}
public BPartnerContactId addAndSaveContact(final I_AD_User contact)
{
bpartnersRepo.save(contact);
final BPartnerContactId contactId = BPartnerContactId.ofRepoId(contact.getC_BPartner_ID(), contact.getAD_User_ID());
if (!getContactById(contactId).isPresent())
{
getOrLoadContacts().add(contact);
}
return contactId;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnersCache.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<Book> getBook() {
List<Book> book = new ArrayList<>(books.values());
return book;
}
@ApiOperation(value="创建图书", notes="创建图书")
@ApiImplicitParam(name = "book", value = "图书详细实体", required = true, dataType = "Book")
@RequestMapping(value="", method=RequestMethod.POST)
public String postBook(@RequestBody Book book) {
books.put(book.getId(), book);
return "success";
}
@ApiOperation(value="获图书细信息", notes="根据url的id来获取详细信息")
@ApiImplicitParam(name = "id", value = "ID", required = true, dataType = "Long",paramType = "path")
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public Book getBook(@PathVariable Long id) {
return books.get(id);
}
@ApiOperation(value="更新信息", notes="根据url的id来指定更新图书信息")
@ApiImplicitParams({
@ApiImplicitParam(name = "id", value = "图书ID", required = true, dataType = "Long",paramType = "path"),
@ApiImplicitParam(name = "book", value = "图书实体book", required = true, dataType = "Book")
})
@RequestMapping(value="/{id}", method= RequestMethod.PUT)
public String putUser(@PathVariable Long id, @RequestBody Book book) {
Book book1 = books.get(id);
book1.setName(book.getName());
book1.setPrice(book.getPrice());
books.put(id, book1);
return "success"; | }
@ApiOperation(value="删除图书", notes="根据url的id来指定删除图书")
@ApiImplicitParam(name = "id", value = "图书ID", required = true, dataType = "Long",paramType = "path")
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
books.remove(id);
return "success";
}
@ApiIgnore//使用该注解忽略这个API
@RequestMapping(value = "/hi", method = RequestMethod.GET)
public String jsonTest() {
return " hi you!";
}
} | repos\SpringBootLearning-master\springboot-swagger\src\main\java\com\forezp\controller\BookContrller.java | 2 |
请完成以下Java代码 | public class ClockUtil {
/**
* Freezes the clock to a specified Date that will be returned by
* {@link #now()} and {@link #getCurrentTime()}
*
* @param currentTime
* the Date to freeze the clock at
*/
public static void setCurrentTime(Date currentTime) {
DateTimeUtils.setCurrentMillisFixed(currentTime.getTime());
}
public static void reset() {
resetClock();
}
public static Date getCurrentTime() {
return now();
}
public static Date now() {
return new Date(DateTimeUtils.currentTimeMillis());
}
/**
* Moves the clock by the given offset and keeps it running from that point
* on.
* | * @param offsetInMillis
* the offset to move the clock by
* @return the new 'now'
*/
public static Date offset(Long offsetInMillis) {
DateTimeUtils.setCurrentMillisOffset(offsetInMillis);
return new Date(DateTimeUtils.currentTimeMillis());
}
public static Date resetClock() {
DateTimeUtils.setCurrentMillisSystem();
return new Date(DateTimeUtils.currentTimeMillis());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\ClockUtil.java | 1 |
请完成以下Java代码 | public Connection getConnection(Object tenantIdentifier) throws SQLException {
final Connection connection = dataSource.getConnection();
connection.setSchema(tenantIdentifier.toString());
return connection;
}
/*
* (non-Javadoc)
* @see org.hibernate.engine.jdbc.connections.spi.MultiTenantConnectionProvider#releaseConnection(java.lang.Object, java.sql.Connection)
*/
@Override
public void releaseConnection(Object tenantIdentifier, Connection connection) throws SQLException {
connection.setSchema("PUBLIC");
connection.close();
}
@Override | public boolean supportsAggressiveRelease() {
return false;
}
@Override
public boolean isUnwrappableAs(Class<?> aClass) {
return false;
}
@Override
public <T> T unwrap(Class<T> aClass) {
throw new UnsupportedOperationException("Can't unwrap this.");
}
@Override
public void customize(Map<String, Object> hibernateProperties) {
hibernateProperties.put(AvailableSettings.MULTI_TENANT_CONNECTION_PROVIDER, this);
}
} | repos\spring-data-examples-main\jpa\multitenant\schema\src\main\java\example\springdata\jpa\hibernatemultitenant\schema\ExampleConnectionProvider.java | 1 |
请完成以下Java代码 | protected byte[] serializeIds(List<String> ids) {
try {
String[] toStore = ids.toArray(new String[] {});
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream out = new ObjectOutputStream(baos);
out.writeObject(toStore);
return baos.toByteArray();
} catch (IOException ioe) {
throw new ActivitiException("Unexpected exception when serializing JPA id's", ioe);
}
}
protected String[] deserializeIds(byte[] bytes) {
try { | ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream in = new ObjectInputStream(bais);
Object read = in.readObject();
if (!(read instanceof String[])) {
throw new ActivitiIllegalArgumentException("Deserialized value is not an array of ID's: " + read);
}
return (String[]) read;
} catch (IOException ioe) {
throw new ActivitiException("Unexpected exception when deserializing JPA id's", ioe);
} catch (ClassNotFoundException e) {
throw new ActivitiException("Unexpected exception when deserializing JPA id's", e);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\JPAEntityListVariableType.java | 1 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setAD_Printer_ID (int AD_Printer_ID)
{
if (AD_Printer_ID < 1)
set_Value (COLUMNNAME_AD_Printer_ID, null);
else
set_Value (COLUMNNAME_AD_Printer_ID, Integer.valueOf(AD_Printer_ID));
}
@Override
public int getAD_Printer_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_ID);
}
@Override
public void setAD_Printer_Tray_ID (int AD_Printer_Tray_ID)
{
if (AD_Printer_Tray_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Printer_Tray_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Printer_Tray_ID, Integer.valueOf(AD_Printer_Tray_ID));
}
@Override
public int getAD_Printer_Tray_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Printer_Tray_ID);
}
@Override
public void setDescription (java.lang.String Description)
{ | set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_Printer_Tray.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ConfigController {
@Value("${config.file.path}")
private String filePath;
private final ApplicationContext applicationContext;
private final ConfigManager configManager;
public ConfigController(ApplicationContext applicationContext, ConfigManager configManager) {
this.applicationContext = applicationContext;
this.configManager = configManager;
}
@GetMapping("/reinitializeConfig")
public void reinitializeConfig() {
configManager.reinitializeConfig();
}
@GetMapping("/reinitializeBean")
public void reinitializeBean() {
DefaultSingletonBeanRegistry registry = (DefaultSingletonBeanRegistry) applicationContext.getAutowireCapableBeanFactory();
registry.destroySingleton("ConfigManager");
registry.registerSingleton("ConfigManager", new ConfigManager(filePath)); | }
@GetMapping("/destroyBean")
public void destroyBean() {
DefaultSingletonBeanRegistry registry = (DefaultSingletonBeanRegistry) applicationContext.getAutowireCapableBeanFactory();
registry.destroySingleton("ConfigManager");
}
@GetMapping("/{key}")
public Object get(@PathVariable String key) {
return configManager.getConfig(key);
}
@GetMapping("/context/{key}")
public Object getFromContext(@PathVariable String key) {
ConfigManager dynamicConfigManager = applicationContext.getBean(ConfigManager.class);
return dynamicConfigManager.getConfig(key);
}
} | repos\tutorials-master\spring-core-2\src\main\java\com\baeldung\reinitializebean\controller\ConfigController.java | 2 |
请完成以下Java代码 | public String getPayload() {
return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_PAYLOAD);
}
public Q get() {
return method(HttpGet.METHOD_NAME);
}
public Q post() {
return method(HttpPost.METHOD_NAME);
}
public Q put() {
return method(HttpPut.METHOD_NAME);
}
public Q delete() {
return method(HttpDelete.METHOD_NAME);
}
public Q patch() {
return method(HttpPatch.METHOD_NAME);
}
public Q head() {
return method(HttpHead.METHOD_NAME);
}
public Q options() {
return method(HttpOptions.METHOD_NAME);
}
public Q trace() {
return method(HttpTrace.METHOD_NAME);
}
public Map<String, Object> getConfigOptions() {
return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG);
}
public Object getConfigOption(String field) {
Map<String, Object> config = getConfigOptions();
if (config != null) {
return config.get(field);
} | return null;
}
@SuppressWarnings("unchecked")
public Q configOption(String field, Object value) {
if (field == null || field.isEmpty() || value == null) {
LOG.ignoreConfig(field, value);
} else {
Map<String, Object> config = getConfigOptions();
if (config == null) {
config = new HashMap<>();
setRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG, config);
}
config.put(field, value);
}
return (Q) this;
}
} | repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\AbstractHttpRequest.java | 1 |
请完成以下Java代码 | protected boolean beforeSave (boolean newRecord)
{
// Order
if (!isOrderBy())
{
setSortNo(0);
setIsGroupBy(false);
setIsPageBreak(false);
}
// Rel Position
if (isRelativePosition())
{
setXPosition(0);
setYPosition(0);
}
else
{
setXSpace(0);
setYSpace(0);
}
// Image
if (isImageField())
{
setImageIsAttached(false);
setImageURL(null);
}
return true;
} // beforeSave
/**
* After Save
* @param newRecord new
* @param success success
* @return success
*/
@Override
protected boolean afterSave (boolean newRecord, boolean success) | {
// Set Translation from Element
if (newRecord
// && MClient.get(getCtx()).isMultiLingualDocument()
&& getPrintName() != null && getPrintName().length() > 0)
{
String sql = "UPDATE AD_PrintFormatItem_Trl trl "
+ "SET PrintName = (SELECT e.PrintName "
+ "FROM AD_Element_Trl e, AD_Column c "
+ "WHERE e.AD_Language=trl.AD_Language"
+ " AND e.AD_Element_ID=c.AD_Element_ID"
+ " AND c.AD_Column_ID=" + getAD_Column_ID() + ") "
+ "WHERE AD_PrintFormatItem_ID = " + get_ID()
+ " AND EXISTS (SELECT * "
+ "FROM AD_Element_Trl e, AD_Column c "
+ "WHERE e.AD_Language=trl.AD_Language"
+ " AND e.AD_Element_ID=c.AD_Element_ID"
+ " AND c.AD_Column_ID=" + getAD_Column_ID()
+ " AND trl.AD_PrintFormatItem_ID = " + get_ID() + ")"
+ " AND EXISTS (SELECT * FROM AD_Client "
+ "WHERE AD_Client_ID=trl.AD_Client_ID AND IsMultiLingualDocument='Y')";
int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
log.debug("translations updated #" + no);
}
// metas-tsa: we need to reset the cache if an item value is changed
CacheMgt.get().resetLocalNowAndBroadcastOnTrxCommit(get_TrxName(), CacheInvalidateMultiRequest.rootRecord(I_AD_PrintFormat.Table_Name, getAD_PrintFormat_ID()));
return success;
} // afterSave
} // MPrintFormatItem | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintFormatItem.java | 1 |
请完成以下Java代码 | public Character firstNonRepeatingCharBruteForceNaive(String inputString) {
if (null == inputString || inputString.isEmpty()) {
return null;
}
for (int outer = 0; outer < inputString.length(); outer++) {
boolean repeat = false;
for (int inner = 0; inner < inputString.length(); inner++) {
if (inner != outer && inputString.charAt(outer) == inputString.charAt(inner)) {
repeat = true;
break;
}
}
if (!repeat) {
return inputString.charAt(outer);
}
}
return null;
}
public Character firstNonRepeatingCharWithMap(String inputString) {
if (null == inputString || inputString.isEmpty()) {
return null;
}
Map<Character, Integer> frequency = new HashMap<>();
for (int outer = 0; outer < inputString.length(); outer++) {
char character = inputString.charAt(outer);
frequency.put(character, frequency.getOrDefault(character, 0) + 1);
}
for (Character c : inputString.toCharArray()) {
if (frequency.get(c) == 1) {
return c; | }
}
return null;
}
public Character firstNonRepeatingCharWithArray(String inputString) {
if (null == inputString || inputString.isEmpty()) {
return null;
}
int[] frequency = new int[26];
for (int outer = 0; outer < inputString.length(); outer++) {
char character = inputString.charAt(outer);
frequency[character - 'a']++;
}
for (Character c : inputString.toCharArray()) {
if (frequency[c - 'a'] == 1) {
return c;
}
}
return null;
}
} | repos\tutorials-master\core-java-modules\core-java-string-algorithms-3\src\main\java\com\baeldung\firstnonrepeatingcharacter\FirstNonRepeatingCharacter.java | 1 |
请完成以下Java代码 | public UnsupportedOperationException simpleExpressionNotSupported() {
return new UnsupportedOperationException(exceptionMessage(
"016",
"Simple Expression not supported by FEEL engine")
);
}
public FeelException unableToEvaluateExpressionAsNotInputIsSet(String simpleUnaryTests, FeelMissingVariableException e) {
return new FeelException(exceptionMessage(
"017",
"Unable to evaluate expression '{}' as no input is set. Maybe the inputExpression is missing or empty.", simpleUnaryTests),
e
);
}
public FeelMethodInvocationException invalidDateAndTimeFormat(String dateTimeString, Throwable cause) {
return new FeelMethodInvocationException(exceptionMessage(
"018",
"Invalid date and time format in '{}'", dateTimeString),
cause, "date and time", dateTimeString
);
}
public FeelMethodInvocationException unableToInvokeMethod(String simpleUnaryTests, FeelMethodInvocationException cause) { | String method = cause.getMethod();
String[] parameters = cause.getParameters();
return new FeelMethodInvocationException(exceptionMessage(
"019",
"Unable to invoke method '{}' with parameters '{}' in expression '{}'", method, parameters, simpleUnaryTests),
cause.getCause(), method, parameters
);
}
public FeelSyntaxException invalidListExpression(String feelExpression) {
String description = "List expression can not have empty elements";
return syntaxException("020", feelExpression, description);
}
} | repos\camunda-bpm-platform-master\engine-dmn\feel-juel\src\main\java\org\camunda\bpm\dmn\feel\impl\juel\FeelEngineLogger.java | 1 |
请完成以下Java代码 | public void setM_InOutLine_ID (int M_InOutLine_ID)
{
if (M_InOutLine_ID < 1)
set_Value (COLUMNNAME_M_InOutLine_ID, null);
else
set_Value (COLUMNNAME_M_InOutLine_ID, Integer.valueOf(M_InOutLine_ID));
}
/** Get Versand-/Wareneingangsposition.
@return Position auf Versand- oder Wareneingangsbeleg
*/
@Override
public int getM_InOutLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set M_InOutLine_To_C_Customs_Invoice_Line.
@param M_InOutLine_To_C_Customs_Invoice_Line_ID M_InOutLine_To_C_Customs_Invoice_Line */
@Override
public void setM_InOutLine_To_C_Customs_Invoice_Line_ID (int M_InOutLine_To_C_Customs_Invoice_Line_ID)
{
if (M_InOutLine_To_C_Customs_Invoice_Line_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_InOutLine_To_C_Customs_Invoice_Line_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_InOutLine_To_C_Customs_Invoice_Line_ID, Integer.valueOf(M_InOutLine_To_C_Customs_Invoice_Line_ID));
}
/** Get M_InOutLine_To_C_Customs_Invoice_Line.
@return M_InOutLine_To_C_Customs_Invoice_Line */
@Override
public int getM_InOutLine_To_C_Customs_Invoice_Line_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_InOutLine_To_C_Customs_Invoice_Line_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Produkt.
@param M_Product_ID
Produkt, Leistung, Artikel
*/
@Override
public void setM_Product_ID (int M_Product_ID)
{
if (M_Product_ID < 1)
set_Value (COLUMNNAME_M_Product_ID, null);
else
set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID));
}
/** Get Produkt.
@return Produkt, Leistung, Artikel
*/
@Override
public int getM_Product_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Bewegungs-Menge.
@param MovementQty
Menge eines bewegten Produktes.
*/
@Override
public void setMovementQty (java.math.BigDecimal MovementQty) | {
set_Value (COLUMNNAME_MovementQty, MovementQty);
}
/** Get Bewegungs-Menge.
@return Menge eines bewegten Produktes.
*/
@Override
public java.math.BigDecimal getMovementQty ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MovementQty);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Einzelpreis.
@param PriceActual
Effektiver Preis
*/
@Override
public void setPriceActual (java.math.BigDecimal PriceActual)
{
set_Value (COLUMNNAME_PriceActual, PriceActual);
}
/** Get Einzelpreis.
@return Effektiver Preis
*/
@Override
public java.math.BigDecimal getPriceActual ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceActual);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutLine_To_C_Customs_Invoice_Line.java | 1 |
请完成以下Java代码 | public String printByTo()
{
StringBuffer sb = new StringBuffer();
sb.append("========按终点打印========\n");
for (int to = 0; to < edgesTo.length; ++to)
{
List<EdgeFrom> edgeFromList = edgesTo[to];
for (EdgeFrom edgeFrom : edgeFromList)
{
sb.append(String.format("to:%3d, from:%3d, weight:%05.2f, word:%s\n", to, edgeFrom.from, edgeFrom.weight, edgeFrom.name));
}
}
return sb.toString();
}
/**
* 根据节点下标数组解释出对应的路径
* @param path
* @return
*/
public List<Vertex> parsePath(int[] path)
{
List<Vertex> vertexList = new LinkedList<Vertex>();
for (int i : path)
{
vertexList.add(vertexes[i]);
}
return vertexList;
}
/**
* 从一个路径中转换出空格隔开的结果
* @param path
* @return
*/
public static String parseResult(List<Vertex> path)
{
if (path.size() < 2)
{ | throw new RuntimeException("路径节点数小于2:" + path);
}
StringBuffer sb = new StringBuffer();
for (int i = 1; i < path.size() - 1; ++i)
{
Vertex v = path.get(i);
sb.append(v.getRealWord() + " ");
}
return sb.toString();
}
public Vertex[] getVertexes()
{
return vertexes;
}
public List<EdgeFrom>[] getEdgesTo()
{
return edgesTo;
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\common\Graph.java | 1 |
请完成以下Java代码 | public class HttpSessionDestroyedEvent extends SessionDestroyedEvent {
public HttpSessionDestroyedEvent(HttpSession session) {
super(session);
}
public HttpSession getSession() {
return (HttpSession) getSource();
}
@SuppressWarnings("unchecked")
@Override
public List<SecurityContext> getSecurityContexts() {
HttpSession session = getSession();
Enumeration<String> attributes = session.getAttributeNames();
ArrayList<SecurityContext> contexts = new ArrayList<>(); | while (attributes.hasMoreElements()) {
String attributeName = attributes.nextElement();
Object attributeValue = session.getAttribute(attributeName);
if (attributeValue instanceof SecurityContext) {
contexts.add((SecurityContext) attributeValue);
}
}
return contexts;
}
@Override
public String getId() {
return getSession().getId();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\session\HttpSessionDestroyedEvent.java | 1 |
请完成以下Java代码 | public static void main(String[] args) {
SpringRestClient springRestClient = new SpringRestClient();
// Step1: first create a new employee
springRestClient.createEmployee();
// Step 2: get new created employee from step1
springRestClient.getEmployeeById();
// Step3: get all employees
springRestClient.getEmployees();
// Step4: Update employee with id = 1
springRestClient.updateEmployee();
// Step5: Delete employee with id = 1
springRestClient.deleteEmployee();
}
private void getEmployees() {
HttpHeaders headers = new HttpHeaders();
headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
HttpEntity<String> entity = new HttpEntity<String>("parameters", headers);
ResponseEntity<String> result = restTemplate.exchange(GET_EMPLOYEES_ENDPOINT_URL, HttpMethod.GET, entity,
String.class);
System.out.println(result);
}
private void getEmployeeById() {
Map<String, String> params = new HashMap<String, String>(); | params.put("id", "1");
RestTemplate restTemplate = new RestTemplate();
Employee result = restTemplate.getForObject(GET_EMPLOYEE_ENDPOINT_URL, Employee.class, params);
System.out.println(result);
}
private void createEmployee() {
Employee newEmployee = new Employee("admin", "admin", "admin@gmail.com");
RestTemplate restTemplate = new RestTemplate();
Employee result = restTemplate.postForObject(CREATE_EMPLOYEE_ENDPOINT_URL, newEmployee, Employee.class);
System.out.println(result);
}
private void updateEmployee() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");
Employee updatedEmployee = new Employee("admin123", "admin123", "admin123@gmail.com");
RestTemplate restTemplate = new RestTemplate();
restTemplate.put(UPDATE_EMPLOYEE_ENDPOINT_URL, updatedEmployee, params);
}
private void deleteEmployee() {
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1");
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete(DELETE_EMPLOYEE_ENDPOINT_URL, params);
}
} | repos\Spring-Boot-Advanced-Projects-main\spring-aop-advice-examples\src\main\java\net\alanbinu\springboot2\springboot2jpacrudexample\SpringRestClient.java | 1 |
请完成以下Java代码 | private ArticleReadDto.CommentDto findParentWithId(ArticleReadDto d, Long parentCommentId) {
return d.getComments().stream()
.filter(c -> c.id.equals(parentCommentId))
.findFirst().orElseThrow();
}
@Cacheable(cacheNames = "previewForPublicHomePage")
public Page<ArticlePreviewDto> previewForPublicHomePage(Pageable pageable) {
return articleRepository.findWithUserAndAttachedFilesByStatus(ArticleStatus.PUBLISHED, pageable)
.map(ArticleMapper.INSTANCE::mapForPreviewListing);
}
@Cacheable(cacheNames = "previewAllWithFilesByUser")
public Page<ArticlePreviewDto> previewAllWithFilesByUser(Pageable pageable, UUID userId) {
return articleRepository.findWithFilesAndUserByCreatedByUser_IdAndStatusOrderByCreatedDateDesc(userId, ArticleStatus.PUBLISHED, pageable)
.map(ArticleMapper.INSTANCE::mapForPreviewListing);
}
@Cacheable(cacheNames = "articleForReview", key = "#id")
public ArticlePreviewDto readForReview(Long id) {
return articleRepository.findOneWithUserAndAttachedFilesByIdAndStatus(id, ArticleStatus.FLAGGED_FOR_MANUAL_REVIEW)
.map(ArticleMapper.INSTANCE::mapForReview)
.orElseThrow();
}
public Page<ArticlePreviewDto> getAllToReview(Pageable pageable) {
return articleRepository.findWithUserAndAttachedFilesByStatus(ArticleStatus.FLAGGED_FOR_MANUAL_REVIEW, pageable)
.map(ArticleMapper.INSTANCE::mapForPreviewListing);
} | @Transactional
public void delete(Long id) {
commentRepo.deleteByArticleId(id);
articleRepository.deleteById(id);
}
@Cacheable(cacheNames = {"article-findCreatedByUserIdById"})
public UUID findCreatedByUserIdById(Long articleId) {
return articleRepository.findCreatedByUserIdById(articleId);
}
public Optional<Article> handleReview(ArticleReviewResultDto dto) {
return articleRepository.findWithModifiedUserByIdAndStatus(dto.getId(), ArticleStatus.FLAGGED_FOR_MANUAL_REVIEW)
.map(n -> {
transactionTemplate.executeWithoutResult(txSt -> {
n.setStatus(dto.getVerdict());
articleRepository.save(n);
});
websocketHandler.sendToUser(n.getLastModifiedByUser().getUsername(), "Your article with title " + n.getTitle() + " has been " + (dto.getVerdict() == ArticleStatus.PUBLISHED ? "approved from manual review." : "rejected from manual review."));
return n;
});
}
} | repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\modules\article\ArticleService.java | 1 |
请完成以下Java代码 | protected String mapPassword(Object passwordValue) {
if (!(passwordValue instanceof String)) {
// Assume it's binary
passwordValue = new String((byte[]) passwordValue);
}
return (String) passwordValue;
}
/**
* Creates a GrantedAuthority from a role attribute. Override to customize authority
* object creation.
* <p>
* The default implementation converts string attributes to roles, making use of the
* <tt>rolePrefix</tt> and <tt>convertToUpperCase</tt> properties. Non-String
* attributes are ignored.
* </p>
* @param role the attribute returned from
* @return the authority to be added to the list of authorities for the user, or null
* if this attribute should be ignored.
*/
protected GrantedAuthority createAuthority(Object role) {
if (role instanceof String) {
if (this.convertToUpperCase) {
role = ((String) role).toUpperCase(Locale.ROOT);
}
return new SimpleGrantedAuthority(this.rolePrefix + role);
}
return null;
}
/**
* Determines whether role field values will be converted to upper case when loaded.
* The default is true.
* @param convertToUpperCase true if the roles should be converted to upper case. | */
public void setConvertToUpperCase(boolean convertToUpperCase) {
this.convertToUpperCase = convertToUpperCase;
}
/**
* The name of the attribute which contains the user's password. Defaults to
* "userPassword".
* @param passwordAttributeName the name of the attribute
*/
public void setPasswordAttributeName(String passwordAttributeName) {
this.passwordAttributeName = passwordAttributeName;
}
/**
* The names of any attributes in the user's entry which represent application roles.
* These will be converted to <tt>GrantedAuthority</tt>s and added to the list in the
* returned LdapUserDetails object. The attribute values must be Strings by default.
* @param roleAttributes the names of the role attributes.
*/
public void setRoleAttributes(String[] roleAttributes) {
Assert.notNull(roleAttributes, "roleAttributes array cannot be null");
this.roleAttributes = roleAttributes;
}
/**
* The prefix that should be applied to the role names
* @param rolePrefix the prefix (defaults to "ROLE_").
*/
public void setRolePrefix(String rolePrefix) {
this.rolePrefix = rolePrefix;
}
} | repos\spring-security-main\ldap\src\main\java\org\springframework\security\ldap\userdetails\LdapUserDetailsMapper.java | 1 |
请完成以下Java代码 | private static <T> String toJson(T object) {
try {
return OBJECT_MAPPER.writeValueAsString(object);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private static <T> T fromJson(String json, Class<T> type) {
try {
return OBJECT_MAPPER.readValue(json, type);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
}
private static SessionFactory createSessionFactory() {
Map<String, Object> settings = new HashMap<>();
settings.put(URL, System.getenv("DB_URL"));
settings.put(DIALECT, "org.hibernate.dialect.PostgreSQLDialect");
settings.put(DEFAULT_SCHEMA, "shipping");
settings.put(DRIVER, "org.postgresql.Driver");
settings.put(USER, System.getenv("DB_USER"));
settings.put(PASS, System.getenv("DB_PASSWORD"));
settings.put("hibernate.hikari.connectionTimeout", "20000");
settings.put("hibernate.hikari.minimumIdle", "1");
settings.put("hibernate.hikari.maximumPoolSize", "2");
settings.put("hibernate.hikari.idleTimeout", "30000"); | // commented out as we only need them on first use
// settings.put(HBM2DDL_AUTO, "create-only");
// settings.put(HBM2DDL_DATABASE_ACTION, "create");
StandardServiceRegistry registry = new StandardServiceRegistryBuilder()
.applySettings(settings)
.build();
return new MetadataSources(registry)
.addAnnotatedClass(Consignment.class)
.addAnnotatedClass(Item.class)
.addAnnotatedClass(Checkin.class)
.buildMetadata()
.buildSessionFactory();
}
private void flushConnectionPool() {
ConnectionProvider connectionProvider = sessionFactory.getSessionFactoryOptions()
.getServiceRegistry()
.getService(ConnectionProvider.class);
HikariDataSource hikariDataSource = connectionProvider.unwrap(HikariDataSource.class);
hikariDataSource.getHikariPoolMXBean().softEvictConnections();
}
} | repos\tutorials-master\aws-modules\aws-lambda-modules\shipping-tracker-lambda\ShippingFunction\src\main\java\com\baeldung\lambda\shipping\App.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.