instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public I_CM_ChatType getCM_ChatType() throws RuntimeException
{
return (I_CM_ChatType)MTable.get(getCtx(), I_CM_ChatType.Table_Name)
.getPO(getCM_ChatType_ID(), get_TrxName()); }
/** Set Chat Type.
@param CM_ChatType_ID
Type of discussion / chat
*/
public void setCM_ChatType_ID (int CM_ChatType_ID)
{
if (CM_ChatType_ID < 1)
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, null);
else
set_ValueNoCheck (COLUMNNAME_CM_ChatType_ID, Integer.valueOf(CM_ChatType_ID));
}
/** Get Chat Type.
@return Type of discussion / chat
*/
public int getCM_ChatType_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_CM_ChatType_ID);
if (ii == null)
return 0;
return ii.intValue(); | }
/** Set Self-Service.
@param IsSelfService
This is a Self-Service entry or this entry can be changed via Self-Service
*/
public void setIsSelfService (boolean IsSelfService)
{
set_Value (COLUMNNAME_IsSelfService, Boolean.valueOf(IsSelfService));
}
/** Get Self-Service.
@return This is a Self-Service entry or this entry can be changed via Self-Service
*/
public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_ChatTypeUpdate.java | 1 |
请完成以下Java代码 | public static String stripDigits(final String text)
{
if (text == null)
{
return null;
}
final char[] inArray = text.toCharArray();
final StringBuilder out = new StringBuilder(inArray.length);
for (final char ch : inArray)
{
if (Character.isLetter(ch) || !Character.isDigit(ch))
{
out.append(ch);
}
}
return out.toString();
}
/**
* @param in input {@link String}
* @return {@param in} if != null, empty string otherwise
*/
@NonNull
public static String nullToEmpty(@Nullable final String in)
{
return in != null ? in : "";
}
@Nullable
public static String createHash(@Nullable final String str, @Nullable final String algorithm) throws NoSuchAlgorithmException
{
if (str == null || str.isEmpty())
{
return null;
}
final String algorithmToUse = algorithm != null ? algorithm : "SHA-512";
final MessageDigest md = MessageDigest.getInstance(algorithmToUse);
// Update MessageDigest with input text in bytes
md.update(str.getBytes(StandardCharsets.UTF_8));
// Get the hashbytes
final byte[] hashBytes = md.digest();
//Convert hash bytes to hex format
final StringBuilder sb = new StringBuilder();
for (final byte b : hashBytes)
{
sb.append(String.format("%02x", b));
}
return sb.toString();
}
@Nullable
public static IPair<String, String> splitStreetAndHouseNumberOrNull(@Nullable final String streetAndNumber)
{
if (EmptyUtil.isBlank(streetAndNumber))
{
return null;
}
final Pattern pattern = Pattern.compile(StringUtils.REGEXP_STREET_AND_NUMBER_SPLIT);
final Matcher matcher = pattern.matcher(streetAndNumber);
if (!matcher.matches())
{
return null;
}
final String street = matcher.group(1);
final String number = matcher.group(2);
return ImmutablePair.of(trim(street), trim(number)); | }
public static String ident(@Nullable final String text, int tabs)
{
if (text == null || text.isEmpty() || tabs <= 0)
{
return text;
}
final String ident = repeat("\t", tabs);
return ident
+ text.trim().replace("\n", "\n" + ident);
}
public static String repeat(@NonNull final String string, final int times)
{
if (string.isEmpty())
{
return string;
}
if (times <= 0)
{
return "";
}
else if (times == 1)
{
return string;
}
else
{
final StringBuilder result = new StringBuilder(string.length() * times);
for (int i = 0; i < times; i++)
{
result.append(string);
}
return result.toString();
}
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\StringUtils.java | 1 |
请完成以下Java代码 | public @Nullable ConfigurationProperty getConfigurationProperty(ConfigurationPropertyName name) {
boolean filtered = getFilter().test(name);
return filtered ? getSource().getConfigurationProperty(name) : null;
}
@Override
public ConfigurationPropertyState containsDescendantOf(ConfigurationPropertyName name) {
ConfigurationPropertyState result = this.source.containsDescendantOf(name);
if (result == ConfigurationPropertyState.PRESENT) {
// We can't be sure a contained descendant won't be filtered
return ConfigurationPropertyState.UNKNOWN;
}
return result;
}
@Override
public @Nullable Object getUnderlyingSource() {
return this.source.getUnderlyingSource();
} | protected ConfigurationPropertySource getSource() {
return this.source;
}
protected Predicate<ConfigurationPropertyName> getFilter() {
return this.filter;
}
@Override
public String toString() {
return this.source.toString() + " (filtered)";
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\FilteredConfigurationPropertiesSource.java | 1 |
请完成以下Java代码 | public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", parentId=").append(parentId); | sb.append(", name=").append(name);
sb.append(", level=").append(level);
sb.append(", productCount=").append(productCount);
sb.append(", productUnit=").append(productUnit);
sb.append(", navStatus=").append(navStatus);
sb.append(", showStatus=").append(showStatus);
sb.append(", sort=").append(sort);
sb.append(", icon=").append(icon);
sb.append(", keywords=").append(keywords);
sb.append(", description=").append(description);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsProductCategory.java | 1 |
请完成以下Java代码 | public ValueNamePair[] getCountQuarter ()
{
return getCount("Q");
} // getCountQuarter
/**
* Get Monthly Count
* @return monthly count
*/
public ValueNamePair[] getCountMonth ()
{
return getCount("MM");
} // getCountMonth
/**
* Get Weekly Count
* @return weekly count | */
public ValueNamePair[] getCountWeek ()
{
return getCount("DY");
} // getCountWeek
/**
* Get Daily Count
* @return dailt count
*/
public ValueNamePair[] getCountDay ()
{
return getCount("J");
} // getCountDay
} // MClickCount | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MClickCount.java | 1 |
请完成以下Java代码 | public static void setMigrationScriptDirectory(@NonNull final Path path)
{
MigrationScriptFileLogger.setMigrationScriptDirectory(path);
}
public static Path getMigrationScriptDirectory()
{
return MigrationScriptFileLogger.getMigrationScriptDirectory();
}
private static boolean isSkipLogging(@NonNull final Sql sql)
{
return sql.isEmpty() || isSkipLogging(sql.getSqlCommand());
}
private static boolean isSkipLogging(@NonNull final String sqlCommand)
{
// Always log DDL (flagged) commands
if (sqlCommand.startsWith(DDL_PREFIX))
{
return false;
}
final String sqlCommandUC = sqlCommand.toUpperCase().trim();
//
// Don't log selects
if (sqlCommandUC.startsWith("SELECT "))
{
return true;
}
//
// Don't log DELETE FROM Some_Table WHERE AD_Table_ID=? AND Record_ID=?
if (sqlCommandUC.startsWith("DELETE FROM ") && sqlCommandUC.endsWith(" WHERE AD_TABLE_ID=? AND RECORD_ID=?"))
{
return true;
} | //
// Check that INSERT/UPDATE/DELETE statements are about our ignored tables
final ImmutableSet<String> exceptionTablesUC = Services.get(IMigrationLogger.class).getTablesToIgnoreUC(Env.getClientIdOrSystem());
for (final String tableNameUC : exceptionTablesUC)
{
if (sqlCommandUC.startsWith("INSERT INTO " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("DELETE FROM " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("DELETE " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("UPDATE " + tableNameUC + " "))
return true;
if (sqlCommandUC.startsWith("INSERT INTO " + tableNameUC + "("))
return true;
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\logger\MigrationScriptFileLoggerHolder.java | 1 |
请完成以下Java代码 | public boolean isEmpty() {return set.isEmpty();}
public ImmutableSet<ResourceTypeId> getResourceTypeIds()
{
final ImmutableSet.Builder<ResourceTypeId> result = ImmutableSet.builder();
for (final ManufacturingJobFacets.FacetId facetId : set)
{
if (ManufacturingJobFacetGroup.RESOURCE_TYPE.equals(facetId.getGroup()))
{
result.add(facetId.getResourceTypeIdNotNull());
}
}
return result.build();
}
}
@Value(staticConstructor = "of")
public static class Facet
{
@NonNull FacetId facetId;
@NonNull ITranslatableString caption;
public WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder newWorkflowLaunchersFacetGroupBuilder()
{
return facetId.getGroup().newWorkflowLaunchersFacetGroupBuilder();
}
public WorkflowLaunchersFacet toWorkflowLaunchersFacet(@Nullable ImmutableSet<WorkflowLaunchersFacetId> activeFacetIds)
{
final WorkflowLaunchersFacetId facetId = this.facetId.toWorkflowLaunchersFacetId();
return WorkflowLaunchersFacet.builder()
.facetId(facetId)
.caption(caption)
.isActive(activeFacetIds != null && activeFacetIds.contains(facetId))
.build();
}
}
@EqualsAndHashCode
@ToString
public static class FacetsCollection implements Iterable<Facet>
{
private static final FacetsCollection EMPTY = new FacetsCollection(ImmutableSet.of());
private final ImmutableSet<Facet> set;
private FacetsCollection(@NonNull final ImmutableSet<Facet> set)
{
this.set = set; | }
public static FacetsCollection ofCollection(final Collection<Facet> collection)
{
return !collection.isEmpty() ? new FacetsCollection(ImmutableSet.copyOf(collection)) : EMPTY;
}
@Override
@NonNull
public Iterator<Facet> iterator() {return set.iterator();}
public boolean isEmpty() {return set.isEmpty();}
public WorkflowLaunchersFacetGroupList toWorkflowLaunchersFacetGroupList(@Nullable ImmutableSet<WorkflowLaunchersFacetId> activeFacetIds)
{
if (isEmpty())
{
return WorkflowLaunchersFacetGroupList.EMPTY;
}
final HashMap<WorkflowLaunchersFacetGroupId, WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder> groupBuilders = new HashMap<>();
for (final ManufacturingJobFacets.Facet manufacturingFacet : set)
{
final WorkflowLaunchersFacet facet = manufacturingFacet.toWorkflowLaunchersFacet(activeFacetIds);
groupBuilders.computeIfAbsent(facet.getGroupId(), k -> manufacturingFacet.newWorkflowLaunchersFacetGroupBuilder())
.facet(facet);
}
final ImmutableList<WorkflowLaunchersFacetGroup> groups = groupBuilders.values()
.stream()
.map(WorkflowLaunchersFacetGroup.WorkflowLaunchersFacetGroupBuilder::build)
.collect(ImmutableList.toImmutableList());
return WorkflowLaunchersFacetGroupList.ofList(groups);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\ManufacturingJobFacets.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class METADATA
{
@JacksonXmlElementWrapper(useWrapping = false)
@JsonProperty("FIELD")
List<FIELD> fields;
@JsonIgnore
@NonFinal
private transient ImmutableMap<String, Integer> _fieldName2FieldIndex; // lazy
@Builder
public METADATA(
@JsonProperty("FIELD") @NonNull @Singular final List<FIELD> fields)
{
this.fields = fields;
}
@NonNull
public ROW createROW(@NonNull final Map<String, String> valuesByName)
{
final ROWBuilder row = ROW.builder();
for (final FIELD field : fields)
{
final String fieldName = field.getName();
final String value = valuesByName.get(fieldName);
row.col(COL.of(value));
}
return row.build();
}
public COL getCell(@NonNull final ROW row, @NonNull final String fieldName)
{
final int fieldIndex = getFieldIndexByName(fieldName);
return row.getCols().get(fieldIndex);
}
private int getFieldIndexByName(final String fieldName)
{
ImmutableMap<String, Integer> fieldName2FieldIndex = this._fieldName2FieldIndex; | if (fieldName2FieldIndex == null)
{
fieldName2FieldIndex = this._fieldName2FieldIndex = createFieldName2FieldIndexMap();
}
final Integer fieldIndex = fieldName2FieldIndex.get(fieldName);
if (fieldIndex == null)
{
throw new IllegalArgumentException("A field with name `" + fieldName + "` is not included in the current file; metadata=" + this);
}
return fieldIndex;
}
private ImmutableMap<String, Integer> createFieldName2FieldIndexMap()
{
ImmutableMap.Builder<String, Integer> builder = ImmutableMap.<String, Integer> builder();
for (int i = 0, size = fields.size(); i < size; i++)
{
final String fieldName = fields.get(i).getName();
builder.put(fieldName, i);
}
return builder.build();
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-filemaker\src\main\java\de\metas\common\filemaker\METADATA.java | 2 |
请完成以下Java代码 | public class X_C_BP_BankAccount_InvoiceAutoAllocateRule extends org.compiere.model.PO implements I_C_BP_BankAccount_InvoiceAutoAllocateRule, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -956367533L;
/** Standard Constructor */
public X_C_BP_BankAccount_InvoiceAutoAllocateRule (final Properties ctx, final int C_BP_BankAccount_InvoiceAutoAllocateRule_ID, @Nullable final String trxName)
{
super (ctx, C_BP_BankAccount_InvoiceAutoAllocateRule_ID, trxName);
}
/** Load Constructor */
public X_C_BP_BankAccount_InvoiceAutoAllocateRule (final Properties ctx, final ResultSet rs, @Nullable final String trxName)
{
super (ctx, rs, trxName);
}
/** Load Meta Data */
@Override
protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setC_BP_BankAccount_ID (final int C_BP_BankAccount_ID)
{
if (C_BP_BankAccount_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BP_BankAccount_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BP_BankAccount_ID, C_BP_BankAccount_ID);
}
@Override
public int getC_BP_BankAccount_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_BankAccount_ID);
}
@Override
public void setC_BP_BankAccount_InvoiceAutoAllocateRule_ID (final int C_BP_BankAccount_InvoiceAutoAllocateRule_ID)
{
if (C_BP_BankAccount_InvoiceAutoAllocateRule_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BP_BankAccount_InvoiceAutoAllocateRule_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BP_BankAccount_InvoiceAutoAllocateRule_ID, C_BP_BankAccount_InvoiceAutoAllocateRule_ID);
} | @Override
public int getC_BP_BankAccount_InvoiceAutoAllocateRule_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BP_BankAccount_InvoiceAutoAllocateRule_ID);
}
@Override
public void setC_DocTypeInvoice_ID (final int C_DocTypeInvoice_ID)
{
if (C_DocTypeInvoice_ID < 1)
set_Value (COLUMNNAME_C_DocTypeInvoice_ID, null);
else
set_Value (COLUMNNAME_C_DocTypeInvoice_ID, C_DocTypeInvoice_ID);
}
@Override
public int getC_DocTypeInvoice_ID()
{
return get_ValueAsInt(COLUMNNAME_C_DocTypeInvoice_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BP_BankAccount_InvoiceAutoAllocateRule.java | 1 |
请完成以下Java代码 | public void setProjectName (String ProjectName)
{
set_Value (COLUMNNAME_ProjectName, ProjectName);
}
/** Get Project.
@return Name of the Project
*/
public String getProjectName ()
{
return (String)get_Value(COLUMNNAME_ProjectName);
}
/** Set Reference.
@param Reference
Reference for this record
*/
public void setReference (String Reference)
{
set_Value (COLUMNNAME_Reference, Reference);
}
/** Get Reference.
@return Reference for this record
*/
public String getReference ()
{
return (String)get_Value(COLUMNNAME_Reference);
}
/** Set Release No.
@param ReleaseNo
Internal Release Number
*/
public void setReleaseNo (String ReleaseNo)
{
set_Value (COLUMNNAME_ReleaseNo, ReleaseNo);
}
/** Get Release No.
@return Internal Release Number
*/
public String getReleaseNo ()
{
return (String)get_Value(COLUMNNAME_ReleaseNo);
}
/** Set Script.
@param Script
Dynamic Java Language Script to calculate result
*/
public void setScript (byte[] Script)
{
set_ValueNoCheck (COLUMNNAME_Script, Script);
}
/** Get Script.
@return Dynamic Java Language Script to calculate result
*/
public byte[] getScript ()
{
return (byte[])get_Value(COLUMNNAME_Script);
}
/** Set Roll the Script.
@param ScriptRoll Roll the Script */ | public void setScriptRoll (String ScriptRoll)
{
set_Value (COLUMNNAME_ScriptRoll, ScriptRoll);
}
/** Get Roll the Script.
@return Roll the Script */
public String getScriptRoll ()
{
return (String)get_Value(COLUMNNAME_ScriptRoll);
}
/** Status AD_Reference_ID=53239 */
public static final int STATUS_AD_Reference_ID=53239;
/** In Progress = IP */
public static final String STATUS_InProgress = "IP";
/** Completed = CO */
public static final String STATUS_Completed = "CO";
/** Error = ER */
public static final String STATUS_Error = "ER";
/** Set Status.
@param Status
Status of the currently running check
*/
public void setStatus (String Status)
{
set_ValueNoCheck (COLUMNNAME_Status, Status);
}
/** Get Status.
@return Status of the currently running check
*/
public String getStatus ()
{
return (String)get_Value(COLUMNNAME_Status);
}
/** Set URL.
@param URL
Full URL address - e.g. http://www.adempiere.org
*/
public void setURL (String URL)
{
set_Value (COLUMNNAME_URL, URL);
}
/** Get URL.
@return Full URL address - e.g. http://www.adempiere.org
*/
public String getURL ()
{
return (String)get_Value(COLUMNNAME_URL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationScript.java | 1 |
请完成以下Java代码 | public Mono<Void> saveToken(ServerWebExchange exchange, @Nullable CsrfToken token) {
return exchange.getSession()
.doOnNext((session) -> putToken(session.getAttributes(), token))
.flatMap((session) -> session.changeSessionId());
}
private void putToken(Map<String, Object> attributes, @Nullable CsrfToken token) {
if (token == null) {
attributes.remove(this.sessionAttributeName);
}
else {
attributes.put(this.sessionAttributeName, token);
}
}
@Override
@SuppressWarnings("NullAway") // https://github.com/uber/NullAway/issues/1290
public Mono<CsrfToken> loadToken(ServerWebExchange exchange) {
return exchange.getSession()
.filter((session) -> session.getAttributes().containsKey(this.sessionAttributeName))
.mapNotNull((session) -> session.getAttribute(this.sessionAttributeName));
}
/**
* Sets the {@link ServerWebExchange} parameter name that the {@link CsrfToken} is
* expected to appear on
* @param parameterName the new parameter name to use
*/
public void setParameterName(String parameterName) {
Assert.hasLength(parameterName, "parameterName cannot be null or empty"); | this.parameterName = parameterName;
}
/**
* Sets the header name that the {@link CsrfToken} is expected to appear on and the
* header that the response will contain the {@link CsrfToken}.
* @param headerName the new header name to use
*/
public void setHeaderName(String headerName) {
Assert.hasLength(headerName, "headerName cannot be null or empty");
this.headerName = headerName;
}
/**
* Sets the {@link WebSession} attribute name that the {@link CsrfToken} is stored in
* @param sessionAttributeName the new attribute name to use
*/
public void setSessionAttributeName(String sessionAttributeName) {
Assert.hasLength(sessionAttributeName, "sessionAttributeName cannot be null or empty");
this.sessionAttributeName = sessionAttributeName;
}
private CsrfToken createCsrfToken() {
return new DefaultCsrfToken(this.headerName, this.parameterName, createNewToken());
}
private String createNewToken() {
return UUID.randomUUID().toString();
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\server\csrf\WebSessionServerCsrfTokenRepository.java | 1 |
请完成以下Java代码 | public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Report Column Set.
@param PA_ReportColumnSet_ID
Collection of Columns for Report
*/
public void setPA_ReportColumnSet_ID (int PA_ReportColumnSet_ID)
{
if (PA_ReportColumnSet_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ReportColumnSet_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ReportColumnSet_ID, Integer.valueOf(PA_ReportColumnSet_ID));
} | /** Get Report Column Set.
@return Collection of Columns for Report
*/
public int getPA_ReportColumnSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportColumnSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportColumnSet.java | 1 |
请完成以下Java代码 | public class RemittanceInformation5CH {
@XmlElement(name = "Ustrd")
protected String ustrd;
@XmlElement(name = "Strd")
protected StructuredRemittanceInformation7 strd;
/**
* Gets the value of the ustrd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getUstrd() {
return ustrd;
}
/**
* Sets the value of the ustrd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUstrd(String value) {
this.ustrd = value;
}
/**
* Gets the value of the strd property. | *
* @return
* possible object is
* {@link StructuredRemittanceInformation7 }
*
*/
public StructuredRemittanceInformation7 getStrd() {
return strd;
}
/**
* Sets the value of the strd property.
*
* @param value
* allowed object is
* {@link StructuredRemittanceInformation7 }
*
*/
public void setStrd(StructuredRemittanceInformation7 value) {
this.strd = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\RemittanceInformation5CH.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConfigurableEnvironment environment = (ConfigurableEnvironment) context.getEnvironment();
boolean fixed = getEnabledProperty(environment, "strategy.fixed.", false);
boolean content = getEnabledProperty(environment, "strategy.content.", false);
Boolean chain = getEnabledProperty(environment, "", null);
Boolean match = Chain.getEnabled(fixed, content, chain);
ConditionMessage.Builder message = ConditionMessage.forCondition(ConditionalOnEnabledResourceChain.class);
if (match == null) {
if (ClassUtils.isPresent(WEBJAR_VERSION_LOCATOR, getClass().getClassLoader())) {
return ConditionOutcome.match(message.found("class").items(WEBJAR_VERSION_LOCATOR));
}
if (ClassUtils.isPresent(WEBJAR_ASSET_LOCATOR, getClass().getClassLoader())) {
return ConditionOutcome.match(message.found("class").items(WEBJAR_ASSET_LOCATOR));
}
return ConditionOutcome.noMatch(message.didNotFind("class").items(WEBJAR_VERSION_LOCATOR));
}
if (match) { | return ConditionOutcome.match(message.because("enabled"));
}
return ConditionOutcome.noMatch(message.because("disabled"));
}
@Contract("_, _, !null -> !null")
private @Nullable Boolean getEnabledProperty(ConfigurableEnvironment environment, String key,
@Nullable Boolean defaultValue) {
String name = "spring.web.resources.chain." + key + "enabled";
if (defaultValue == null) {
return environment.getProperty(name, Boolean.class);
}
return environment.getProperty(name, Boolean.class, defaultValue);
}
} | repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\web\OnEnabledResourceChainCondition.java | 2 |
请完成以下Java代码 | private static JSONDashboardChangedEventsList toJSONDashboardChangedEventsList(final @NonNull UserDashboardItemChangeResult changeResult)
{
final JSONDashboardChangedEventsList.JSONDashboardChangedEventsListBuilder eventBuilder = JSONDashboardChangedEventsList.builder()
.event(JSONDashboardItemChangedEvent.of(
changeResult.getDashboardId(),
changeResult.getDashboardWidgetType(),
changeResult.getItemId()));
if (changeResult.isPositionChanged())
{
eventBuilder.event(JSONDashboardOrderChangedEvent.of(
changeResult.getDashboardId(),
changeResult.getDashboardWidgetType(),
changeResult.getDashboardOrderedItemIds()));
}
return eventBuilder.build();
}
private void sendEvents(
@NonNull final Set<WebsocketTopicName> websocketEndpoints,
@NonNull final JSONDashboardChangedEventsList events)
{ | if (websocketEndpoints.isEmpty() || events.isEmpty())
{
return;
}
for (final WebsocketTopicName websocketEndpoint : websocketEndpoints)
{
websocketSender.convertAndSend(websocketEndpoint, events);
logger.trace("Notified WS {}: {}", websocketEndpoint, events);
}
}
private ImmutableSet<WebsocketTopicName> getWebsocketTopicNamesByDashboardId(@NonNull final UserDashboardId dashboardId)
{
return websocketProducersRegistry.streamActiveProducersOfType(UserDashboardWebsocketProducer.class)
.filter(producer -> producer.isMatchingDashboardId(dashboardId))
.map(UserDashboardWebsocketProducer::getWebsocketTopicName)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\websocket\UserDashboardWebsocketSender.java | 1 |
请完成以下Java代码 | protected void eventNotificationsCompleted(PvmExecutionImpl execution) {
PvmActivity activity = execution.getActivity();
if (execution.isScope()
&& (executesNonScopeActivity(execution) || isAsyncBeforeActivity(execution))
&& !CompensationBehavior.executesNonScopeCompensationHandler(execution)) {
execution.removeAllTasks();
// case this is a scope execution and the activity is not a scope
execution.leaveActivityInstance();
execution.setActivity(getFlowScopeActivity(activity));
execution.performOperation(DELETE_CASCADE_FIRE_ACTIVITY_END);
} else {
if (execution.isScope()) {
ProcessEngineConfigurationImpl engineConfiguration = Context.getProcessEngineConfiguration();
// execution was canceled and output mapping for activity is marked as skippable
boolean alwaysSkipIoMappings =
execution instanceof ExecutionEntity &&
!execution.isProcessInstanceExecution() &&
execution.isCanceled() &&
engineConfiguration.isSkipOutputMappingOnCanceledActivities();
execution.destroy(alwaysSkipIoMappings);
}
// remove this execution and its concurrent parent (if exists)
execution.remove();
boolean continueRemoval = !execution.isDeleteRoot();
if (continueRemoval) {
PvmExecutionImpl propagatingExecution = execution.getParent();
if (propagatingExecution != null && !propagatingExecution.isScope() && !propagatingExecution.hasChildren()) {
propagatingExecution.remove();
continueRemoval = !propagatingExecution.isDeleteRoot();
propagatingExecution = propagatingExecution.getParent();
}
if (continueRemoval) {
if (propagatingExecution != null) {
// continue deletion with the next scope execution
// set activity on parent in case the parent is an inactive scope execution and activity has been set to 'null'.
if(propagatingExecution.getActivity() == null && activity != null && activity.getFlowScope() != null) {
propagatingExecution.setActivity(getFlowScopeActivity(activity));
}
}
}
}
} | }
protected boolean executesNonScopeActivity(PvmExecutionImpl execution) {
ActivityImpl activity = execution.getActivity();
return activity!=null && !activity.isScope();
}
protected boolean isAsyncBeforeActivity(PvmExecutionImpl execution) {
return execution.getActivityId() != null && execution.getActivityInstanceId() == null;
}
protected ActivityImpl getFlowScopeActivity(PvmActivity activity) {
ScopeImpl flowScope = activity.getFlowScope();
ActivityImpl flowScopeActivity = null;
if(flowScope.getProcessDefinition() != flowScope) {
flowScopeActivity = (ActivityImpl) flowScope;
}
return flowScopeActivity;
}
@Override
public String getCanonicalName() {
return "delete-cascade-fire-activity-end";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\operation\PvmAtomicOperationDeleteCascadeFireActivityEnd.java | 1 |
请完成以下Java代码 | private boolean isStaleDocumentChanges(final DocumentChanges documentChanges)
{
final DocumentPath documentPath = documentChanges.getDocumentPath();
if (!documentPath.isSingleIncludedDocument())
{
return false;
}
final DocumentPath rootDocumentPath = documentPath.getRootDocumentPath();
final DetailId detailId = documentPath.getDetailId();
return documentChangesIfExists(rootDocumentPath)
.flatMap(rootDocumentChanges -> rootDocumentChanges.includedDetailInfoIfExists(detailId))
.map(IncludedDetailInfo::isStale)
.orElse(false); | }
@Override
public void collectEvent(final IDocumentFieldChangedEvent event)
{
documentChanges(event.getDocumentPath())
.collectEvent(event);
}
@Override
public void collectFieldWarning(final IDocumentFieldView documentField, final DocumentFieldWarning fieldWarning)
{
documentChanges(documentField)
.collectFieldWarning(documentField, fieldWarning);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentChangesCollector.java | 1 |
请完成以下Java代码 | public void setIsCreateAsActive (boolean IsCreateAsActive)
{
set_Value (COLUMNNAME_IsCreateAsActive, Boolean.valueOf(IsCreateAsActive));
}
/** Get Create As Active.
@return Create Asset and activate it
*/
public boolean isCreateAsActive ()
{
Object oo = get_Value(COLUMNNAME_IsCreateAsActive);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Depreciate.
@param IsDepreciated
The asset will be depreciated
*/
public void setIsDepreciated (boolean IsDepreciated)
{
set_Value (COLUMNNAME_IsDepreciated, Boolean.valueOf(IsDepreciated));
}
/** Get Depreciate.
@return The asset will be depreciated
*/
public boolean isDepreciated ()
{
Object oo = get_Value(COLUMNNAME_IsDepreciated);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set One Asset Per UOM.
@param IsOneAssetPerUOM
Create one asset per UOM
*/
public void setIsOneAssetPerUOM (boolean IsOneAssetPerUOM)
{
set_Value (COLUMNNAME_IsOneAssetPerUOM, Boolean.valueOf(IsOneAssetPerUOM));
}
/** Get One Asset Per UOM.
@return Create one asset per UOM
*/
public boolean isOneAssetPerUOM ()
{
Object oo = get_Value(COLUMNNAME_IsOneAssetPerUOM);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Owned.
@param IsOwned
The asset is owned by the organization
*/
public void setIsOwned (boolean IsOwned)
{
set_Value (COLUMNNAME_IsOwned, Boolean.valueOf(IsOwned));
}
/** Get Owned.
@return The asset is owned by the organization
*/
public boolean isOwned ()
{
Object oo = get_Value(COLUMNNAME_IsOwned);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo); | }
return false;
}
/** Set Track Issues.
@param IsTrackIssues
Enable tracking issues for this asset
*/
public void setIsTrackIssues (boolean IsTrackIssues)
{
set_Value (COLUMNNAME_IsTrackIssues, Boolean.valueOf(IsTrackIssues));
}
/** Get Track Issues.
@return Enable tracking issues for this asset
*/
public boolean isTrackIssues ()
{
Object oo = get_Value(COLUMNNAME_IsTrackIssues);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Group.java | 1 |
请完成以下Java代码 | public static BaseResp<Boolean> success() {
BaseResp<Boolean> response = new BaseResp<Boolean>();
response.setCode(ResultStatus.SUCCESS);
return response;
}
public static <T> BaseResp<T> success(T data, String msg) {
BaseResp<T> response = new BaseResp<T>();
response.setCode(ResultStatus.SUCCESS);
response.setData(data);
response.setMessage(msg);
return response;
}
public static BaseResp<String> fail(String msg) { | BaseResp<String> response = new BaseResp<String>();
response.setCode(ResultStatus.FAIL);
response.setMessage(msg);
return response;
}
public static BaseResp<String> fail(ResultStatus code, String msg) {
BaseResp<String> response = new BaseResp<String>();
response.setCode(code);
response.setMessage(msg);
return response;
}
} | repos\spring-boot-quick-master\quick-platform-common\src\main\java\com\quick\common\base\rest\BaseResp.java | 1 |
请完成以下Java代码 | public EventSubscriptionQueryImpl activityId(String activityId) {
if (activityId == null) {
throw new ActivitiIllegalArgumentException("Provided activity id is null");
}
this.activityId = activityId;
return this;
}
public EventSubscriptionQueryImpl eventType(String eventType) {
if (eventType == null) {
throw new ActivitiIllegalArgumentException("Provided event type is null");
}
this.eventType = eventType;
return this;
}
public String getTenantId() {
return tenantId;
}
public EventSubscriptionQueryImpl tenantId(String tenantId) {
this.tenantId = tenantId;
return this;
}
public EventSubscriptionQueryImpl configuration(String configuration) {
this.configuration = configuration;
return this;
}
public EventSubscriptionQueryImpl orderByCreated() {
return orderBy(EventSubscriptionQueryProperty.CREATED);
}
// results //////////////////////////////////////////
@Override
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext.getEventSubscriptionEntityManager().findEventSubscriptionCountByQueryCriteria(this);
}
@Override | public List<EventSubscriptionEntity> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getEventSubscriptionEntityManager().findEventSubscriptionsByQueryCriteria(this, page);
}
// getters //////////////////////////////////////////
public String getEventSubscriptionId() {
return eventSubscriptionId;
}
public String getEventName() {
return eventName;
}
public String getEventType() {
return eventType;
}
public String getExecutionId() {
return executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getActivityId() {
return activityId;
}
public String getConfiguration() {
return configuration;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\EventSubscriptionQueryImpl.java | 1 |
请完成以下Java代码 | public void notifyGenerated(@Nullable final Collection<? extends I_M_Inventory> inventories)
{
if (inventories == null || inventories.isEmpty())
{
return;
}
notificationBL.sendAfterCommit(inventories.stream()
.map(InventoryUserNotificationsProducer::toUserNotification)
.collect(ImmutableList.toImmutableList()));
}
private static UserNotificationRequest toUserNotification(@NonNull final I_M_Inventory inventory)
{
final TableRecordReference inventoryRef = TableRecordReference.of(inventory);
return UserNotificationRequest.builder()
.topic(EVENTBUS_TOPIC)
.recipientUserId(getNotificationRecipientUserId(inventory))
.contentADMessage(MSG_Event_InventoryGenerated)
.contentADMessageParam(inventoryRef)
.targetAction(TargetRecordAction.ofRecordAndWindow(inventoryRef, WINDOW_INTERNAL_INVENTORY))
.build();
} | private static UserId getNotificationRecipientUserId(final I_M_Inventory inventory)
{
//
// In case of reversal i think we shall notify the current user too
final DocStatus docStatus = DocStatus.ofNullableCodeOrUnknown(inventory.getDocStatus());
if (docStatus.isReversedOrVoided())
{
final UserId loggedUserId = Env.getLoggedUserIdIfExists().orElse(null);
if (loggedUserId != null)
{
return loggedUserId;
}
return UserId.ofRepoId(inventory.getUpdatedBy()); // last updated
}
//
// Fallback: notify only the creator
else
{
return UserId.ofRepoId(inventory.getCreatedBy());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\event\InventoryUserNotificationsProducer.java | 1 |
请完成以下Java代码 | public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setExternalSystem_Config_ID (final int ExternalSystem_Config_ID)
{
if (ExternalSystem_Config_ID < 1)
set_Value (COLUMNNAME_ExternalSystem_Config_ID, null);
else
set_Value (COLUMNNAME_ExternalSystem_Config_ID, ExternalSystem_Config_ID);
}
@Override
public int getExternalSystem_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_ID);
}
@Override
public void setHostKey (final @Nullable java.lang.String HostKey)
{
set_ValueNoCheck (COLUMNNAME_HostKey, HostKey);
}
@Override
public java.lang.String getHostKey()
{
return get_ValueAsString(COLUMNNAME_HostKey);
}
@Override
public void setIPP_URL (final @Nullable java.lang.String IPP_URL)
{
set_Value (COLUMNNAME_IPP_URL, IPP_URL);
}
@Override
public java.lang.String getIPP_URL()
{
return get_ValueAsString(COLUMNNAME_IPP_URL);
}
@Override | public void setName (final java.lang.String Name)
{
set_ValueNoCheck (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
/**
* OutputType AD_Reference_ID=540632
* Reference name: OutputType
*/
public static final int OUTPUTTYPE_AD_Reference_ID=540632;
/** Attach = Attach */
public static final String OUTPUTTYPE_Attach = "Attach";
/** Store = Store */
public static final String OUTPUTTYPE_Store = "Store";
/** Queue = Queue */
public static final String OUTPUTTYPE_Queue = "Queue";
/** Frontend = Frontend */
public static final String OUTPUTTYPE_Frontend = "Frontend";
@Override
public void setOutputType (final java.lang.String OutputType)
{
set_Value (COLUMNNAME_OutputType, OutputType);
}
@Override
public java.lang.String getOutputType()
{
return get_ValueAsString(COLUMNNAME_OutputType);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java-gen\de\metas\printing\model\X_AD_PrinterHW.java | 1 |
请完成以下Java代码 | public IHUPackingMaterialsCollector<IHUPackingMaterialCollectorSource> errorIfAnyHuIsAdded()
{
this.errorIfHuIsAdded = true;
return this;
}
@Value
public static final class HUpipToHUPackingMaterialCollectorSource
{
private @NonNull final I_M_HU_PI_Item_Product hupip;
private final int originalSourceID;
public int getM_HU_PI_Item_Product_ID()
{
return hupip.getM_HU_PI_Item_Product_ID();
}
} | @Override
public IHUPackingMaterialsCollector<IHUPackingMaterialCollectorSource> disable()
{
this.disabled = true;
return this;
}
@Override
public IHUPackingMaterialsCollector<IHUPackingMaterialCollectorSource> copy()
{
return new HUPackingMaterialsCollector(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\spi\impl\HUPackingMaterialsCollector.java | 1 |
请完成以下Java代码 | public void setQtyOrdered_Override (final @Nullable BigDecimal QtyOrdered_Override)
{
set_Value (COLUMNNAME_QtyOrdered_Override, QtyOrdered_Override);
}
@Override
public BigDecimal getQtyOrdered_Override()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyOrdered_Override);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setUPC_CU (final @Nullable java.lang.String UPC_CU)
{
set_Value (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_Value (COLUMNNAME_UPC_TU, UPC_TU);
}
@Override
public java.lang.String getUPC_TU()
{
return get_ValueAsString(COLUMNNAME_UPC_TU);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_DesadvLine.java | 1 |
请完成以下Java代码 | public static Optional<BPartnerLocationId> optionalOfRepoId(
@Nullable final Integer bpartnerId,
@Nullable final Integer bpartnerLocationId)
{
return Optional.ofNullable(ofRepoIdOrNull(bpartnerId, bpartnerLocationId));
}
@Nullable
public static BPartnerLocationId ofRepoIdOrNull(
@Nullable final BPartnerId bpartnerId,
@Nullable final Integer bpartnerLocationId)
{
return bpartnerId != null && bpartnerLocationId != null && bpartnerLocationId > 0 ? ofRepoId(bpartnerId, bpartnerLocationId) : null;
}
@Jacksonized
@Builder
private BPartnerLocationId(@NonNull final BPartnerId bpartnerId, final int repoId)
{ | this.repoId = Check.assumeGreaterThanZero(repoId, "bpartnerLocationId");
this.bpartnerId = bpartnerId;
}
public static int toRepoId(@Nullable final BPartnerLocationId bpLocationId)
{
return bpLocationId != null ? bpLocationId.getRepoId() : -1;
}
@Nullable
public static Integer toRepoIdOrNull(@Nullable final BPartnerLocationId bpLocationId)
{
return bpLocationId != null ? bpLocationId.getRepoId() : null;
}
public static boolean equals(final BPartnerLocationId id1, final BPartnerLocationId id2)
{
return Objects.equals(id1, id2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerLocationId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class UserService {
private UserRepository userRepository;
private String defaultImage;
private PasswordEncoder passwordEncoder;
@Autowired
public UserService(
UserRepository userRepository,
@Value("${image.default}") String defaultImage,
PasswordEncoder passwordEncoder) {
this.userRepository = userRepository;
this.defaultImage = defaultImage;
this.passwordEncoder = passwordEncoder;
}
public User createUser(@Valid RegisterParam registerParam) {
User user =
new User(
registerParam.getEmail(),
registerParam.getUsername(),
passwordEncoder.encode(registerParam.getPassword()),
"",
defaultImage);
userRepository.save(user);
return user;
}
public void updateUser(@Valid UpdateUserCommand command) {
User user = command.getTargetUser();
UpdateUserParam updateUserParam = command.getParam();
user.update(
updateUserParam.getEmail(),
updateUserParam.getUsername(),
updateUserParam.getPassword(),
updateUserParam.getBio(),
updateUserParam.getImage());
userRepository.save(user);
}
}
@Constraint(validatedBy = UpdateUserValidator.class)
@Retention(RetentionPolicy.RUNTIME)
@interface UpdateUserConstraint {
String message() default "invalid update param"; | Class[] groups() default {};
Class[] payload() default {};
}
class UpdateUserValidator implements ConstraintValidator<UpdateUserConstraint, UpdateUserCommand> {
@Autowired private UserRepository userRepository;
@Override
public boolean isValid(UpdateUserCommand value, ConstraintValidatorContext context) {
String inputEmail = value.getParam().getEmail();
String inputUsername = value.getParam().getUsername();
final User targetUser = value.getTargetUser();
boolean isEmailValid =
userRepository.findByEmail(inputEmail).map(user -> user.equals(targetUser)).orElse(true);
boolean isUsernameValid =
userRepository
.findByUsername(inputUsername)
.map(user -> user.equals(targetUser))
.orElse(true);
if (isEmailValid && isUsernameValid) {
return true;
} else {
context.disableDefaultConstraintViolation();
if (!isEmailValid) {
context
.buildConstraintViolationWithTemplate("email already exist")
.addPropertyNode("email")
.addConstraintViolation();
}
if (!isUsernameValid) {
context
.buildConstraintViolationWithTemplate("username already exist")
.addPropertyNode("username")
.addConstraintViolation();
}
return false;
}
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\application\user\UserService.java | 2 |
请完成以下Java代码 | public void planTakeOutgoingSequenceFlowsOperation(ExecutionEntity execution, boolean evaluateConditions) {
planOperation(new TakeOutgoingSequenceFlowsOperation(commandContext, execution, evaluateConditions, false), execution);
}
@Override
public void planTakeOutgoingSequenceFlowsSynchronousOperation(ExecutionEntity execution, boolean evaluateConditions) {
planOperation(new TakeOutgoingSequenceFlowsOperation(commandContext, execution, evaluateConditions, true), execution);
}
@Override
public void planEndExecutionOperation(ExecutionEntity execution) {
planOperation(new EndExecutionOperation(commandContext, execution), execution);
}
@Override
public void planEndExecutionOperationSynchronous(ExecutionEntity execution) {
planOperation(new EndExecutionOperation(commandContext, execution, true), execution);
}
@Override
public void planTriggerExecutionOperation(ExecutionEntity execution) {
planOperation(new TriggerExecutionOperation(commandContext, execution), execution);
}
@Override | public void planAsyncTriggerExecutionOperation(ExecutionEntity execution) {
planOperation(new TriggerExecutionOperation(commandContext, execution, true), execution);
}
@Override
public void planEvaluateConditionalEventsOperation(ExecutionEntity execution) {
planOperation(new EvaluateConditionalEventsOperation(commandContext, execution), execution);
}
@Override
public void planEvaluateVariableListenerEventsOperation(String processDefinitionId, String processInstanceId) {
planOperation(new EvaluateVariableListenerEventDefinitionsOperation(commandContext, processDefinitionId, processInstanceId));
}
@Override
public void planDestroyScopeOperation(ExecutionEntity execution) {
planOperation(new DestroyScopeOperation(commandContext, execution), execution);
}
@Override
public void planExecuteInactiveBehaviorsOperation(Collection<ExecutionEntity> executions) {
planOperation(new ExecuteInactiveBehaviorsOperation(commandContext, executions));
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\agenda\DefaultFlowableEngineAgenda.java | 1 |
请完成以下Java代码 | private static ImmutableSet<String> computeDependsOnFieldNames(
final @Nullable IStringExpression sqlWhereClause,
final @Nullable INamePairPredicate postQueryPredicate)
{
final ImmutableSet.Builder<String> builder = ImmutableSet.builder();
if (sqlWhereClause != null)
{
builder.addAll(sqlWhereClause.getParameterNames());
}
if (postQueryPredicate != null)
{
builder.addAll(postQueryPredicate.getParameters(null));
}
return builder.build();
}
static SqlLookupFilter of(@NonNull final IValidationRule valRule, @Nullable final LookupDescriptorProvider.LookupScope onlyScope)
{
return builder()
.onlyScope(onlyScope)
.sqlWhereClause(valRule.getPrefilterWhereClause()) | .postQueryPredicate(valRule.getPostQueryFilter())
.dependsOnTableNames(valRule.getDependsOnTableNames())
.build();
}
public boolean isMatchingScope(@NonNull final LookupDescriptorProvider.LookupScope scope)
{
return onlyScope == null || onlyScope.equals(scope);
}
public boolean isMatchingForAvailableParameterNames(@Nullable final ImmutableSet<String> availableParameterNames)
{
// TODO: instead of checking all `dependsOnFieldNames` i think we shall remove parameters that will be always provided (e.g. FilterSql etc)
return availableParameterNames == null || availableParameterNames.containsAll(this.dependsOnFieldNames);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\sql\SqlLookupFilter.java | 1 |
请完成以下Java代码 | public class CreateCasePageTaskAfterContext {
protected CasePageTask casePageTask;
protected PlanItemInstanceEntity planItemInstanceEntity;
public CreateCasePageTaskAfterContext() {
}
public CreateCasePageTaskAfterContext(CasePageTask casePageTask, PlanItemInstanceEntity planItemInstanceEntity) {
this.casePageTask = casePageTask;
this.planItemInstanceEntity = planItemInstanceEntity;
}
public CasePageTask getCasePageTask() { | return casePageTask;
}
public void setCasePageTask(CasePageTask casePageTask) {
this.casePageTask = casePageTask;
}
public PlanItemInstanceEntity getPlanItemInstanceEntity() {
return planItemInstanceEntity;
}
public void setPlanItemInstanceEntity(PlanItemInstanceEntity planItemInstanceEntity) {
this.planItemInstanceEntity = planItemInstanceEntity;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\interceptor\CreateCasePageTaskAfterContext.java | 1 |
请完成以下Spring Boot application配置 | server.port=8900
spring.freemarker.suffix=.ftl
#spring.jpa.generate-ddl=false
#spring.datasource.url= jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
#spring.datasource | .username=root
#spring.datasource.password=root
#spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver | repos\tutorials-master\security-modules\cas\cas-secured-app\src\main\resources\application.properties | 2 |
请完成以下Java代码 | public abstract class SpinXmlAttribute extends SpinXmlNode<SpinXmlAttribute> {
/**
* Returns the value of the attribute as {@link String}.
*
* @return the string value of the attribute
*/
public abstract String value();
/**
* Sets the value of the attribute.
*
* @param value the value to set
* @return the wrapped xml dom attribute
* @throws SpinXmlNodeException if the value is null
*/
public abstract SpinXmlAttribute value(String value);
/**
* Removes the attribute.
*
* @return the wrapped owner {@link SpinXmlElement tree element}
*/
public abstract SpinXmlElement remove(); | /**
* Returns the wrapped XML attribute value as string representation.
*
* @return the string representation
*/
public abstract String toString();
/**
* Writes the wrapped XML attribute value to an existing writer.
*
* @param writer the writer to write to
*/
public abstract void writeToWriter(Writer writer);
} | repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\xml\SpinXmlAttribute.java | 1 |
请完成以下Java代码 | protected void prepare() {
for ( ProcessInfoParameter para : getParametersAsArray())
{
if ( para.getParameterName().equals("C_POSKeyLayout_ID") )
posKeyLayoutId = para.getParameterAsInt();
if ( para.getParameterName().equals("M_Product_Category_ID") )
productCategoryId = para.getParameterAsInt();
else
log.info("Parameter not found " + para.getParameterName());
}
if ( posKeyLayoutId == 0 )
{
posKeyLayoutId = getRecord_ID();
}
}
/**
* Generate keys for each product
*/
@Override
protected String doIt() throws Exception {
if ( posKeyLayoutId == 0 )
throw new FillMandatoryException("C_POSKeyLayout_ID");
int count = 0;
String where = "";
Object [] params = new Object[] {};
if ( productCategoryId > 0 )
{
where = "M_Product_Category_ID = ? ";
params = new Object[] {productCategoryId};
} | Query query = new Query(getCtx(), MProduct.Table_Name, where, get_TrxName())
.setParameters(params)
.setOnlyActiveRecords(true)
.setOrderBy("Value");
List<MProduct> products = query.list(MProduct.class);
for (MProduct product : products )
{
final I_C_POSKey key = InterfaceWrapperHelper.newInstance(I_C_POSKey.class, this);
key.setName(product.getName());
key.setM_Product_ID(product.getM_Product_ID());
key.setC_POSKeyLayout_ID(posKeyLayoutId);
key.setSeqNo(count*10);
key.setQty(Env.ONE);
InterfaceWrapperHelper.save(key);
count++;
}
return "@Created@ " + count;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\process\PosKeyGenerate.java | 1 |
请完成以下Java代码 | public class CompositePermissionCheck {
protected boolean disjunctive;
protected List<CompositePermissionCheck> compositeChecks = new ArrayList<CompositePermissionCheck>();
protected List<PermissionCheck> atomicChecks = new ArrayList<PermissionCheck>();
public CompositePermissionCheck() {
this(true);
}
public CompositePermissionCheck(boolean disjunctive) {
this.disjunctive = disjunctive;
}
public void addAtomicCheck(PermissionCheck permissionCheck) {
this.atomicChecks.add(permissionCheck);
}
public void setAtomicChecks(List<PermissionCheck> atomicChecks) {
this.atomicChecks = atomicChecks;
}
public void setCompositeChecks(List<CompositePermissionCheck> subChecks) {
this.compositeChecks = subChecks;
}
public void addCompositeCheck(CompositePermissionCheck subCheck) {
this.compositeChecks.add(subCheck);
}
/**
* conjunctive else
*/
public boolean isDisjunctive() {
return disjunctive;
} | public List<CompositePermissionCheck> getCompositeChecks() {
return compositeChecks;
}
public List<PermissionCheck> getAtomicChecks() {
return atomicChecks;
}
public void clear() {
compositeChecks.clear();
atomicChecks.clear();
}
public List<PermissionCheck> getAllPermissionChecks() {
List<PermissionCheck> allChecks = new ArrayList<PermissionCheck>();
allChecks.addAll(atomicChecks);
for (CompositePermissionCheck compositePermissionCheck : compositeChecks) {
allChecks.addAll(compositePermissionCheck.getAllPermissionChecks());
}
return allChecks;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\CompositePermissionCheck.java | 1 |
请在Spring Boot框架中完成以下Java代码 | class RSocketWebSocketNettyRouteProvider implements NettyRouteProvider {
private final String mappingPath;
private final SocketAcceptor socketAcceptor;
private final List<RSocketServerCustomizer> customizers;
private final Consumer<Builder> serverSpecCustomizer;
RSocketWebSocketNettyRouteProvider(String mappingPath, SocketAcceptor socketAcceptor,
Consumer<Builder> serverSpecCustomizer, Stream<RSocketServerCustomizer> customizers) {
this.mappingPath = mappingPath;
this.socketAcceptor = socketAcceptor;
this.serverSpecCustomizer = serverSpecCustomizer;
this.customizers = customizers.toList();
}
@Override | public HttpServerRoutes apply(HttpServerRoutes httpServerRoutes) {
RSocketServer server = RSocketServer.create(this.socketAcceptor);
this.customizers.forEach((customizer) -> customizer.customize(server));
ServerTransport.ConnectionAcceptor connectionAcceptor = server.asConnectionAcceptor();
return httpServerRoutes.ws(this.mappingPath, WebsocketRouteTransport.newHandler(connectionAcceptor),
createWebsocketServerSpec());
}
private WebsocketServerSpec createWebsocketServerSpec() {
WebsocketServerSpec.Builder builder = WebsocketServerSpec.builder();
this.serverSpecCustomizer.accept(builder);
return builder.build();
}
} | repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketWebSocketNettyRouteProvider.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JsonResponseManufacturingOrdersReport
{
@NonNull
String transactionKey;
@Nullable
JsonError error;
@NonNull
@Singular
List<JsonResponseReceiveFromManufacturingOrder> receipts;
@NonNull
@Singular
List<JsonResponseIssueToManufacturingOrder> issues; | @JsonPOJOBuilder(withPrefix = "")
public static class JsonResponseManufacturingOrdersReportBuilder
{
}
public boolean isOK()
{
return error == null;
}
public boolean hasErrors()
{
return error != null;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-manufacturing\src\main\java\de\metas\common\manufacturing\v1\JsonResponseManufacturingOrdersReport.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class Car extends Vehicle {
private String model;
private String name;
@Embedded
@AttributeOverrides({
@AttributeOverride(name = "name", column = @Column(name = "BRAND_NAME", length = 5)),
@AttributeOverride(name = "address.name", column = @Column(name = "ADDRESS_NAME"))
})
private Brand brand;
@ElementCollection
@AttributeOverrides({
@AttributeOverride(name = "key.name", column = @Column(name = "OWNER_NAME")),
@AttributeOverride(name = "key.surname", column = @Column(name = "OWNER_SURNAME")),
@AttributeOverride(name = "value.name", column = @Column(name = "ADDRESS_NAME")),
})
Map<Owner, Address> owners;
public String getModel() {
return model;
} | public void setModel(String model) {
this.model = model;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Brand getBrand() {
return brand;
}
public void setBrand(Brand brand) {
this.brand = brand;
}
} | repos\tutorials-master\persistence-modules\spring-data-jpa-annotations-2\src\main\java\com\baeldung\attribute\override\entity\Car.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JmxManagedJobExecutor implements PlatformService<JobExecutor>, JmxManagedJobExecutorMBean {
protected final JobExecutor jobExecutor;
public JmxManagedJobExecutor(JobExecutor jobExecutor) {
this.jobExecutor = jobExecutor;
}
public void start(PlatformServiceContainer mBeanServiceContainer) {
// no-op:
// job executor is lazy-started when first process engine is registered and jobExecutorActivate = true
// See: #CAM-4817
}
public void stop(PlatformServiceContainer mBeanServiceContainer) {
shutdown();
}
public void start() {
jobExecutor.start();
}
public void shutdown() {
jobExecutor.shutdown();
}
public int getWaitTimeInMillis() {
return jobExecutor.getWaitTimeInMillis();
}
public void setWaitTimeInMillis(int waitTimeInMillis) {
jobExecutor.setWaitTimeInMillis(waitTimeInMillis);
}
public int getLockTimeInMillis() {
return jobExecutor.getLockTimeInMillis(); | }
public void setLockTimeInMillis(int lockTimeInMillis) {
jobExecutor.setLockTimeInMillis(lockTimeInMillis);
}
public String getLockOwner() {
return jobExecutor.getLockOwner();
}
public void setLockOwner(String lockOwner) {
jobExecutor.setLockOwner(lockOwner);
}
public int getMaxJobsPerAcquisition() {
return jobExecutor.getMaxJobsPerAcquisition();
}
public void setMaxJobsPerAcquisition(int maxJobsPerAcquisition) {
jobExecutor.setMaxJobsPerAcquisition(maxJobsPerAcquisition);
}
public String getName() {
return jobExecutor.getName();
}
public JobExecutor getValue() {
return jobExecutor;
}
public boolean isActive() {
return jobExecutor.isActive();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\services\JmxManagedJobExecutor.java | 2 |
请完成以下Java代码 | public void setInternalName (final @Nullable java.lang.String InternalName)
{
set_Value (COLUMNNAME_InternalName, InternalName);
}
@Override
public java.lang.String getInternalName()
{
return get_ValueAsString(COLUMNNAME_InternalName);
}
@Override
public void setIsDefault (final boolean IsDefault)
{
set_Value (COLUMNNAME_IsDefault, IsDefault);
}
@Override
public boolean isDefault()
{
return get_ValueAsBoolean(COLUMNNAME_IsDefault);
}
@Override
public void setM_Shipper_ID (final int M_Shipper_ID)
{
if (M_Shipper_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipper_ID, M_Shipper_ID);
}
@Override
public int getM_Shipper_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipper_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setPickupTimeFrom (final java.sql.Timestamp PickupTimeFrom)
{
set_Value (COLUMNNAME_PickupTimeFrom, PickupTimeFrom);
}
@Override
public java.sql.Timestamp getPickupTimeFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_PickupTimeFrom);
}
@Override
public void setPickupTimeTo (final java.sql.Timestamp PickupTimeTo)
{
set_Value (COLUMNNAME_PickupTimeTo, PickupTimeTo);
}
@Override
public java.sql.Timestamp getPickupTimeTo()
{ | return get_ValueAsTimestamp(COLUMNNAME_PickupTimeTo);
}
/**
* ShipperGateway AD_Reference_ID=540808
* Reference name: ShipperGateway
*/
public static final int SHIPPERGATEWAY_AD_Reference_ID=540808;
/** GO = go */
public static final String SHIPPERGATEWAY_GO = "go";
/** Der Kurier = derKurier */
public static final String SHIPPERGATEWAY_DerKurier = "derKurier";
/** DHL = dhl */
public static final String SHIPPERGATEWAY_DHL = "dhl";
/** DPD = dpd */
public static final String SHIPPERGATEWAY_DPD = "dpd";
/** nShift = nshift */
public static final String SHIPPERGATEWAY_NShift = "nshift";
@Override
public void setShipperGateway (final @Nullable java.lang.String ShipperGateway)
{
set_Value (COLUMNNAME_ShipperGateway, ShipperGateway);
}
@Override
public java.lang.String getShipperGateway()
{
return get_ValueAsString(COLUMNNAME_ShipperGateway);
}
@Override
public void setTrackingURL (final @Nullable java.lang.String TrackingURL)
{
set_Value (COLUMNNAME_TrackingURL, TrackingURL);
}
@Override
public java.lang.String getTrackingURL()
{
return get_ValueAsString(COLUMNNAME_TrackingURL);
}
@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.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipper.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class InMemoryReactiveClientRegistrationRepository
implements ReactiveClientRegistrationRepository, Iterable<ClientRegistration> {
private final Map<String, ClientRegistration> clientIdToClientRegistration;
/**
* Constructs an {@code InMemoryReactiveClientRegistrationRepository} using the
* provided parameters.
* @param registrations the client registration(s)
*/
public InMemoryReactiveClientRegistrationRepository(ClientRegistration... registrations) {
this(toList(registrations));
}
private static List<ClientRegistration> toList(ClientRegistration... registrations) {
Assert.notEmpty(registrations, "registrations cannot be null or empty");
return Arrays.asList(registrations);
}
/**
* Constructs an {@code InMemoryReactiveClientRegistrationRepository} using the
* provided parameters.
* @param registrations the client registration(s)
*/
public InMemoryReactiveClientRegistrationRepository(List<ClientRegistration> registrations) {
this.clientIdToClientRegistration = toUnmodifiableConcurrentMap(registrations);
}
@Override
public Mono<ClientRegistration> findByRegistrationId(String registrationId) {
return Mono.justOrEmpty(this.clientIdToClientRegistration.get(registrationId));
} | /**
* Returns an {@code Iterator} of {@link ClientRegistration}.
* @return an {@code Iterator<ClientRegistration>}
*/
@Override
public Iterator<ClientRegistration> iterator() {
return this.clientIdToClientRegistration.values().iterator();
}
private static Map<String, ClientRegistration> toUnmodifiableConcurrentMap(List<ClientRegistration> registrations) {
Assert.notEmpty(registrations, "registrations cannot be null or empty");
ConcurrentHashMap<String, ClientRegistration> result = new ConcurrentHashMap<>();
for (ClientRegistration registration : registrations) {
Assert.notNull(registration, "no registration can be null");
if (result.containsKey(registration.getRegistrationId())) {
throw new IllegalStateException(String.format("Duplicate key %s", registration.getRegistrationId()));
}
result.put(registration.getRegistrationId(), registration);
}
return Collections.unmodifiableMap(result);
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\registration\InMemoryReactiveClientRegistrationRepository.java | 2 |
请完成以下Java代码 | public static List<DepartIdModel> wrapTreeDataToDepartIdTreeList(List<SysDepart> recordList) {
// 在该方法每请求一次,都要对全局list集合进行一次清理
//idList.clear();
List<DepartIdModel> idList = new ArrayList<DepartIdModel>();
List<SysDepartTreeModel> records = new ArrayList<>();
for (int i = 0; i < recordList.size(); i++) {
SysDepart depart = recordList.get(i);
records.add(new SysDepartTreeModel(depart));
}
findChildren(records, idList);
return idList;
}
/**
* queryTreeList的子方法 ====2=====
* 该方法是找到并封装顶级父类的节点到TreeList集合
*/
private static List<SysDepartTreeModel> findChildren(List<SysDepartTreeModel> recordList,
List<DepartIdModel> departIdList) {
List<SysDepartTreeModel> treeList = new ArrayList<>();
for (int i = 0; i < recordList.size(); i++) {
SysDepartTreeModel branch = recordList.get(i);
if (oConvertUtils.isEmpty(branch.getParentId())) {
treeList.add(branch);
DepartIdModel departIdModel = new DepartIdModel().convert(branch);
departIdList.add(departIdModel);
}
}
getGrandChildren(treeList,recordList,departIdList);
//idList = departIdList;
return treeList;
}
/**
* queryTreeList的子方法====3====
*该方法是找到顶级父类下的所有子节点集合并封装到TreeList集合
*/
private static void getGrandChildren(List<SysDepartTreeModel> treeList,List<SysDepartTreeModel> recordList,List<DepartIdModel> idList) {
for (int i = 0; i < treeList.size(); i++) {
SysDepartTreeModel model = treeList.get(i);
DepartIdModel idModel = idList.get(i);
for (int i1 = 0; i1 < recordList.size(); i1++) {
SysDepartTreeModel m = recordList.get(i1);
if (m.getParentId()!=null && m.getParentId().equals(model.getId())) {
model.getChildren().add(m);
DepartIdModel dim = new DepartIdModel().convert(m);
idModel.getChildren().add(dim);
} | }
getGrandChildren(treeList.get(i).getChildren(), recordList, idList.get(i).getChildren());
}
}
/**
* queryTreeList的子方法 ====4====
* 该方法是将子节点为空的List集合设置为Null值
*/
private static void setEmptyChildrenAsNull(List<SysDepartTreeModel> treeList) {
for (int i = 0; i < treeList.size(); i++) {
SysDepartTreeModel model = treeList.get(i);
if (model.getChildren().size() == 0) {
model.setChildren(null);
model.setIsLeaf(true);
}else{
setEmptyChildrenAsNull(model.getChildren());
model.setIsLeaf(false);
}
}
// sysDepartTreeList = treeList;
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\util\FindsDepartsChildrenUtil.java | 1 |
请完成以下Java代码 | public void setC_DirectDebitLine_ID (int C_DirectDebitLine_ID)
{
if (C_DirectDebitLine_ID < 1)
throw new IllegalArgumentException ("C_DirectDebitLine_ID is mandatory.");
set_ValueNoCheck (COLUMNNAME_C_DirectDebitLine_ID, Integer.valueOf(C_DirectDebitLine_ID));
}
/** Get C_DirectDebitLine_ID.
@return C_DirectDebitLine_ID */
@Override
public int getC_DirectDebitLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_DirectDebitLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public I_C_Invoice getC_Invoice() throws Exception
{
return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class);
}
/** Set Invoice.
@param C_Invoice_ID
Invoice Identifier | */
@Override
public void setC_Invoice_ID (int C_Invoice_ID)
{
if (C_Invoice_ID < 1)
throw new IllegalArgumentException ("C_Invoice_ID is mandatory.");
set_Value (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID));
}
/** Get Invoice.
@return Invoice Identifier
*/
@Override
public int getC_Invoice_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_DirectDebitLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private void releaseAdvisoryLock() {
try {
jdbcTemplate.queryForObject(
"SELECT pg_advisory_unlock(?)",
Boolean.class,
ADVISORY_LOCK_ID
);
log.debug("Released advisory lock");
} catch (Exception e) {
log.error("Failed to release advisory lock", e);
}
}
private VersionInfo parseVersion(String version) {
try {
String[] parts = version.split("\\.");
int major = Integer.parseInt(parts[0]);
int minor = parts.length > 1 ? Integer.parseInt(parts[1]) : 0;
int maintenance = parts.length > 2 ? Integer.parseInt(parts[2]) : 0;
int patch = parts.length > 3 ? Integer.parseInt(parts[3]) : 0;
return new VersionInfo(major, minor, maintenance, patch);
} catch (Exception e) {
log.error("Failed to parse version: {}", version, e);
return null;
} | }
private Stream<Path> listDir(Path dir) {
try {
return Files.list(dir);
} catch (NoSuchFileException e) {
return Stream.empty();
} catch (IOException e) {
throw new UncheckedIOException(e);
}
}
public record VersionInfo(int major, int minor, int maintenance, int patch) {}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\system\SystemPatchApplier.java | 2 |
请完成以下Java代码 | public Properties loadFromFile(@NonNull final File dir, @NonNull final String filename)
{
final File settingsFile = new File(
directoryChecker.checkDirectory(filename, dir),
filename);
return loadFromFile(settingsFile);
}
public Properties loadFromFile(@NonNull final File settingsFile)
{
final Properties fileProperties = new Properties();
try (final FileInputStream in = new FileInputStream(settingsFile);)
{
fileProperties.load(in);
}
catch (final IOException e) | {
throw new CantLoadPropertiesException("Cannot load " + settingsFile, e);
}
return fileProperties;
}
public static final class CantLoadPropertiesException extends RuntimeException
{
private static final long serialVersionUID = 4240250517349321980L;
public CantLoadPropertiesException(@NonNull final String msg, @NonNull final Exception e)
{
super(msg, e);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.cli\src\main\java\de\metas\migration\cli\rollout_migrate\PropertiesFileLoader.java | 1 |
请完成以下Java代码 | public static void main(String args[]) {
//
// Connect to cluster (default is localhost:27017)
//
setUp();
//
// Update with upsert operation
//
updateOperations();
//
// Update with upsert operation using setOnInsert
//
updateSetOnInsertOperations(); | //
// Update with upsert operation using findOneAndUpdate
//
findOneAndUpdateOperations();
//
// Update with upsert operation using replaceOneOperations
//
replaceOneOperations();
}
} | repos\tutorials-master\persistence-modules\java-mongodb-2\src\main\java\com\baeldung\mongo\update\UpsertOperations.java | 1 |
请完成以下Java代码 | public boolean isAllowDifferentCapacities()
{
return allowDifferentCapacities;
}
@Override
public boolean accept(final I_M_HU_PI_Item_Product itemProduct)
{
final Object capacityKey = createCapacityKey(itemProduct);
final int piItemId = itemProduct.getM_HU_PI_Item_ID();
if (!seenSet.add(Util.mkKey(I_M_HU_PI_Item.Table_Name, piItemId, capacityKey)))
{
// already added
return false;
}
final I_M_HU_PI_Item piItem = itemProduct.getM_HU_PI_Item();
if (!piItem.isActive())
{
return false;
}
final int piVersionId = piItem.getM_HU_PI_Version_ID();
if (!seenSet.add(Util.mkKey(I_M_HU_PI_Version.Table_Name, piVersionId, capacityKey)))
{
// already added
return false;
}
final I_M_HU_PI_Version piVersion = piItem.getM_HU_PI_Version();
if (!piVersion.isActive())
{
return false;
}
if (!piVersion.isCurrent())
{
return false; | }
final int piId = piVersion.getM_HU_PI_ID();
if (!seenSet.add(Util.mkKey(I_M_HU_PI.Table_Name, piId, capacityKey)))
{
// already added
return false;
}
// if (!Services.get(IHandlingUnitsBL.class).isConcretePI(piId))
// {
// // skip Virtual PIs, No HU PIs
// return false;
// }
return true;
}
private Object createCapacityKey(final I_M_HU_PI_Item_Product itemProduct)
{
if (!allowDifferentCapacities)
{
return null;
}
else if (itemProduct.isInfiniteCapacity())
{
return "INFINITE";
}
else
{
return itemProduct.getQty();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductRetainOnePerPIFilter.java | 1 |
请完成以下Java代码 | public boolean isSingleProductWithQtyEqualsTo(@NonNull final ProductId productId, @NonNull final Quantity qty)
{
return getStorage().isSingleProductWithQtyEqualsTo(productId, qty);
}
@NonNull
public HuPackingInstructionsId getPackingInstructionsId()
{
HuPackingInstructionsId packingInstructionsId = this._packingInstructionsId;
if (packingInstructionsId == null)
{
packingInstructionsId = this._packingInstructionsId = handlingUnitsBL.getPackingInstructionsId(hu);
}
return packingInstructionsId;
}
}
//
//
// ------------------------------------
//
//
private static class PickFromHUsList
{
private final ArrayList<PickFromHU> list = new ArrayList<>();
PickFromHUsList() {}
public void add(@NonNull final PickFromHU pickFromHU) {list.add(pickFromHU);}
public List<I_M_HU> toHUsList() {return list.stream().map(PickFromHU::toM_HU).collect(ImmutableList.toImmutableList());}
public PickFromHU getSingleHU() {return CollectionUtils.singleElement(list);}
public boolean isSingleHUAlreadyPacked(
final boolean checkIfAlreadyPacked,
@NonNull final ProductId productId,
@NonNull final Quantity qty,
@Nullable final HuPackingInstructionsId packingInstructionsId)
{
if (list.size() != 1)
{ | return false;
}
final PickFromHU hu = list.get(0);
// NOTE we check isGeneratedFromInventory because we want to avoid splitting an HU that we just generated it, even if checkIfAlreadyPacked=false
if (checkIfAlreadyPacked || hu.isGeneratedFromInventory())
{
return hu.isAlreadyPacked(productId, qty, packingInstructionsId);
}
else
{
return false;
}
}
}
//
//
// ------------------------------------
//
//
@Value(staticConstructor = "of")
@EqualsAndHashCode(doNotUseGetters = true)
private static class HuPackingInstructionsIdAndCaptionAndCapacity
{
@NonNull HuPackingInstructionsId huPackingInstructionsId;
@NonNull String caption;
@Nullable Capacity capacity;
@Nullable
public Capacity getCapacityOrNull() {return capacity;}
@SuppressWarnings("unused")
@NonNull
public Optional<Capacity> getCapacity() {return Optional.ofNullable(capacity);}
public TUPickingTarget toTUPickingTarget()
{
return TUPickingTarget.ofPackingInstructions(huPackingInstructionsId, caption);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\candidate\commands\PackToHUsProducer.java | 1 |
请完成以下Java代码 | private void updateStockAvailability(
@NonNull final MSV3StockAvailability request,
final String mfSyncToken,
@NonNull final MSV3EventVersion mfEventVersion)
{
if (request.isDelete())
{
stockAvailabilityRepo
.deleteInBatchByMfPznAndMfEventVersionLessThan(
request.getPzn(),
mfEventVersion.getAsInt());
}
else
{
JpaStockAvailability jpaStockAvailability = stockAvailabilityRepo.findByMfPzn(request.getPzn());
if (jpaStockAvailability == null)
{
jpaStockAvailability = new JpaStockAvailability();
jpaStockAvailability.setMfPzn(request.getPzn());
}
else if (jpaStockAvailability.getMfEventVersion() > mfEventVersion.getAsInt())
{
logger.debug("Discard request with mfEventVersion={} because our local record has mfEventVersion={}; request={}",
mfEventVersion, jpaStockAvailability.getMfEventVersion(), request);
return;
}
jpaStockAvailability.setMfEventVersion(mfEventVersion.getAsInt());
jpaStockAvailability.setMfQty(request.getQty());
jpaStockAvailability.setMfSyncToken(mfSyncToken);
stockAvailabilityRepo.save(jpaStockAvailability);
}
}
@Transactional
public void handleEvent(@NonNull final MSV3ProductExcludesUpdateEvent event)
{
final String syncToken = event.getId();
//
// Update
{
final AtomicInteger countUpdated = new AtomicInteger();
event.getItems().forEach(eventItem -> {
updateProductExclude(eventItem, syncToken);
countUpdated.incrementAndGet();
});
logger.debug("Updated {} product exclude records", countUpdated);
}
//
// Delete | if (event.isDeleteAllOtherItems())
{
final long countDeleted = productExcludeRepo.deleteInBatchBySyncTokenNot(syncToken);
logger.debug("Deleted {} product exclude records", countDeleted);
}
}
private void updateProductExclude(@NonNull final MSV3ProductExclude request, final String syncToken)
{
if (request.isDelete())
{
productExcludeRepo.deleteInBatchByPznAndMfBpartnerId(request.getPzn().getValueAsLong(), request.getBpartnerId());
}
else
{
JpaProductExclude jpaProductExclude = productExcludeRepo.findByPznAndMfBpartnerId(request.getPzn().getValueAsLong(), request.getBpartnerId());
if (jpaProductExclude == null)
{
jpaProductExclude = new JpaProductExclude();
jpaProductExclude.setPzn(request.getPzn().getValueAsLong());
jpaProductExclude.setMfBpartnerId(request.getBpartnerId());
}
jpaProductExclude.setSyncToken(syncToken);
productExcludeRepo.save(jpaProductExclude);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\stockAvailability\StockAvailabilityService.java | 1 |
请完成以下Java代码 | private FieldDeclaration addInstanceVar(ConstructorDeclaration constructor, TypeReference typeReference, TypeDeclaration innerClass) {
FieldDeclaration field = new FieldDeclaration();
field.modifiers = AccPrivate | AccStatic | AccFinal;
field.name = "INSTANCE".toCharArray();
field.type = typeReference;
AllocationExpression exp = new AllocationExpression();
exp.type = typeReference;
exp.binding = constructor.binding;
exp.sourceStart = innerClass.sourceStart;
exp.sourceEnd = innerClass.sourceEnd;
field.initialization = exp;
return field;
} | private ConstructorDeclaration addConstructor(EclipseNode singletonClass, TypeDeclaration astNode) {
ConstructorDeclaration constructor = new ConstructorDeclaration(astNode.compilationResult);
constructor.modifiers = AccPrivate;
constructor.selector = astNode.name;
constructor.sourceStart = astNode.sourceStart;
constructor.sourceEnd = astNode.sourceEnd;
constructor.thrownExceptions = null;
constructor.typeParameters = null;
constructor.bits |= ECLIPSE_DO_NOT_TOUCH_FLAG;
constructor.bodyStart = constructor.declarationSourceStart = constructor.sourceStart = astNode.sourceStart;
constructor.bodyEnd = constructor.declarationSourceEnd = constructor.sourceEnd = astNode.sourceEnd;
constructor.arguments = null;
EclipseHandlerUtil.injectMethod(singletonClass, constructor);
return constructor;
}
} | repos\tutorials-master\lombok-modules\lombok-custom\src\main\java\com\baeldung\singleton\handlers\SingletonEclipseHandler.java | 1 |
请完成以下Java代码 | public class PrintColor {
public static void main(String[] args) {
logColorUsingANSICodes();
logColorUsingLogger();
logColorUsingJANSI();
}
private static void logColorUsingANSICodes() {
System.out.println("Here's some text");
System.out.println("\u001B[31m" + "and now the text is red" + "\u001B[0m");
System.out.println("and now back to the default");
}
private static void logColorUsingLogger() {
ColorLogger colorLogger = new ColorLogger();
colorLogger.logDebug("Some debug logging");
colorLogger.logInfo("Some info logging");
colorLogger.logError("Some error logging");
}
private static void logColorUsingJANSI() {
AnsiConsole.systemInstall();
System.out.println(ansi().fgRed().a("Some red text").fgYellow().a(" and some yellow text").reset()); | AnsiConsole.systemUninstall();
}
}
/*
* More ANSI codes:
*
* Always conclude your logging with the ANSI reset code: "\u001B[0m"
*
* In each case, replace # with the corresponding number:
*
* 0 = black
* 1 = red
* 2 = green
* 3 = yellow
* 4 = blue
* 5 = purple
* 6 = cyan (light blue)
* 7 = white
*
* \u001B[3#m = color font
* \u001B[4#m = color background
* \u001B[1;3#m = bold font
* \u001B[4;3#m = underlined font
* \u001B[3;3#m = italics font (not widely supported, works in VS Code)
*/ | repos\tutorials-master\core-java-modules\core-java-console\src\main\java\com\baeldung\color\PrintColor.java | 1 |
请完成以下Java代码 | public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setM_DiscountSchema_Calculated_Surcharge_ID (final int M_DiscountSchema_Calculated_Surcharge_ID)
{
if (M_DiscountSchema_Calculated_Surcharge_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID, M_DiscountSchema_Calculated_Surcharge_ID);
}
@Override
public int getM_DiscountSchema_Calculated_Surcharge_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_Calculated_Surcharge_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
} | @Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setSurcharge_Calc_SQL (final java.lang.String Surcharge_Calc_SQL)
{
set_Value (COLUMNNAME_Surcharge_Calc_SQL, Surcharge_Calc_SQL);
}
@Override
public java.lang.String getSurcharge_Calc_SQL()
{
return get_ValueAsString(COLUMNNAME_Surcharge_Calc_SQL);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchema_Calculated_Surcharge.java | 1 |
请完成以下Java代码 | public class HUContextDateTrxProvider
{
public interface ITemporaryDateTrx extends AutoCloseable
{
@Override void close();
}
/** Thread Local used to hold the DateTrx overrides */
private final ThreadLocal<ZonedDateTime> dateRef = new ThreadLocal<>();
/**
* Gets DateTrx.
*
* By default, it will return {@link SystemTime#asDate()}.
*
* @return date trx;
*/
public ZonedDateTime getDateTrx()
{
final ZonedDateTime date = dateRef.get();
if (date != null)
{
return date;
}
return de.metas.common.util.time.SystemTime.asZonedDateTime();
}
/**
* Temporary override current date provider by given date.
*
* @param date
* @return
*/ | public ITemporaryDateTrx temporarySet(@NonNull final Date date)
{
return temporarySet(TimeUtil.asZonedDateTime(date));
}
public ITemporaryDateTrx temporarySet(@NonNull final ZonedDateTime date)
{
final ZonedDateTime dateOld = dateRef.get();
dateRef.set(date);
return () -> dateRef.set(dateOld);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\HUContextDateTrxProvider.java | 1 |
请完成以下Java代码 | public void setUserObject(final Object userObject)
{
final String textOld = getText();
final int caretPosition = getTextCaretPosition();
//
super.setUserObject(userObject);
// Object valueOld = editor.getValue();
Object value = null;
if (userObject == null)
{
editor.setValue(null);
}
else if (userObject instanceof ValueNamePair)
{
ValueNamePair vnp = (ValueNamePair)userObject;
value = vnp.getValue();
}
else if (userObject instanceof KeyNamePair)
{
KeyNamePair knp = (KeyNamePair)userObject; | value = knp.getKey();
}
else
{
log.warn("Not supported - {}, class={}", userObject, userObject.getClass());
return;
}
editor.actionCombo(value);
if (value == null)
{
setText(textOld);
setTextCaretPosition(caretPosition);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\VLookupAutoCompleter.java | 1 |
请完成以下Java代码 | public static boolean hasRealActivityId(String jobHandlerConfiguration) {
try {
JsonNode cfgJson = readJsonValue(jobHandlerConfiguration);
JsonNode keyNode = cfgJson.get(PROPERTYNAME_PROCESS_DEFINITION_KEY);
if (keyNode != null && !keyNode.isNull()) {
return !keyNode.asString().isEmpty();
} else {
return false;
}
} catch (JacksonException ex) {
return false;
}
}
protected static ObjectNode createObjectNode() { | return Context.getProcessEngineConfiguration().getObjectMapper().createObjectNode();
}
protected static ObjectNode readJsonValueAsObjectNode(String config) throws JacksonException {
return (ObjectNode) readJsonValue(config);
}
protected static JsonNode readJsonValue(String config) throws JacksonException {
if (Context.getCommandContext() != null) {
return Context.getProcessEngineConfiguration().getObjectMapper().readTree(config);
} else {
return JsonMapper.shared().readTree(config);
}
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\jobexecutor\TimerEventHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Post {
@Id
private Long id;
@Lob
private String content;
@JsonManagedReference
@OneToMany(cascade = CascadeType.ALL, mappedBy = "post", fetch = FetchType.EAGER)
private List<Comment> comments;
@JsonBackReference
@ManyToOne
private User author;
public Post() {
}
public Long getId() {
return this.id;
}
public String getContent() {
return this.content;
}
public List<Comment> getComments() {
return this.comments;
}
public User getAuthor() {
return this.author;
}
public void setId(Long id) {
this.id = id;
}
public void setContent(String content) {
this.content = content;
}
public void setComments(List<Comment> comments) {
this.comments = comments;
}
public void setAuthor(User author) {
this.author = author;
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Post post = (Post) o;
return Objects.equals(id, post.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String toString() {
return "Post(id=" + this.getId() + ", content=" + this.getContent() + ", comments=" + this.getComments() + ", author="
+ this.getAuthor() + ")";
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\Post.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Filter tracingFilter(HttpTracing httpTracing) { // 拦截请求,记录 HTTP 请求的链路信息
return TracingFilter.create(httpTracing);
}
// ==================== SpringMVC 相关 ====================
// @see SpringMvcConfiguration 类上的,@Import(SpanCustomizingAsyncHandlerInterceptor.class) 。因为 SpanCustomizingAsyncHandlerInterceptor 未提供 public 构造方法
// ==================== Kafka 相关 ====================
@Bean
public KafkaTracing kafkaTracing(Tracing tracing) {
return KafkaTracing.newBuilder(tracing)
.remoteServiceName("demo-mq-kafka") // 远程 Kafka 服务名,可自定义
.build();
}
@Bean
public ProducerFactory<?, ?> kafkaProducerFactory(KafkaProperties properties, KafkaTracing kafkaTracing) {
// 创建 DefaultKafkaProducerFactory 对象
DefaultKafkaProducerFactory<?, ?> factory = new DefaultKafkaProducerFactory(properties.buildProducerProperties()) {
@Override
public Producer createProducer() {
// 创建默认的 Producer
Producer<?, ?> producer = super.createProducer();
// 创建可链路追踪的 Producer
return kafkaTracing.producer(producer);
}
};
// 设置事务前缀
String transactionIdPrefix = properties.getProducer().getTransactionIdPrefix();
if (transactionIdPrefix != null) {
factory.setTransactionIdPrefix(transactionIdPrefix); | }
return factory;
}
@Bean
public ConsumerFactory<?, ?> kafkaConsumerFactory(KafkaProperties properties, KafkaTracing kafkaTracing) {
// 创建 DefaultKafkaConsumerFactory 对象
return new DefaultKafkaConsumerFactory(properties.buildConsumerProperties()) {
@Override
public Consumer<?, ?> createConsumer(String groupId, String clientIdPrefix, String clientIdSuffix) {
return this.createConsumer(groupId, clientIdPrefix, clientIdSuffix, null);
}
@Override
public Consumer<?, ?> createConsumer(String groupId, String clientIdPrefix, final String clientIdSuffixArg, Properties properties) {
// 创建默认的 Consumer
Consumer<?, ?> consumer = super.createConsumer(groupId, clientIdPrefix, clientIdSuffixArg, properties);
// 创建可链路追踪的 Consumer
return kafkaTracing.consumer(consumer);
}
};
}
} | repos\SpringBoot-Labs-master\lab-40\lab-40-kafka\src\main\java\cn\iocoder\springboot\lab40\zipkindemo\config\ZipkinConfiguration.java | 2 |
请完成以下Java代码 | public String toString()
{
StringBuffer sb = new StringBuffer("MGoal[");
sb.append(get_ID())
.append("-").append(getName())
.append(",").append(getGoalPerformance())
.append("]");
return sb.toString();
} // toString
/**
* Before Save
*
* @param newRecord new
* @return true
*/
@Override
protected boolean beforeSave(boolean newRecord)
{
// if (getMultiplier(this) == null) // error
// setMeasureDisplay(getMeasureScope());
// Measure required if nor Summary
if (!isSummary() && getPA_Measure_ID() == 0)
{
throw new FillMandatoryException("PA_Measure_ID");
}
if (isSummary() && getPA_Measure_ID() != 0)
setPA_Measure_ID(0);
// User/Role Check
if ((newRecord || is_ValueChanged("AD_User_ID") || is_ValueChanged("AD_Role_ID"))
&& getAD_User_ID() != 0)
{
final List<IUserRolePermissions> roles = Services.get(IUserRolePermissionsDAO.class)
.retrieveUserRolesPermissionsForUserWithOrgAccess(
ClientId.ofRepoId(getAD_Client_ID()),
OrgId.ofRepoId(getAD_Org_ID()),
UserId.ofRepoId(getAD_User_ID()),
Env.getLocalDate());
if (roles.isEmpty()) // No Role
{
setAD_Role_ID(0);
}
else if (roles.size() == 1) // One
{
setAD_Role_ID(roles.get(0).getRoleId().getRepoId());
}
else
{
int AD_Role_ID = getAD_Role_ID();
if (AD_Role_ID != 0) // validate
{
boolean found = false;
for (IUserRolePermissions role : roles)
{
if (AD_Role_ID == role.getRoleId().getRepoId())
{
found = true;
break; | }
}
if (!found)
AD_Role_ID = 0;
}
if (AD_Role_ID == 0) // set to first one
setAD_Role_ID(roles.get(0).getRoleId().getRepoId());
} // multiple roles
} // user check
return true;
} // beforeSave
/**
* After Save
*
* @param newRecord new
* @param success success
* @return true
*/
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
if (!success)
return success;
// Update Goal if Target / Scope Changed
if (newRecord
|| is_ValueChanged("MeasureTarget")
|| is_ValueChanged("MeasureScope"))
updateGoal(true);
return success;
}
} // MGoal | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MGoal.java | 1 |
请完成以下Java代码 | public Amount negate()
{
return isZero()
? this
: new Amount(value.negate(), currencyCode);
}
public Amount negateIf(final boolean condition)
{
return condition ? negate() : this;
}
public Amount negateIfNot(final boolean condition)
{
return !condition ? negate() : this;
}
public Amount add(@NonNull final Amount amtToAdd)
{
assertSameCurrency(this, amtToAdd);
if (amtToAdd.isZero())
{
return this;
}
else if (isZero())
{
return amtToAdd;
}
else
{
return new Amount(value.add(amtToAdd.value), currencyCode);
}
}
public Amount subtract(@NonNull final Amount amtToSubtract)
{
assertSameCurrency(this, amtToSubtract);
if (amtToSubtract.isZero())
{
return this; | }
else
{
return new Amount(value.subtract(amtToSubtract.value), currencyCode);
}
}
public Amount multiply(@NonNull final Percent percent, @NonNull final CurrencyPrecision precision)
{
final BigDecimal newValue = percent.computePercentageOf(value, precision.toInt(), precision.getRoundingMode());
return !newValue.equals(value)
? new Amount(newValue, currencyCode)
: this;
}
public Amount abs()
{
return value.signum() < 0
? new Amount(value.abs(), currencyCode)
: this;
}
public Money toMoney(@NonNull final Function<CurrencyCode, CurrencyId> currencyIdMapper)
{
return Money.of(value, currencyIdMapper.apply(currencyCode));
}
public static boolean equals(@Nullable final Amount a1, @Nullable final Amount a2) {return Objects.equals(a1, a2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\currency\Amount.java | 1 |
请完成以下Java代码 | public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public int getRevisionNext() {
return revision + 1;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public void forceUpdate() {
this.forcedUpdate = true;
}
public Object getPersistentState() {
Map<String, Object> persistentState = new HashMap<String, Object>();
persistentState.put("satisfied", isSatisfied());
if (forcedUpdate) {
persistentState.put("forcedUpdate", Boolean.TRUE);
}
return persistentState;
}
// helper ////////////////////////////////////////////////////////////////////
protected CaseExecutionEntity findCaseExecutionById(String caseExecutionId) {
return Context
.getCommandContext()
.getCaseExecutionManager()
.findCaseExecutionById(caseExecutionId);
} | @Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
if (caseExecutionId != null) {
referenceIdAndClass.put(caseExecutionId, CaseExecutionEntity.class);
}
if (caseInstanceId != null) {
referenceIdAndClass.put(caseInstanceId, CaseExecutionEntity.class);
}
return referenceIdAndClass;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\entity\runtime\CaseSentryPartEntity.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Consumer<Builder> customizeWebsocketServerSpec(Spec spec) {
return (builder) -> {
PropertyMapper map = PropertyMapper.get();
map.from(spec.getProtocols()).to(builder::protocols);
map.from(spec.getMaxFramePayloadLength()).asInt(DataSize::toBytes).to(builder::maxFramePayloadLength);
map.from(spec.isHandlePing()).to(builder::handlePing);
map.from(spec.isCompress()).to(builder::compress);
};
}
}
@ConditionalOnProperty("spring.rsocket.server.port")
@ConditionalOnClass(ReactorResourceFactory.class)
@Configuration(proxyBeanMethods = false)
@Import(ReactorNettyConfigurations.ReactorResourceFactoryConfiguration.class)
static class EmbeddedServerConfiguration {
@Bean
@ConditionalOnMissingBean
RSocketServerFactory rSocketServerFactory(RSocketProperties properties, ReactorResourceFactory resourceFactory,
ObjectProvider<RSocketServerCustomizer> customizers, ObjectProvider<SslBundles> sslBundles) {
NettyRSocketServerFactory factory = new NettyRSocketServerFactory();
factory.setResourceFactory(resourceFactory);
factory.setTransport(properties.getServer().getTransport());
PropertyMapper map = PropertyMapper.get();
map.from(properties.getServer().getAddress()).to(factory::setAddress);
map.from(properties.getServer().getPort()).to(factory::setPort);
map.from(properties.getServer().getFragmentSize()).to(factory::setFragmentSize);
map.from(properties.getServer().getSsl()).to(factory::setSsl);
factory.setSslBundles(sslBundles.getIfAvailable());
factory.setRSocketServerCustomizers(customizers.orderedStream().toList());
return factory;
}
@Bean
@ConditionalOnMissingBean
RSocketServerBootstrap rSocketServerBootstrap(RSocketServerFactory rSocketServerFactory,
RSocketMessageHandler rSocketMessageHandler) {
return new RSocketServerBootstrap(rSocketServerFactory, rSocketMessageHandler.responder());
} | @Bean
RSocketServerCustomizer frameDecoderRSocketServerCustomizer(RSocketMessageHandler rSocketMessageHandler) {
return (server) -> {
if (rSocketMessageHandler.getRSocketStrategies()
.dataBufferFactory() instanceof NettyDataBufferFactory) {
server.payloadDecoder(PayloadDecoder.ZERO_COPY);
}
};
}
}
static class OnRSocketWebServerCondition extends AllNestedConditions {
OnRSocketWebServerCondition() {
super(ConfigurationPhase.PARSE_CONFIGURATION);
}
@ConditionalOnWebApplication(type = Type.REACTIVE)
static class IsReactiveWebApplication {
}
@ConditionalOnProperty(name = "spring.rsocket.server.port", matchIfMissing = true)
static class HasNoPortConfigured {
}
@ConditionalOnProperty("spring.rsocket.server.mapping-path")
static class HasMappingPathConfigured {
}
@ConditionalOnProperty(name = "spring.rsocket.server.transport", havingValue = "websocket")
static class HasWebsocketTransportConfigured {
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-rsocket\src\main\java\org\springframework\boot\rsocket\autoconfigure\RSocketServerAutoConfiguration.java | 2 |
请完成以下Java代码 | public void onAfterQuery(final ICalloutRecord calloutRecord)
{
updateFacets(calloutRecord);
}
@Override
public void onRefreshAll(final ICalloutRecord calloutRecord)
{
// NOTE: we are not updating the facets on refresh all because following case would fail:
// Case: user is pressing the "Refresh" toolbar button to refresh THE content of the grid,
// but user is not expecting to have all it's facets reset.
// updateFacets(gridTab);
}
/**
* Retrieve invoice candidates facets from current grid tab rows and add them to window side panel
*
* @param calloutRecord
* @param http://dewiki908/mediawiki/index.php/08602_Rechnungsdispo_UI_%28106621797084%29 | */
private void updateFacets(final ICalloutRecord calloutRecord)
{
//
// If user asked to approve for invoicing some ICs, the grid will be asked to refresh all,
// but in this case we don't want to reset current facets and recollect them
if (action_ApproveForInvoicing.isRunning())
{
return;
}
//
// Collect the facets from current grid tab rows and fully update the facets pool.
gridTabFacetExecutor.collectFacetsAndResetPool();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\callout\C_Invoice_Candidate_TabCallout.java | 1 |
请完成以下Java代码 | public class ColumnSyncDDLExecutable implements IPostponedExecutable
{
private static final Logger logger = LogManager.getLogger(ColumnSyncDDLExecutable.class);
private final AdColumnId adColumnId;
private final boolean drop;
public ColumnSyncDDLExecutable(@NonNull final AdColumnId adColumnId, final boolean drop)
{
this.adColumnId = adColumnId;
this.drop = drop;
}
@Override
public void execute() | {
if (drop)
{
// TODO unsync column?
final IADTableDAO adTableDAO = Services.get(IADTableDAO.class);
final MinimalColumnInfo column = adTableDAO.getMinimalColumnInfo(adColumnId);
final String tableName = adTableDAO.retrieveTableName(column.getAdTableId());
logger.warn("Please manualy drop column {}.{}", tableName, column.getColumnName());
}
else
{
final TableDDLSyncService syncService = SpringContextHolder.instance.getBean(TableDDLSyncService.class);
syncService.syncToDatabase(adColumnId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\executor\impl\ColumnSyncDDLExecutable.java | 1 |
请完成以下Java代码 | public class SentryPartInstanceEntityManagerImpl
extends AbstractEngineEntityManager<CmmnEngineConfiguration, SentryPartInstanceEntity, SentryPartInstanceDataManager>
implements SentryPartInstanceEntityManager {
public SentryPartInstanceEntityManagerImpl(CmmnEngineConfiguration cmmnEngineConfiguration, SentryPartInstanceDataManager sentryPartInstanceDataManager) {
super(cmmnEngineConfiguration, sentryPartInstanceDataManager);
}
@Override
public List<SentryPartInstanceEntity> findSentryPartInstancesByCaseInstanceId(String caseInstanceId) {
return dataManager.findSentryPartInstancesByCaseInstanceId(caseInstanceId);
}
@Override
public List<SentryPartInstanceEntity> findSentryPartInstancesByCaseInstanceIdAndNullPlanItemInstanceId(String caseInstanceId) {
return dataManager.findSentryPartInstancesByCaseInstanceIdAndNullPlanItemInstanceId(caseInstanceId);
}
@Override
public List<SentryPartInstanceEntity> findSentryPartInstancesByPlanItemInstanceId(String planItemId) {
return dataManager.findSentryPartInstancesByPlanItemInstanceId(planItemId);
}
@Override | public void updateSentryPartInstancesCaseDefinitionId(String caseInstanceId, String caseDefinitionId) {
List<SentryPartInstanceEntity> sentryPartInstances = findSentryPartInstancesByCaseInstanceId(caseInstanceId);
if (sentryPartInstances != null && !sentryPartInstances.isEmpty()) {
for (SentryPartInstanceEntity sentryPartInstanceEntity : sentryPartInstances) {
sentryPartInstanceEntity.setCaseDefinitionId(caseDefinitionId);
update(sentryPartInstanceEntity);
}
}
}
@Override
public void deleteByCaseInstanceId(String caseInstanceId) {
dataManager.deleteByCaseInstanceId(caseInstanceId);
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\SentryPartInstanceEntityManagerImpl.java | 1 |
请完成以下Java代码 | private void registerProcessToImportTableNames(@NonNull final ImportTableRelatedProcess registration)
{
if (registration.getProcessId() == null)
{
return;
}
for (final String importTableName : ImmutableSet.copyOf(this.importTableNames))
{
if (registration.hasTableName(importTableName))
{
continue;
}
registerRelatedProcessNoFail(importTableName, registration.getProcessId());
registration.addTableName(importTableName);
}
}
private void registerRelatedProcessNoFail(
@NonNull final String importTableName,
@NonNull final AdProcessId processId)
{
try
{
final IADTableDAO tablesRepo = Services.get(IADTableDAO.class);
final AdTableId importTableId = AdTableId.ofRepoId(tablesRepo.retrieveTableId(importTableName));
adProcessesRepo.registerTableProcess(RelatedProcessDescriptor.builder()
.processId(processId)
.tableId(importTableId)
.displayPlace(DisplayPlace.ViewActionsMenu)
.build());
}
catch (final Exception ex)
{
logger.warn("Cannot register process {} to {}. Skip", processId, importTableName, ex);
}
}
@ToString
private static class ImportTableRelatedProcess
{ | @Getter
private final String name;
@Getter
private AdProcessId processId;
private final HashSet<String> registeredOnTableNames = new HashSet<>();
public ImportTableRelatedProcess(@NonNull final String name)
{
this.name = name;
}
public void setProcessId(@NonNull final AdProcessId processId)
{
if (this.processId != null && !Objects.equals(this.processId, processId))
{
throw new AdempiereException("Changing process from " + this.processId + " to " + processId + " is not allowed.");
}
this.processId = processId;
}
public boolean hasTableName(@NonNull final String tableName)
{
return registeredOnTableNames.contains(tableName);
}
public void addTableName(@NonNull final String tableName)
{
registeredOnTableNames.add(tableName);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\processing\impl\ImportTablesRelatedProcessesRegistry.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static List toList() {
FundInfoTypeEnum[] ary = FundInfoTypeEnum.values();
List list = new ArrayList();
for (int i = 0; i < ary.length; i++) {
Map<String, String> map = new HashMap<String, String>();
map.put("desc", ary[i].getDesc());
map.put("name", ary[i].name());
list.add(map);
}
return list;
}
public static FundInfoTypeEnum getEnum(String name) {
FundInfoTypeEnum[] arry = FundInfoTypeEnum.values();
for (int i = 0; i < arry.length; i++) {
if (arry[i].name().equalsIgnoreCase(name)) {
return arry[i];
}
}
return null;
} | /**
* 取枚举的json字符串
*
* @return
*/
public static String getJsonStr() {
FundInfoTypeEnum[] enums = FundInfoTypeEnum.values();
StringBuffer jsonStr = new StringBuffer("[");
for (FundInfoTypeEnum senum : enums) {
if (!"[".equals(jsonStr.toString())) {
jsonStr.append(",");
}
jsonStr.append("{id:'").append(senum).append("',desc:'").append(senum.getDesc()).append("'}");
}
jsonStr.append("]");
return jsonStr.toString();
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\enums\FundInfoTypeEnum.java | 2 |
请完成以下Java代码 | public Jackson2JavaTypeMapper getTypeMapper() {
return this.typeMapper;
}
/**
* Set a customized type mapper.
* @param typeMapper the type mapper.
*/
public void setTypeMapper(Jackson2JavaTypeMapper typeMapper) {
Assert.notNull(typeMapper, "'typeMapper' cannot be null");
this.typeMapper = typeMapper;
}
/**
* Return the object mapper.
* @return the mapper.
*/
protected ObjectMapper getObjectMapper() {
return this.objectMapper;
}
@Override
protected Headers initialRecordHeaders(Message<?> message) {
RecordHeaders headers = new RecordHeaders();
this.typeMapper.fromClass(message.getPayload().getClass(), headers);
return headers;
}
@Override
protected @Nullable Object convertPayload(Message<?> message) {
throw new UnsupportedOperationException("Select a subclass that creates a ProducerRecord value "
+ "corresponding to the configured Kafka Serializer");
}
@Override
protected Object extractAndConvertValue(ConsumerRecord<?, ?> record, @Nullable Type type) {
Object value = record.value();
if (record.value() == null) {
return KafkaNull.INSTANCE;
}
JavaType javaType = determineJavaType(record, type);
if (value instanceof Bytes) {
value = ((Bytes) value).get();
}
if (value instanceof String) {
try {
return this.objectMapper.readValue((String) value, javaType);
}
catch (IOException e) {
throw new ConversionException("Failed to convert from JSON", record, e);
}
}
else if (value instanceof byte[]) {
try {
return this.objectMapper.readValue((byte[]) value, javaType);
}
catch (IOException e) { | throw new ConversionException("Failed to convert from JSON", record, e);
}
}
else {
throw new IllegalStateException("Only String, Bytes, or byte[] supported");
}
}
private JavaType determineJavaType(ConsumerRecord<?, ?> record, @Nullable Type type) {
JavaType javaType = this.typeMapper.getTypePrecedence()
.equals(org.springframework.kafka.support.mapping.Jackson2JavaTypeMapper.TypePrecedence.INFERRED) && type != null
? TypeFactory.defaultInstance().constructType(type)
: this.typeMapper.toJavaType(record.headers());
if (javaType == null) { // no headers
if (type != null) {
javaType = TypeFactory.defaultInstance().constructType(type);
}
else {
javaType = OBJECT;
}
}
return javaType;
}
} | repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\converter\JsonMessageConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public byte[] getVariableData(@ApiParam(name = "executionId") @PathVariable("executionId") String executionId, @ApiParam(name = "variableName") @PathVariable("variableName") String variableName,
@RequestParam(value = "scope", required = false) String scope,
HttpServletResponse response) {
try {
byte[] result = null;
Execution execution = getExecutionFromRequestWithoutAccessCheck(executionId);
RestVariable variable = getVariableFromRequest(execution, variableName, scope, true);
if (RestResponseFactory.BYTE_ARRAY_VARIABLE_TYPE.equals(variable.getType())) {
result = (byte[]) variable.getValue();
response.setContentType("application/octet-stream");
} else if (RestResponseFactory.SERIALIZABLE_VARIABLE_TYPE.equals(variable.getType())) {
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
ObjectOutputStream outputStream = new ObjectOutputStream(buffer); | outputStream.writeObject(variable.getValue());
outputStream.close();
result = buffer.toByteArray();
response.setContentType("application/x-java-serialized-object");
} else {
throw new FlowableObjectNotFoundException("The variable does not have a binary data stream.", null);
}
return result;
} catch (IOException ioe) {
throw new FlowableException("Error getting variable " + variableName, ioe);
}
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\runtime\process\ExecutionVariableDataResource.java | 2 |
请在Spring Boot框架中完成以下Java代码 | void configure(HttpSecurity httpSecurity) {
OAuth2AuthorizationServerMetadataEndpointFilter authorizationServerMetadataEndpointFilter = new OAuth2AuthorizationServerMetadataEndpointFilter();
Consumer<OAuth2AuthorizationServerMetadata.Builder> authorizationServerMetadataCustomizer = getAuthorizationServerMetadataCustomizer();
if (authorizationServerMetadataCustomizer != null) {
authorizationServerMetadataEndpointFilter
.setAuthorizationServerMetadataCustomizer(authorizationServerMetadataCustomizer);
}
httpSecurity.addFilterBefore(postProcess(authorizationServerMetadataEndpointFilter),
AbstractPreAuthenticatedProcessingFilter.class);
}
private Consumer<OAuth2AuthorizationServerMetadata.Builder> getAuthorizationServerMetadataCustomizer() {
Consumer<OAuth2AuthorizationServerMetadata.Builder> authorizationServerMetadataCustomizer = null;
if (this.defaultAuthorizationServerMetadataCustomizer != null
|| this.authorizationServerMetadataCustomizer != null) {
if (this.defaultAuthorizationServerMetadataCustomizer != null) {
authorizationServerMetadataCustomizer = this.defaultAuthorizationServerMetadataCustomizer;
} | if (this.authorizationServerMetadataCustomizer != null) {
authorizationServerMetadataCustomizer = (authorizationServerMetadataCustomizer != null)
? authorizationServerMetadataCustomizer.andThen(this.authorizationServerMetadataCustomizer)
: this.authorizationServerMetadataCustomizer;
}
}
return authorizationServerMetadataCustomizer;
}
@Override
RequestMatcher getRequestMatcher() {
return this.requestMatcher;
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\oauth2\server\authorization\OAuth2AuthorizationServerMetadataEndpointConfigurer.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public void skipConvertingToJson(@NonNull final String variableName)
{
this.skipConvertingToJsonVariableNames.add(variableName);
}
@Nullable
@Override
public String get_ValueAsString(final String variableName)
{
final Object valueObj = super.get_ValueAsObject(variableName);
if (skipConvertingToJsonVariableNames.contains(variableName))
{
return valueObj != null ? valueObj.toString() : "";
}
else
{
return toJsonString(valueObj);
}
} | private String toJsonString(@Nullable final Object valueObj)
{
if (valueObj == null)
{
return "null";
}
try
{
return jsonObjectMapper.writeValueAsString(valueObj);
}
catch (final JsonProcessingException ex)
{
throw new AdempiereException("Cannot convert `" + valueObj + "` to JSON", ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\ToJsonEvaluatee.java | 2 |
请完成以下Java代码 | public List<Bar> getBars() {
return bars;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
return result;
} | public void setBars(List<Bar> bars) {
this.bars = bars;
}
public void setId(final Long id) {
this.id = id;
}
public void setName(final String name) {
this.name = name;
}
@Override
public String toString() {
final StringBuilder builder = new StringBuilder();
builder.append("Foo [name=")
.append(name)
.append("]");
return builder.toString();
}
} | repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\cache\model\Foo.java | 1 |
请完成以下Java代码 | public GettingStartedSection addAdditionalLink(String href, String description) {
this.additionalLinks.addItem(new Link(href, description));
return this;
}
public BulletedSection<Link> additionalLinks() {
return this.additionalLinks;
}
/**
* Internal representation of a link.
*/
public static class Link {
private final String href;
private final String description;
Link(String href, String description) { | this.href = href;
this.description = description;
}
public String getHref() {
return this.href;
}
public String getDescription() {
return this.description;
}
}
} | repos\initializr-main\initializr-generator-spring\src\main\java\io\spring\initializr\generator\spring\documentation\GettingStartedSection.java | 1 |
请完成以下Java代码 | public T sql(String sqlStatement) {
this.sqlStatement = sqlStatement;
return (T) this;
}
@Override
@SuppressWarnings("unchecked")
public T parameter(String name, Object value) {
parameters.put(name, value);
return (T) this;
}
@Override
@SuppressWarnings("unchecked")
public U singleResult() {
this.resultType = ResultType.SINGLE_RESULT;
if (commandExecutor != null) {
return (U) commandExecutor.execute(this);
}
return executeSingleResult(Context.getCommandContext());
}
@Override
@SuppressWarnings("unchecked")
public List<U> list() {
this.resultType = ResultType.LIST;
if (commandExecutor != null) {
return (List<U>) commandExecutor.execute(this);
}
return executeList(Context.getCommandContext(), generateParameterMap());
}
@Override
@SuppressWarnings("unchecked")
public List<U> listPage(int firstResult, int maxResults) {
this.firstResult = firstResult;
this.maxResults = maxResults;
this.resultType = ResultType.LIST_PAGE;
if (commandExecutor != null) {
return (List<U>) commandExecutor.execute(this);
}
return executeList(Context.getCommandContext(), generateParameterMap());
} | @Override
public long count() {
this.resultType = ResultType.COUNT;
if (commandExecutor != null) {
return (Long) commandExecutor.execute(this);
}
return executeCount(Context.getCommandContext(), generateParameterMap());
}
@Override
public Object execute(CommandContext commandContext) {
if (resultType == ResultType.LIST) {
return executeList(commandContext, generateParameterMap());
} else if (resultType == ResultType.LIST_PAGE) {
return executeList(commandContext, generateParameterMap());
} else if (resultType == ResultType.SINGLE_RESULT) {
return executeSingleResult(commandContext);
} else {
return executeCount(commandContext, generateParameterMap());
}
}
public abstract long executeCount(CommandContext commandContext, Map<String, Object> parameterMap);
/**
* Executes the actual query to retrieve the list of results.
*
* @param commandContext
* @param parameterMap
*/
public abstract List<U> executeList(CommandContext commandContext, Map<String, Object> parameterMap);
public U executeSingleResult(CommandContext commandContext) {
List<U> results = executeList(commandContext, generateParameterMap());
if (results.size() == 1) {
return results.get(0);
} else if (results.size() > 1) {
throw new FlowableException("Query return " + results.size() + " results instead of max 1");
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\query\AbstractNativeQuery.java | 1 |
请完成以下Java代码 | public String getAttributeValueType()
{
return X_M_Attribute.ATTRIBUTEVALUETYPE_Number;
}
@Override
public boolean canGenerateValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return true;
}
@Override
public BigDecimal generateNumericValue(final Properties ctx, final IAttributeSet attributeSet, final I_M_Attribute attribute)
{
return BigDecimal.ZERO;
}
@Override
protected boolean isExecuteCallout(final IAttributeValueContext attributeValueContext,
final IAttributeSet attributeSet,
final I_M_Attribute attribute,
final Object valueOld,
final Object valueNew)
{
final IWeightable weightable = getWeightableOrNull(attributeSet);
if (weightable == null)
{
return false;
}
final AttributeCode attributeCode = AttributeCode.ofString(attribute.getValue());
if (!weightable.isWeightGrossAttribute(attributeCode))
{
return false;
}
if (!weightable.hasWeightGross())
{
return false;
} | if (!weightable.hasWeightTare())
{
return false;
}
if (!(attributeValueContext instanceof IHUAttributePropagationContext))
{
return false;
}
final IHUAttributePropagationContext huAttributePropagationContext = (IHUAttributePropagationContext)attributeValueContext;
final AttributeCode attr_WeightNet = weightable.getWeightNetAttribute();
if (huAttributePropagationContext.isExternalInput()
&& huAttributePropagationContext.isValueUpdatedBefore(attr_WeightNet))
{
//
// Net weight was set externally. Do not modify it.
return false;
}
return true;
}
@Override
public boolean isDisplayedUI(@NonNull final IAttributeSet attributeSet, @NonNull final I_M_Attribute attribute)
{
return isLUorTUorTopLevelVHU(attributeSet);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\adempiere\mm\attributes\spi\impl\WeightGrossAttributeValueCallout.java | 1 |
请完成以下Java代码 | public int hashCode()
{
return Objects.hashCode(value);
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof DocActionItem)
{
final DocActionItem other = (DocActionItem)obj;
return Objects.equal(value, other.value);
}
else | {
return false;
}
}
@Override
public String getValue()
{
return value;
}
@Override
public String getDescription()
{
return description;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\document\engine\impl\AbstractDocumentBL.java | 1 |
请完成以下Java代码 | public void setDefaultTimerJobAcquireWaitTimeInMillis(int defaultTimerJobAcquireWaitTimeInMillis) {
this.defaultTimerJobAcquireWaitTimeInMillis = defaultTimerJobAcquireWaitTimeInMillis;
}
public int getDefaultAsyncJobAcquireWaitTimeInMillis() {
return defaultAsyncJobAcquireWaitTimeInMillis;
}
public void setDefaultAsyncJobAcquireWaitTimeInMillis(int defaultAsyncJobAcquireWaitTimeInMillis) {
this.defaultAsyncJobAcquireWaitTimeInMillis = defaultAsyncJobAcquireWaitTimeInMillis;
}
public void setTimerJobRunnable(AcquireTimerJobsRunnable timerJobRunnable) {
this.timerJobRunnable = timerJobRunnable;
}
public int getDefaultQueueSizeFullWaitTimeInMillis() {
return defaultQueueSizeFullWaitTime;
}
public void setDefaultQueueSizeFullWaitTimeInMillis(int defaultQueueSizeFullWaitTime) {
this.defaultQueueSizeFullWaitTime = defaultQueueSizeFullWaitTime;
}
public void setAsyncJobsDueRunnable(AcquireAsyncJobsDueRunnable asyncJobsDueRunnable) {
this.asyncJobsDueRunnable = asyncJobsDueRunnable;
}
public void setResetExpiredJobsRunnable(ResetExpiredJobsRunnable resetExpiredJobsRunnable) {
this.resetExpiredJobsRunnable = resetExpiredJobsRunnable;
}
public int getRetryWaitTimeInMillis() {
return retryWaitTimeInMillis; | }
public void setRetryWaitTimeInMillis(int retryWaitTimeInMillis) {
this.retryWaitTimeInMillis = retryWaitTimeInMillis;
}
public int getResetExpiredJobsInterval() {
return resetExpiredJobsInterval;
}
public void setResetExpiredJobsInterval(int resetExpiredJobsInterval) {
this.resetExpiredJobsInterval = resetExpiredJobsInterval;
}
public int getResetExpiredJobsPageSize() {
return resetExpiredJobsPageSize;
}
public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) {
this.resetExpiredJobsPageSize = resetExpiredJobsPageSize;
}
public ExecuteAsyncRunnableFactory getExecuteAsyncRunnableFactory() {
return executeAsyncRunnableFactory;
}
public void setExecuteAsyncRunnableFactory(ExecuteAsyncRunnableFactory executeAsyncRunnableFactory) {
this.executeAsyncRunnableFactory = executeAsyncRunnableFactory;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\DefaultAsyncJobExecutor.java | 1 |
请完成以下Java代码 | public List<Integer> runBinarySearchOnSortedArraysWithDuplicates(int[] sortedArray, Integer key) {
int startIndex = startIndexSearch(sortedArray, key);
int endIndex = endIndexSearch(sortedArray, key);
return IntStream.rangeClosed(startIndex, endIndex)
.boxed()
.collect(Collectors.toList());
}
private int endIndexSearch(int[] sortedArray, int target) {
int left = 0;
int right = sortedArray.length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (sortedArray[mid] == target) {
result = mid;
left = mid + 1;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
private int startIndexSearch(int[] sortedArray, int target) {
int left = 0; | int right = sortedArray.length - 1;
int result = -1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (sortedArray[mid] == target) {
result = mid;
right = mid - 1;
} else if (sortedArray[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return result;
}
} | repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\binarysearch\BinarySearch.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setUrl(String url) {
this.url = url;
}
public List<RestVariable> getVariables() {
return variables;
}
public void setVariables(List<RestVariable> variables) {
this.variables = variables;
}
public void addVariable(RestVariable variable) {
variables.add(variable);
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
public String getTenantId() {
return tenantId;
}
public void setCategory(String category) {
this.category = category;
}
public String getCategory() {
return category;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public void setCaseInstanceId(String caseInstanceId) {
this.caseInstanceId = caseInstanceId;
}
public String getCaseInstanceUrl() {
return caseInstanceUrl;
}
public void setCaseInstanceUrl(String caseInstanceUrl) {
this.caseInstanceUrl = caseInstanceUrl;
}
public String getCaseDefinitionId() {
return caseDefinitionId;
}
public void setCaseDefinitionId(String caseDefinitionId) {
this.caseDefinitionId = caseDefinitionId;
}
public String getCaseDefinitionUrl() {
return caseDefinitionUrl;
}
public void setCaseDefinitionUrl(String caseDefinitionUrl) {
this.caseDefinitionUrl = caseDefinitionUrl;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
}
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
} | public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getPropagatedStageInstanceId() {
return propagatedStageInstanceId;
}
public void setPropagatedStageInstanceId(String propagatedStageInstanceId) {
this.propagatedStageInstanceId = propagatedStageInstanceId;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\task\HistoricTaskInstanceResponse.java | 2 |
请完成以下Java代码 | public int getM_DiscountSchema_ID()
{
return get_ValueAsInt(COLUMNNAME_M_DiscountSchema_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setProcessing (final boolean Processing)
{
set_Value (COLUMNNAME_Processing, Processing);
}
@Override
public boolean isProcessing()
{
return get_ValueAsBoolean(COLUMNNAME_Processing); | }
@Override
public void setScript (final @Nullable java.lang.String Script)
{
set_Value (COLUMNNAME_Script, Script);
}
@Override
public java.lang.String getScript()
{
return get_ValueAsString(COLUMNNAME_Script);
}
@Override
public void setValidFrom (final java.sql.Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
@Override
public java.sql.Timestamp getValidFrom()
{
return get_ValueAsTimestamp(COLUMNNAME_ValidFrom);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_DiscountSchema.java | 1 |
请完成以下Java代码 | public static InvoiceAndLineId ofRepoIdOrNull(
@Nullable final Integer invoiceId,
@Nullable final Integer invoiceLineId)
{
return invoiceId != null && invoiceId > 0 && invoiceLineId != null && invoiceLineId > 0
? ofRepoId(invoiceId, invoiceLineId)
: null;
}
@Nullable
public static InvoiceAndLineId ofRepoIdOrNull(
@Nullable final InvoiceId bpartnerId,
final int bpartnerLocationId)
{
return bpartnerId != null && bpartnerLocationId > 0 ? ofRepoId(bpartnerId, bpartnerLocationId) : null;
}
private InvoiceAndLineId(@NonNull final InvoiceId invoiceId, final int invoiceLineId)
{
this.repoId = Check.assumeGreaterThanZero(invoiceLineId, "invoiceLineId");
this.invoiceId = invoiceId;
}
public static int toRepoId(@Nullable final InvoiceAndLineId invoiceAndLineId)
{
return toRepoIdOr(invoiceAndLineId, -1);
} | public static int toRepoIdOr(@Nullable final InvoiceAndLineId invoiceAndLineId, final int defaultValue)
{
return invoiceAndLineId != null ? invoiceAndLineId.getRepoId() : defaultValue;
}
public static boolean equals(final InvoiceAndLineId id1, final InvoiceAndLineId id2)
{
return Objects.equals(id1, id2);
}
public void assertInvoiceId(@NonNull final InvoiceId expectedInvoiceId)
{
if (!InvoiceId.equals(this.invoiceId, expectedInvoiceId))
{
throw new AdempiereException("InvoiceId does not match for " + this + ". Expected invoiceId was " + expectedInvoiceId);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\invoice\InvoiceAndLineId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Logging getLogging() {
return this.logging;
}
/**
* A health endpoint group.
*/
public static class Group extends HealthProperties {
public static final String SERVER_PREFIX = "server:";
public static final String MANAGEMENT_PREFIX = "management:";
/**
* Health indicator IDs that should be included or '*' for all.
*/
private @Nullable Set<String> include;
/**
* Health indicator IDs that should be excluded or '*' for all.
*/
private @Nullable Set<String> exclude;
/**
* When to show full health details. Defaults to the value of
* 'management.endpoint.health.show-details'.
*/
private @Nullable Show showDetails;
/**
* Additional path that this group can be made available on. The additional path
* must start with a valid prefix, either `server` or `management` to indicate if
* it will be available on the main port or the management port. For instance,
* `server:/healthz` will configure the group on the main port at `/healthz`.
*/
private @Nullable String additionalPath;
public @Nullable Set<String> getInclude() {
return this.include;
}
public void setInclude(@Nullable Set<String> include) {
this.include = include;
}
public @Nullable Set<String> getExclude() { | return this.exclude;
}
public void setExclude(@Nullable Set<String> exclude) {
this.exclude = exclude;
}
@Override
public @Nullable Show getShowDetails() {
return this.showDetails;
}
public void setShowDetails(@Nullable Show showDetails) {
this.showDetails = showDetails;
}
public @Nullable String getAdditionalPath() {
return this.additionalPath;
}
public void setAdditionalPath(@Nullable String additionalPath) {
this.additionalPath = additionalPath;
}
}
/**
* Health logging properties.
*/
public static class Logging {
/**
* Threshold after which a warning will be logged for slow health indicators.
*/
private Duration slowIndicatorThreshold = Duration.ofSeconds(10);
public Duration getSlowIndicatorThreshold() {
return this.slowIndicatorThreshold;
}
public void setSlowIndicatorThreshold(Duration slowIndicatorThreshold) {
this.slowIndicatorThreshold = slowIndicatorThreshold;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-health\src\main\java\org\springframework\boot\health\autoconfigure\actuate\endpoint\HealthEndpointProperties.java | 2 |
请完成以下Java代码 | public class SetRemovalTimeToHistoricDecisionInstancesDto extends AbstractSetRemovalTimeDto {
protected String[] historicDecisionInstanceIds;
protected HistoricDecisionInstanceQueryDto historicDecisionInstanceQuery;
protected boolean hierarchical;
public String[] getHistoricDecisionInstanceIds() {
return historicDecisionInstanceIds;
}
public void setHistoricDecisionInstanceIds(String[] historicDecisionInstanceIds) {
this.historicDecisionInstanceIds = historicDecisionInstanceIds;
}
public HistoricDecisionInstanceQueryDto getHistoricDecisionInstanceQuery() { | return historicDecisionInstanceQuery;
}
public void setHistoricDecisionInstanceQuery(HistoricDecisionInstanceQueryDto historicDecisionInstanceQuery) {
this.historicDecisionInstanceQuery = historicDecisionInstanceQuery;
}
public boolean isHierarchical() {
return hierarchical;
}
public void setHierarchical(boolean hierarchical) {
this.hierarchical = hierarchical;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\removaltime\SetRemovalTimeToHistoricDecisionInstancesDto.java | 1 |
请完成以下Java代码 | public JAXBElement<de.metas.shipper.gateway.go.schema.Sendung> createGOWebServiceSendungsErstellung(de.metas.shipper.gateway.go.schema.Sendung value) {
return new JAXBElement<de.metas.shipper.gateway.go.schema.Sendung>(_GOWebServiceSendungsErstellung_QNAME, de.metas.shipper.gateway.go.schema.Sendung.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link SendungsRueckmeldung }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link SendungsRueckmeldung }{@code >}
*/
@XmlElementDecl(namespace = "https://wsdemo.ax4.com/ws/GeneralOvernight", name = "GOWebService_SendungsRueckmeldung")
public JAXBElement<SendungsRueckmeldung> createGOWebServiceSendungsRueckmeldung(SendungsRueckmeldung value) {
return new JAXBElement<SendungsRueckmeldung>(_GOWebServiceSendungsRueckmeldung_QNAME, SendungsRueckmeldung.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Fehlerbehandlung }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link Fehlerbehandlung }{@code >}
*/
@XmlElementDecl(namespace = "https://wsdemo.ax4.com/ws/GeneralOvernight", name = "GOWebService_Fehlerbehandlung")
public JAXBElement<Fehlerbehandlung> createGOWebServiceFehlerbehandlung(Fehlerbehandlung value) {
return new JAXBElement<Fehlerbehandlung>(_GOWebServiceFehlerbehandlung_QNAME, Fehlerbehandlung.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Sendungsnummern }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return | * the new instance of {@link JAXBElement }{@code <}{@link Sendungsnummern }{@code >}
*/
@XmlElementDecl(namespace = "https://wsdemo.ax4.com/ws/GeneralOvernight", name = "GOWebService_Sendungsnummern")
public JAXBElement<Sendungsnummern> createGOWebServiceSendungsnummern(Sendungsnummern value) {
return new JAXBElement<Sendungsnummern>(_GOWebServiceSendungsnummern_QNAME, Sendungsnummern.class, null, value);
}
/**
* Create an instance of {@link JAXBElement }{@code <}{@link Label }{@code >}
*
* @param value
* Java instance representing xml element's value.
* @return
* the new instance of {@link JAXBElement }{@code <}{@link Label }{@code >}
*/
@XmlElementDecl(namespace = "https://wsdemo.ax4.com/ws/GeneralOvernight", name = "GOWebService_Label")
public JAXBElement<Label> createGOWebServiceLabel(Label value) {
return new JAXBElement<Label>(_GOWebServiceLabel_QNAME, Label.class, null, value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.go\src\main\java-xjc\de\metas\shipper\gateway\go\schema\ObjectFactory.java | 1 |
请完成以下Java代码 | public void enqueueDistributedEvent(final Event event, final Topic topic)
{
final String topicName = topic.getName();
final String amqpExchangeName = rabbitMQDestinationResolver.getAMQPExchangeNameByTopicName(topicName);
final String routingKey = amqpExchangeName; // this corresponds to the way we bound our queues to the exchanges in IEventBusQueueConfiguration implementations
amqpTemplate.convertAndSend(
amqpExchangeName,
routingKey,
event,
getMessagePostProcessor(topic));
logger.debug("Send event; topicName={}; event={}; type={}; timestamp={}, ThreadId={}", topicName, event, topic.getType(), SystemTime.asTimestamp(), Thread.currentThread().getId());
}
@Override
public void enqueueLocalEvent(final Event event, final Topic topic)
{
final String queueName = rabbitMQDestinationResolver.getAMQPQueueNameByTopicName(topic.getName());
amqpTemplate.convertAndSend(queueName,
event,
getMessagePostProcessor(topic)); | logger.debug("Send event; topicName={}; event={}; type={}", topic.getName(), event, topic.getType());
}
@NonNull
private MessagePostProcessor getMessagePostProcessor(@NonNull final Topic topic)
{
return message -> {
final Map<String, Object> headers = message.getMessageProperties().getHeaders();
headers.put(HEADER_SenderId, getSenderId());
headers.put(HEADER_TopicName, topic.getName());
headers.put(HEADER_TopicType, topic.getType());
return message;
};
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\event\impl\RabbitMQEnqueuer.java | 1 |
请完成以下Java代码 | protected final void grantAccessToSelectedRows()
{
final Principal principal = getPrincipal();
final Set<Access> permissionsToGrant = getPermissionsToGrant();
final UserId requestedBy = getUserId();
final IView view = getView();
getSelectedRowIds()
.stream()
.map(view::getTableRecordReferenceOrNull)
.forEach(recordRef -> userGroupRecordAccessService.grantAccess(RecordAccessGrantRequest.builder()
.recordRef(recordRef)
.principal(principal)
.permissions(permissionsToGrant)
.issuer(PermissionIssuer.MANUAL)
.requestedBy(requestedBy)
.build()));
}
protected final void revokeAccessFromSelectedRows()
{
final Principal principal = getPrincipal();
final UserId requestedBy = getUserId();
final boolean revokeAllPermissions;
final List<Access> permissionsToRevoke;
final Access permission = getPermissionOrNull();
if (permission == null)
{
revokeAllPermissions = true;
permissionsToRevoke = ImmutableList.of();
}
else
{
revokeAllPermissions = false;
permissionsToRevoke = ImmutableList.of(permission);
}
final IView view = getView();
getSelectedRowIds()
.stream()
.map(view::getTableRecordReferenceOrNull)
.forEach(recordRef -> userGroupRecordAccessService.revokeAccess(RecordAccessRevokeRequest.builder()
.recordRef(recordRef)
.principal(principal)
.revokeAllPermissions(revokeAllPermissions)
.permissions(permissionsToRevoke)
.issuer(PermissionIssuer.MANUAL)
.requestedBy(requestedBy)
.build()));
}
private Principal getPrincipal()
{
final PrincipalType principalType = PrincipalType.ofCode(principalTypeCode); | if (PrincipalType.USER.equals(principalType))
{
return Principal.userId(userId);
}
else if (PrincipalType.USER_GROUP.equals(principalType))
{
return Principal.userGroupId(userGroupId);
}
else
{
throw new AdempiereException("@Unknown@ @PrincipalType@: " + principalType);
}
}
private Set<Access> getPermissionsToGrant()
{
final Access permission = getPermissionOrNull();
if (permission == null)
{
throw new FillMandatoryException(PARAM_PermissionCode);
}
if (Access.WRITE.equals(permission))
{
return ImmutableSet.of(Access.READ, Access.WRITE);
}
else
{
return ImmutableSet.of(permission);
}
}
private Access getPermissionOrNull()
{
if (Check.isEmpty(permissionCode, true))
{
return null;
}
else
{
return Access.ofCode(permissionCode);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\security\process\WEBUI_UserGroupRecordAccess_Base.java | 1 |
请完成以下Java代码 | public int getPA_ReportCube_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportCube_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Financial Report.
@param PA_Report_ID
Financial Report
*/
public void setPA_Report_ID (int PA_Report_ID)
{
if (PA_Report_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_Report_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_Report_ID, Integer.valueOf(PA_Report_ID));
}
/** Get Financial Report.
@return Financial Report
*/
public int getPA_Report_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_Report_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_PA_ReportLineSet getPA_ReportLineSet() throws RuntimeException
{
return (I_PA_ReportLineSet)MTable.get(getCtx(), I_PA_ReportLineSet.Table_Name)
.getPO(getPA_ReportLineSet_ID(), get_TrxName()); }
/** Set Report Line Set.
@param PA_ReportLineSet_ID Report Line Set */ | public void setPA_ReportLineSet_ID (int PA_ReportLineSet_ID)
{
if (PA_ReportLineSet_ID < 1)
set_Value (COLUMNNAME_PA_ReportLineSet_ID, null);
else
set_Value (COLUMNNAME_PA_ReportLineSet_ID, Integer.valueOf(PA_ReportLineSet_ID));
}
/** Get Report Line Set.
@return Report Line Set */
public int getPA_ReportLineSet_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLineSet_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** 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;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Report.java | 1 |
请在Spring Boot框架中完成以下Java代码 | static final class LiquibaseDataSourceCondition extends AnyNestedCondition {
LiquibaseDataSourceCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@ConditionalOnBean(DataSource.class)
private static final class DataSourceBeanCondition {
}
@ConditionalOnBean(JdbcConnectionDetails.class)
private static final class JdbcConnectionDetailsCondition {
}
@ConditionalOnProperty("spring.liquibase.url")
private static final class LiquibaseUrlCondition {
}
}
static class LiquibaseAutoConfigurationRuntimeHints implements RuntimeHintsRegistrar {
@Override
public void registerHints(RuntimeHints hints, @Nullable ClassLoader classLoader) {
hints.resources().registerPattern("db/changelog/**");
}
}
/**
* Adapts {@link LiquibaseProperties} to {@link LiquibaseConnectionDetails}.
*/
static final class PropertiesLiquibaseConnectionDetails implements LiquibaseConnectionDetails {
private final LiquibaseProperties properties;
PropertiesLiquibaseConnectionDetails(LiquibaseProperties properties) {
this.properties = properties; | }
@Override
public @Nullable String getUsername() {
return this.properties.getUser();
}
@Override
public @Nullable String getPassword() {
return this.properties.getPassword();
}
@Override
public @Nullable String getJdbcUrl() {
return this.properties.getUrl();
}
@Override
public @Nullable String getDriverClassName() {
String driverClassName = this.properties.getDriverClassName();
return (driverClassName != null) ? driverClassName : LiquibaseConnectionDetails.super.getDriverClassName();
}
}
@FunctionalInterface
interface SpringLiquibaseCustomizer {
/**
* Customize the given {@link SpringLiquibase} instance.
* @param springLiquibase the instance to configure
*/
void customize(SpringLiquibase springLiquibase);
}
} | repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseAutoConfiguration.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class SpringSecurity extends WebSecurityConfigurerAdapter {
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth
.inMemoryAuthentication()
.withUser("admin")
.password(passwordEncoder().encode("admin123"))
.roles("ADMIN").authorities("ACCESS_TEST1", "ACCESS_TEST2")
.and()
.withUser("hamdamboy")
.password(passwordEncoder().encode("hamdamboy123"))
.roles("USER")
.and()
.withUser("manager")
.password(passwordEncoder().encode("manager"))
.roles("MANAGER")
.authorities("ACCESS_TEST1");
}
/**
* Enable HTTPS/SSL in Spring Boot
* **/
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
// .anyRequest().permitAll() if you fix all permission values, then remove all conditions.
.antMatchers("/index.html").permitAll() | .antMatchers("/profile/**").authenticated()
.antMatchers("/admin/**").hasRole("ADMIN")
.antMatchers("/management/**").hasAnyRole("ADMIN", "MANAGER")
.antMatchers("/api/public/test1").hasAuthority("ACCESS_TEST1")
.antMatchers("/api/public/test2").hasAuthority("ACCESS_TEST2")
.and()
.httpBasic();
}
@Bean
PasswordEncoder passwordEncoder(){
return new BCryptPasswordEncoder();
}
} | repos\SpringBoot-Projects-FullStack-master\Part-6 Spring Boot Security\5. SpringHttpsSecurity\src\main\java\spring\security\security\SpringSecurity.java | 2 |
请完成以下Java代码 | public T getEntry() {
return entry;
}
public HttpResult<T> setEntry(T entry) {
this.entry = entry;
return this;
}
public static <T> HttpResult<T> failure() {
return HttpResult.failure(RESPONSE_FAILURE, "");
}
public static <T> HttpResult<T> failure(String msg) {
return HttpResult.failure(RESPONSE_FAILURE, msg);
}
public static <T> HttpResult<T> failure(int code, String msg) {
HttpResult result = new HttpResult<T>();
result.setStatus(false);
result.setMessage(msg);
result.setCode(code);
return result;
}
public static <T> HttpResult<T> success(T obj) {
SuccessResult result = new SuccessResult<T>();
result.setStatus(true);
result.setEntry(obj);
result.setCode(200);
return result;
}
public static <T> HttpResult<T> success(T obj, int code) {
SuccessResult<T> result = new SuccessResult<T>();
result.setStatus(true);
result.setCode(200);
result.setEntry(obj);
return result;
}
public static <T> HttpResult<List<T>> success(List<T> list) {
SuccessResult<List<T>> result = new SuccessResult<List<T>>();
result.setStatus(true);
result.setCode(200);
if (null == list) {
result.setEntry(new ArrayList<T>(0));
} else {
result.setEntry(list);
}
return result;
}
public static HttpResult<Boolean> success() {
SuccessResult<Boolean> result = new SuccessResult<Boolean>();
result.setStatus(true);
result.setEntry(true);
result.setCode(200);
return result;
}
public static <T> HttpResult<T> success(T entry, String message) {
SuccessResult<T> result = new SuccessResult<T>();
result.setStatus(true);
result.setEntry(entry);
result.setMessage(message);
result.setCode(200);
return result;
}
/**
* Result set data with paging information
*/
public static class PageSuccessResult<T> extends HttpResult<T> {
@Override
public String getMessage() { | return null != message ? message : HttpResult.MESSAGE_SUCCESS;
}
@Override
public int getCode() {
return HttpResult.RESPONSE_SUCCESS;
}
}
public static class SuccessResult<T> extends HttpResult<T> {
@Override
public String getMessage() {
return null != message ? message : HttpResult.MESSAGE_SUCCESS;
}
@Override
public int getCode() {
return code != 0 ? code : HttpResult.RESPONSE_SUCCESS;
}
}
public static class FailureResult<T> extends HttpResult<T> {
@Override
public String getMessage() {
return null != message ? message : HttpResult.MESSAGE_FAILURE;
}
@Override
public int getCode() {
return code != 0 ? code : HttpResult.RESPONSE_FAILURE;
}
}
} | repos\springboot-demo-master\Aviator\src\main\java\com\et\exception\HttpResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static void createWorkpackage(final I_C_Order order)
{
SCHEDULER.schedule(order);
}
private static final WorkpackagesOnCommitSchedulerTemplate<I_C_Order> SCHEDULER = new WorkpackagesOnCommitSchedulerTemplate<I_C_Order>(R_Request_CreateFromOrder_Async.class)
{
@Override
protected boolean isEligibleForScheduling(final I_C_Order model)
{
return model != null && model.getC_Order_ID() > 0;
}
@Override
protected Properties extractCtxFromItem(final I_C_Order item)
{
return Env.getCtx();
}
@Override
protected String extractTrxNameFromItem(final I_C_Order item)
{
return ITrx.TRXNAME_ThreadInherited;
} | @Override
protected Object extractModelToEnqueueFromItem(final Collector collector, final I_C_Order item)
{
return TableRecordReference.of(I_C_Order.Table_Name, item.getC_Order_ID());
}
};
@Override
public Result processWorkPackage(final I_C_Queue_WorkPackage workPackage, final String localTrxName)
{
// retrieve the order and generate requests
queueDAO.retrieveAllItems(workPackage, I_C_Order.class)
.forEach(requestBL::createRequestFromOrder);
return Result.SUCCESS;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\request\service\async\spi\impl\R_Request_CreateFromOrder_Async.java | 2 |
请完成以下Java代码 | public void setNote (final @Nullable java.lang.String Note)
{
set_Value (COLUMNNAME_Note, Note);
}
@Override
public java.lang.String getNote()
{
return get_ValueAsString(COLUMNNAME_Note);
}
/**
* Status AD_Reference_ID=541324
* Reference name: Invoice Verification Run Status
*/
public static final int STATUS_AD_Reference_ID=541324;
/** Planned = P */ | public static final String STATUS_Planned = "P";
/** Running = R */
public static final String STATUS_Running = "R";
/** Finished = F */
public static final String STATUS_Finished = "F";
@Override
public void setStatus (final java.lang.String Status)
{
set_ValueNoCheck (COLUMNNAME_Status, Status);
}
@Override
public java.lang.String getStatus()
{
return get_ValueAsString(COLUMNNAME_Status);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Verification_Run.java | 1 |
请完成以下Java代码 | protected String doIt() throws Exception
{
Check.assume(p_WhereClause != null, "WhereClause is not null");
final long startTime = System.currentTimeMillis();
final ISweepTableBL sweepTableBL = Services.get(ISweepTableBL.class);
// clean log data
db_delete_logs();
DB.saveConstraints();
final String trxName = get_TrxName();
try
{
DB.getConstraints().setTrxTimeoutSecs(-1, false);
// workaround, the API should do
Services.get(IOpenTrxBL.class).onTimeOutChange(Trx.get(trxName, false));
// final int targetClientId = 100;
final int targetClientId = -1;
final boolean result = sweepTableBL.sweepTable(getCtx(), p_TableName, p_WhereClause, targetClientId, this, trxName);
addLog("Finished after " + TimeUtil.formatElapsed(System.currentTimeMillis() - startTime) + " (Everything deleted: " + result + ")");
//
// Do a second run, just for safety and to check the results
{
addLog("--------------- SECOND RUN ------------------------------------------");
final long startTime2 = System.currentTimeMillis();
final boolean result2 = sweepTableBL.sweepTable(getCtx(), p_TableName, p_WhereClause, targetClientId, this, trxName);
addLog("Finished(2) after " + TimeUtil.formatElapsed(System.currentTimeMillis() - startTime2) + " (Everything deleted: " + result2 + ")");
if (result2 == false)
{
// NOTE: because in de.metas.adempiere.service.impl.SweepTableBL.retrieveRecordIds(RuntimeContext,
// String, String, int)
// we are setting references to NULL, is absolutely mandatory to make sure that everything was
// deleted, because else we will leave the database in a inconsistent and irreversible state
throw new AdempiereException("There is remaining data! ROLLBACK!");
}
}
if (p_IsTest)
{ | throw new AdempiereException("ROLLBACK!");
}
return "Everything could be deleted: " + result;
}
finally
{
DB.restoreConstraints();
// workaround, the API should do this automatically
Services.get(IOpenTrxBL.class).onTimeOutChange(Trx.get(trxName, false));
}
}
private int db_delete_logs()
{
final String sql = "select db_delete_logs(?, ?)";
final int adSessionId = Env.getAD_Session_ID(getCtx());
final int no = DB.getSQLValueEx(get_TrxName(), sql, adSessionId, getPinstanceId());
addLog("Deleted log data: " + no + " records");
return no;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\process\SweepTable.java | 1 |
请完成以下Java代码 | private void extractMbeanNotifications(Object managedBean, Set<ModelMBeanNotificationInfo> mBeanNotifications) {
ManagedNotifications notifications = managedBean.getClass().getAnnotation(ManagedNotifications.class);
if (notifications != null) {
for (ManagedNotification notification : notifications.value()) {
ModelMBeanNotificationInfo info = new ModelMBeanNotificationInfo(notification.notificationTypes(), notification.name(), notification.description());
mBeanNotifications.add(info);
LOGGER.trace("Assembled notification: {}", info);
}
}
}
private String getDescription(Object managedBean, String objectName) {
ManagedResource mr = managedBean.getClass().getAnnotation(ManagedResource.class);
return mr != null ? mr.description() : "";
}
private String getName(Object managedBean, String objectName) {
return managedBean == null ? null : managedBean.getClass().getName();
}
private static final class ManagedAttributeInfo {
private String key;
private String description;
private Method getter;
private Method setter;
private ManagedAttributeInfo(String key, String description) {
this.key = key;
this.description = description;
}
public String getKey() {
return key;
}
public String getDescription() {
return description;
}
public Method getGetter() {
return getter;
}
public void setGetter(Method getter) {
this.getter = getter;
}
public Method getSetter() {
return setter;
}
public void setSetter(Method setter) {
this.setter = setter;
}
@Override
public String toString() {
return "ManagedAttributeInfo: [" + key + " + getter: " + getter + ", setter: " + setter + "]";
}
}
private static final class ManagedOperationInfo {
private final String description; | private final Method operation;
private ManagedOperationInfo(String description, Method operation) {
this.description = description;
this.operation = operation;
}
public String getDescription() {
return description;
}
public Method getOperation() {
return operation;
}
@Override
public String toString() {
return "ManagedOperationInfo: [" + operation + "]";
}
}
private static final class MBeanAttributesAndOperations {
private Map<String, ManagedAttributeInfo> attributes;
private Set<ManagedOperationInfo> operations;
}
} | repos\flowable-engine-main\modules\flowable-jmx\src\main\java\org\flowable\management\jmx\MBeanInfoAssembler.java | 1 |
请完成以下Java代码 | public static void main(final String[] args)
{
new SpringApplicationBuilder(Application.class)
.headless(true)
.web(WebApplicationType.SERVLET)
.run(args);
}
@Bean
public ObjectMapper jsonObjectMapper()
{
final ObjectMapper jsonObjectMapper = new ObjectMapper();
jsonObjectMapper.findAndRegisterModules();
return jsonObjectMapper;
}
@Bean
public MSV3PeerAuthToken authTokenString(@Value("${msv3server.peer.authToken:}") final String authTokenStringValue)
{
if (authTokenStringValue == null || authTokenStringValue.trim().isEmpty())
{
// a token is needed on the receiver side, even if it's not valid
return MSV3PeerAuthToken.TOKEN_NOT_SET;
}
return MSV3PeerAuthToken.of(authTokenStringValue);
} | @Override
public void afterPropertiesSet()
{
try
{
if (requestAllDataOnStartup)
{
msv3ServerPeerService.requestAllUpdates();
}
else if (requestConfigDataOnStartup)
{
msv3ServerPeerService.requestConfigUpdates();
}
}
catch (Exception ex)
{
logger.warn("Error while requesting ALL updates. Skipped.", ex);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.server\src\main\java\de\metas\vertical\pharma\msv3\server\Application.java | 1 |
请完成以下Java代码 | public static int getPtypeButton() {
return PTYPE_BUTTON;
}
public static void setPtypeButton(int ptypeButton) {
PTYPE_BUTTON = ptypeButton;
}
public Long getPid() {
return pid;
}
public void setPid(Long pid) {
this.pid = pid;
}
public String getPname() {
return pname;
}
public void setPname(String pname) {
this.pname = pname;
}
public Integer getPtype() {
return ptype;
}
public void setPtype(Integer ptype) { | this.ptype = ptype;
}
public String getPval() {
return pval;
}
public void setPval(String pval) {
this.pval = pval;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public Date getUpdated() {
return updated;
}
public void setUpdated(Date updated) {
this.updated = updated;
}
} | repos\spring-boot-quick-master\quick-spring-shiro\src\main\java\com\shiro\entity\Perm.java | 1 |
请完成以下Java代码 | public void setIsValueDisplayed (boolean IsValueDisplayed)
{
set_Value (COLUMNNAME_IsValueDisplayed, Boolean.valueOf(IsValueDisplayed));
}
/** Get 'Value' anzeigen.
@return Displays Value column with the Display column
*/
@Override
public boolean isValueDisplayed ()
{
Object oo = get_Value(COLUMNNAME_IsValueDisplayed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Sql ORDER BY.
@param OrderByClause
Fully qualified ORDER BY clause
*/
@Override
public void setOrderByClause (java.lang.String OrderByClause)
{
set_Value (COLUMNNAME_OrderByClause, OrderByClause);
}
/** Get Sql ORDER BY.
@return Fully qualified ORDER BY clause
*/
@Override
public java.lang.String getOrderByClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_OrderByClause);
}
/** Set Inaktive Werte anzeigen.
@param ShowInactiveValues Inaktive Werte anzeigen */
@Override
public void setShowInactiveValues (boolean ShowInactiveValues)
{
set_Value (COLUMNNAME_ShowInactiveValues, Boolean.valueOf(ShowInactiveValues));
}
/** Get Inaktive Werte anzeigen.
@return Inaktive Werte anzeigen */
@Override
public boolean isShowInactiveValues ()
{
Object oo = get_Value(COLUMNNAME_ShowInactiveValues);
if (oo != null)
{ | if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Sql WHERE.
@param WhereClause
Fully qualified SQL WHERE clause
*/
@Override
public void setWhereClause (java.lang.String WhereClause)
{
set_Value (COLUMNNAME_WhereClause, WhereClause);
}
/** Get Sql WHERE.
@return Fully qualified SQL WHERE clause
*/
@Override
public java.lang.String getWhereClause ()
{
return (java.lang.String)get_Value(COLUMNNAME_WhereClause);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Ref_Table.java | 1 |
请完成以下Java代码 | public class CharTablePanel extends JPanel {
JEditorPane editor;
Border border1;
FlowLayout flowLayout1 = new FlowLayout();
String[] chars =
{
"\u00A9",
"\u00AE",
"\u2122",
"\u00AB\u00BB",
"\u201C\u201D",
"\u2018\u2019",
"\u2013",
"\u2014",
"\u2020",
"\u2021",
"\u00A7",
"\u2116",
"\u20AC",
"\u00A2",
"\u00A3",
"\u00A4",
"\u00A5",
"\u00B7",
"\u2022",
"\u25E6",
"\u25AA",
"\u25AB",
"\u25CF",
"\u25CB",
"\u25A0",
"\u25A1",
"\u263A",
"\u00A0" };
Vector buttons = new Vector();
public CharTablePanel(JEditorPane ed) {
try {
editor = ed;
jbInit();
}
catch (Exception e) {
e.printStackTrace();
}
}
private void jbInit() throws Exception {
//this.setSize(200, 50);
this.setFocusable(false);
//this.setBackground();
this.setPreferredSize(new Dimension(200, 45));
this.setToolTipText("");
flowLayout1.setHgap(0);
flowLayout1.setVgap(0); | flowLayout1.setAlignment(FlowLayout.LEFT);
this.setLayout(flowLayout1);
//this.getContentPane().add(cal, BorderLayout.CENTER);
createButtons();
}
void createButtons() {
for (int i = 0; i < chars.length; i++) {
JButton button = new JButton(new CharAction(chars[i]));
button.setMaximumSize(new Dimension(50, 22));
//button.setMinimumSize(new Dimension(22, 22));
button.setPreferredSize(new Dimension(30, 22));
button.setRequestFocusEnabled(false);
button.setFocusable(false);
button.setBorderPainted(false);
button.setOpaque(false);
button.setMargin(new Insets(0,0,0,0));
button.setFont(new Font("serif", 0, 14));
if (i == chars.length-1) {
button.setText("nbsp");
button.setFont(new Font("Dialog",0,10));
button.setMargin(new Insets(0,0,0,0));
}
this.add(button, null);
}
}
class CharAction extends AbstractAction {
CharAction(String name) {
super(name);
//putValue(Action.SHORT_DESCRIPTION, name);
}
public void actionPerformed(ActionEvent e) {
String s = this.getValue(Action.NAME).toString();
editor.replaceSelection(s);
if (s.length() == 2)
editor.setCaretPosition(editor.getCaretPosition()-1);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\CharTablePanel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class MyBatisConfig {
@Autowired
private DataSource dataSource;
@Bean(name = "sqlSessionFactory")
public SqlSessionFactoryBean sqlSessionFactory(
ApplicationContext applicationContext) throws Exception {
SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
sessionFactory.setDataSource(dataSource);
org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setMapUnderscoreToCamelCase(true);
configuration.setJdbcTypeForNull(JdbcType.NULL);
configuration.setLogImpl(org.apache.ibatis.logging.log4j.Log4jImpl.class);//use log4j log | sessionFactory.setConfiguration(configuration);
sessionFactory.setMapperLocations(applicationContext.getResources("classpath:com/yy/example/mapper/*.xml"));
//
// Properties prop = new Properties();
// prop.setProperty("supportMethodsArguments","true");
// prop.setProperty("rowBoundsWithCount", "true");
// prop.setProperty("params","pageNum=pageNum;pageSize=pageSize;");
// PageInterceptor pi = new PageInterceptor();
// pi.setProperties(prop);
// sessionFactory.setPlugins(new Interceptor[]{pi});
return sessionFactory;
}
} | repos\springBoot-master\springboot-springSecurity4\src\main\java\com\yy\example\config\MyBatisConfig.java | 2 |
请完成以下Java代码 | public JsonResponseManufacturingOrderBOMLine toJson(
@NonNull final I_PP_Order_BOMLine bomLine,
@NonNull final IPPOrderBOMBL ppOrderBOMBL,
@NonNull final ProductRepository productRepository)
{
final ProductId productId = ProductId.ofRepoId(bomLine.getM_Product_ID());
final Product product = productRepository.getById(productId);
final String adLanguage = Env.getADLanguageOrBaseLanguage();
final Quantity qtyRequiredToIssue = ppOrderBOMBL.getQtyRequiredToIssue(bomLine);
return JsonResponseManufacturingOrderBOMLine.builder()
.componentType(bomLine.getComponentType())
.product(toJsonProduct(product, adLanguage))
.qty(JsonConverter.toJsonQuantity(qtyRequiredToIssue))
.build();
}
@NonNull
public JsonResponseManufacturingOrder toJson(@NonNull final MapToJsonResponseManufacturingOrderRequest request)
{
final I_PP_Order ppOrder = request.getOrder();
final PPOrderId orderId = PPOrderId.ofRepoId(ppOrder.getPP_Order_ID());
final Quantity qtyToProduce = request.getPpOrderBOMBL().getQuantities(ppOrder).getQtyRequiredToProduce();
final OrgId orgId = OrgId.ofRepoId(ppOrder.getAD_Org_ID());
final IOrgDAO orgDAO = request.getOrgDAO();
final ZoneId timeZone = orgDAO.getTimeZone(orgId);
final String orgCode = orgDAO.retrieveOrgValue(orgId);
final ProductId productId = ProductId.ofRepoId(ppOrder.getM_Product_ID()); | final Product product = request.getProductRepository().getById(productId);
final String adLanguage = Env.getADLanguageOrBaseLanguage();
return JsonResponseManufacturingOrder.builder()
.orderId(JsonMetasfreshId.of(orderId.getRepoId()))
.orgCode(orgCode)
.documentNo(ppOrder.getDocumentNo())
.description(StringUtils.trimBlankToNull(ppOrder.getDescription()))
.finishGoodProduct(toJsonProduct(product, adLanguage))
.qtyToProduce(JsonConverter.toJsonQuantity(qtyToProduce))
.dateOrdered(TimeUtil.asZonedDateTime(ppOrder.getDateOrdered(), timeZone))
.datePromised(TimeUtil.asZonedDateTime(ppOrder.getDatePromised(), timeZone))
.dateStartSchedule(TimeUtil.asZonedDateTime(ppOrder.getDateStartSchedule(), timeZone))
.productId(JsonMetasfreshId.of(ppOrder.getM_Product_ID()))
.bpartnerId(JsonMetasfreshId.ofOrNull(ppOrder.getC_BPartner_ID()))
.components(request.getComponents())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\rest_api\v2\JsonConverter.java | 1 |
请完成以下Java代码 | public final void commit() throws SQLException
{
if (this.ownedConnection != null && !this.ownedConnection.getAutoCommit())
{
this.ownedConnection.commit();
}
}
@Nullable
private static Trx getTrx(@NonNull final CStatementVO vo)
{
final ITrxManager trxManager = Services.get(ITrxManager.class);
final String trxName = vo.getTrxName();
if (trxManager.isNull(trxName))
{
return (Trx)ITrx.TRX_None;
} | else
{
final ITrx trx = trxManager.get(trxName, false); // createNew=false
// NOTE: we assume trx if of type Trx because we need to invoke getConnection()
return (Trx)trx;
}
}
@Override
public String toString()
{
return "AbstractCStatementProxy [ownedConnection=" + this.ownedConnection + ", closed=" + closed + ", p_vo=" + vo + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\sql\impl\AbstractCStatementProxy.java | 1 |
请完成以下Java代码 | public Builder applyTo(ch.qos.logback.classic.Logger logger) {
this.logger = logger;
return this;
}
public Builder setContext(Context context) {
this.context = context;
return this;
}
public Builder setName(String name) {
this.name = name;
return this;
}
public Builder useSynchronization() {
this.useSynchronization = true;
return this;
}
private Optional<DelegatingAppender> getDelegate() {
return Optional.ofNullable(this.delegate);
}
private Optional<ch.qos.logback.classic.Logger> getLogger() {
return Optional.ofNullable(this.logger);
}
private Context resolveContext() {
return this.context != null
? this.context
: Optional.ofNullable(LoggerFactory.getILoggerFactory())
.filter(Context.class::isInstance)
.map(Context.class::cast)
.orElse(null);
}
private String resolveName() {
return this.name != null && !this.name.trim().isEmpty() ? this.name : DEFAULT_NAME;
}
private StringAppenderWrapper resolveStringAppenderWrapper() {
return this.useSynchronization
? StringBufferAppenderWrapper.create()
: StringBuilderAppenderWrapper.create();
}
public StringAppender build() {
StringAppender stringAppender =
new StringAppender(resolveStringAppenderWrapper());
stringAppender.setContext(resolveContext());
stringAppender.setName(resolveName());
getDelegate().ifPresent(delegate -> {
Appender appender = this.replace ? stringAppender
: CompositeAppender.compose(delegate.getAppender(), stringAppender);
delegate.setAppender(appender);
});
getLogger().ifPresent(logger -> logger.addAppender(stringAppender));
return stringAppender;
}
public StringAppender buildAndStart() {
StringAppender stringAppender = build();
stringAppender.start(); | return stringAppender;
}
}
private final StringAppenderWrapper stringAppenderWrapper;
protected StringAppender(StringAppenderWrapper stringAppenderWrapper) {
if (stringAppenderWrapper == null) {
throw new IllegalArgumentException("StringAppenderWrapper must not be null");
}
this.stringAppenderWrapper = stringAppenderWrapper;
}
public String getLogOutput() {
return getStringAppenderWrapper().toString();
}
protected StringAppenderWrapper getStringAppenderWrapper() {
return this.stringAppenderWrapper;
}
@Override
protected void append(ILoggingEvent loggingEvent) {
Optional.ofNullable(loggingEvent)
.map(event -> preProcessLogMessage(toString(event)))
.filter(this::isValidLogMessage)
.ifPresent(getStringAppenderWrapper()::append);
}
protected boolean isValidLogMessage(String message) {
return message != null && !message.isEmpty();
}
protected String preProcessLogMessage(String message) {
return message != null ? message.trim() : null;
}
protected String toString(ILoggingEvent loggingEvent) {
return loggingEvent != null ? loggingEvent.getFormattedMessage() : null;
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode-starters\spring-geode-starter-logging\src\main\java\org\springframework\geode\logging\slf4j\logback\StringAppender.java | 1 |
请完成以下Java代码 | public AuthenticationManager resolve(HttpServletRequest context) {
for (RequestMatcherEntry<AuthenticationManager> entry : this.authenticationManagers) {
if (entry.getRequestMatcher().matches(context)) {
return entry.getEntry();
}
}
return this.defaultAuthenticationManager;
}
/**
* Set the default {@link AuthenticationManager} to use when a request does not match
* @param defaultAuthenticationManager the default {@link AuthenticationManager} to
* use
*/
public void setDefaultAuthenticationManager(AuthenticationManager defaultAuthenticationManager) {
Assert.notNull(defaultAuthenticationManager, "defaultAuthenticationManager cannot be null");
this.defaultAuthenticationManager = defaultAuthenticationManager;
}
/**
* Creates a builder for {@link RequestMatcherDelegatingAuthorizationManager}.
* @return the new {@link RequestMatcherDelegatingAuthorizationManager.Builder}
* instance
*/
public static Builder builder() {
return new Builder();
}
/**
* A builder for {@link RequestMatcherDelegatingAuthenticationManagerResolver}.
*/
public static final class Builder {
private final List<RequestMatcherEntry<AuthenticationManager>> entries = new ArrayList<>();
private Builder() {
}
/**
* Maps a {@link RequestMatcher} to an {@link AuthorizationManager}.
* @param matcher the {@link RequestMatcher} to use
* @param manager the {@link AuthenticationManager} to use
* @return the {@link Builder} for further
* customizationServerWebExchangeDelegatingReactiveAuthenticationManagerResolvers | */
public Builder add(RequestMatcher matcher, AuthenticationManager manager) {
Assert.notNull(matcher, "matcher cannot be null");
Assert.notNull(manager, "manager cannot be null");
this.entries.add(new RequestMatcherEntry<>(matcher, manager));
return this;
}
/**
* Creates a {@link RequestMatcherDelegatingAuthenticationManagerResolver}
* instance.
* @return the {@link RequestMatcherDelegatingAuthenticationManagerResolver}
* instance
*/
public RequestMatcherDelegatingAuthenticationManagerResolver build() {
return new RequestMatcherDelegatingAuthenticationManagerResolver(this.entries);
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\RequestMatcherDelegatingAuthenticationManagerResolver.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.