instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private void setAsRunning(final I_C_Invoice_Verification_Run run)
{
run.setStatus(InvoiceVerificationRunStatus.Running.getCode());
run.setDateStart(SystemTime.asTimestamp());
run.setAD_PInstance_ID(getPinstanceId().getRepoId());
InterfaceWrapperHelper.save(run);
}
private void setCompleted(final I_C_Invoice_Verification_Run run)
{
run.setStatus(InvoiceVerificationRunStatus.Finished.getCode());
run.setDateEnd(SystemTime.asTimestamp());
InterfaceWrapperHelper.save(run);
}
private InvoiceVerificationRunStatus getInvoiceVerificationRunStatus(final @NonNull IProcessPreconditionsContext context)
{ | final I_C_Invoice_Verification_Run run = Check.assumeNotNull(queryBL.createQueryBuilder(I_C_Invoice_Verification_Run.class)
.addOnlyActiveRecordsFilter()
.filter(context.getQueryFilter(I_C_Invoice_Verification_Run.class))
.create().firstOnly(I_C_Invoice_Verification_Run.class), "C_Invoice_Verification_Run with ID {} not found", context.getSingleSelectedRecordId());
return Check.isBlank(run.getStatus()) ? InvoiceVerificationRunStatus.Planned : InvoiceVerificationRunStatus.ofNullableCode(run.getStatus());
}
@NonNull
private I_C_Invoice_Verification_Run getInvoiceVerificationRun()
{
return Check.assumeNotNull(queryBL.createQueryBuilder(I_C_Invoice_Verification_Run.class)
.addOnlyActiveRecordsFilter()
.filter(getProcessInfo().getQueryFilterOrElseFalse())
.create().firstOnly(I_C_Invoice_Verification_Run.class), "C_Invoice_Verification_Run with ID {} not found", getProcessInfo().getRecord_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\process\C_Invoice_Verification_Run_Execute.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DefaultVariableTypes addType(VariableType type) {
return addType(type, typesList.size());
}
@Override
public DefaultVariableTypes addType(VariableType type, int index) {
typesList.add(index, type);
typesMap.put(type.getTypeName(), type);
return this;
}
public void setTypesList(List<VariableType> typesList) {
this.typesList.clear();
this.typesList.addAll(typesList);
this.typesMap.clear();
for (VariableType type : typesList) {
typesMap.put(type.getTypeName(), type);
}
}
@Override
public VariableType getVariableType(String typeName) {
return typesMap.get(typeName);
}
@Override
public VariableType findVariableType(Object value) {
for (VariableType type : typesList) {
if (type.isAbleToStore(value)) {
return type;
}
}
throw new FlowableException("couldn't find a variable type that is able to serialize " + value);
}
@Override
public int getTypeIndex(VariableType type) {
return typesList.indexOf(type); | }
@Override
public int getTypeIndex(String typeName) {
VariableType type = typesMap.get(typeName);
if (type != null) {
return getTypeIndex(type);
} else {
return -1;
}
}
@Override
public VariableTypes removeType(VariableType type) {
typesList.remove(type);
typesMap.remove(type.getTypeName());
return this;
}
public int size() {
return typesList.size();
}
} | repos\flowable-engine-main\modules\flowable-variable-service\src\main\java\org\flowable\variable\service\impl\types\DefaultVariableTypes.java | 2 |
请完成以下Java代码 | public static class Settings {
private final String title;
private final String brand;
private final String loginIcon;
private final String favicon;
private final String faviconDanger;
private final PollTimer pollTimer;
private final UiTheme theme;
private final boolean notificationFilterEnabled;
private final boolean rememberMeEnabled;
private final List<String> availableLanguages;
private final List<String> routes;
private final List<ExternalView> externalViews;
private final List<ViewSettings> viewSettings;
private final Boolean enableToasts;
private final Boolean hideInstanceUrl;
private final Boolean disableInstanceUrl;
}
@lombok.Data
@JsonInclude(Include.NON_EMPTY)
public static class ExternalView {
/**
* Label to be shown in the navbar.
*/
private final String label;
/**
* Url for the external view to be linked
*/
private final String url;
/**
* Order in the navbar.
*/
private final Integer order; | /**
* Should the page shown as an iframe or open in a new window.
*/
private final boolean iframe;
/**
* A list of child views.
*/
private final List<ExternalView> children;
public ExternalView(String label, String url, Integer order, boolean iframe, List<ExternalView> children) {
Assert.hasText(label, "'label' must not be empty");
if (isEmpty(children)) {
Assert.hasText(url, "'url' must not be empty");
}
this.label = label;
this.url = url;
this.order = order;
this.iframe = iframe;
this.children = children;
}
}
@lombok.Data
@JsonInclude(Include.NON_EMPTY)
public static class ViewSettings {
/**
* Name of the view to address.
*/
private final String name;
/**
* Set view enabled.
*/
private boolean enabled;
public ViewSettings(String name, boolean enabled) {
Assert.hasText(name, "'name' must not be empty");
this.name = name;
this.enabled = enabled;
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-server-ui\src\main\java\de\codecentric\boot\admin\server\ui\web\UiController.java | 1 |
请完成以下Java代码 | public void clearDiagnosticsData() {
DiagnosticsRegistry diagnosticsRegistry = ((ProcessEngineConfigurationImpl) processEngineConfiguration).getDiagnosticsRegistry();
if (diagnosticsRegistry != null) {
diagnosticsRegistry.clear();
}
MetricsRegistry metricsRegistry = ((ProcessEngineConfigurationImpl) processEngineConfiguration).getMetricsRegistry();
if(metricsRegistry != null) {
metricsRegistry.clearDiagnosticsMetrics();
}
deleteMetrics(null);
}
protected class DbSchemaUpgradeCmd implements Command<String> {
protected Connection connection;
protected String catalog;
protected String schema;
public DbSchemaUpgradeCmd(Connection connection, String catalog, String schema) {
this.connection = connection;
this.catalog = catalog;
this.schema = schema;
}
@Override
public String execute(CommandContext commandContext) {
commandContext.getAuthorizationManager().checkCamundaAdmin();
DbSqlSessionFactory dbSqlSessionFactory = (DbSqlSessionFactory) commandContext.getSessionFactories().get(DbSqlSession.class); | DbSqlSession dbSqlSession = dbSqlSessionFactory.openSession(connection, catalog, schema);
commandContext.getSessions().put(DbSqlSession.class, dbSqlSession);
dbSqlSession.dbSchemaUpdate();
return "";
}
}
protected class GetRegisteredDeploymentsCmd implements Command<Set<String>> {
@Override
public Set<String> execute(CommandContext commandContext) {
commandContext.getAuthorizationManager().checkCamundaAdminOrPermission(CommandChecker::checkReadRegisteredDeployments);
Set<String> registeredDeployments = Context.getProcessEngineConfiguration().getRegisteredDeployments();
return new HashSet<>(registeredDeployments);
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ManagementServiceImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private static FTSConfigField toFTSConfigField(final I_ES_FTS_Config_Field record)
{
return FTSConfigField.builder()
.id(FTSConfigFieldId.ofRepoId(record.getES_FTS_Config_Field_ID()))
.esFieldName(ESFieldName.ofString(record.getES_FieldName()))
.build();
}
public void setConfigFields(
@NonNull final FTSConfigId configId,
@NonNull final Set<ESFieldName> esFieldNames)
{
final HashMap<ESFieldName, I_ES_FTS_Config_Field> records = queryBL.createQueryBuilder(I_ES_FTS_Config_Field.class)
.addEqualsFilter(I_ES_FTS_Config_Field.COLUMNNAME_ES_FTS_Config_ID, configId)
.create()
.stream()
.collect(GuavaCollectors.toHashMapByKey(record -> ESFieldName.ofString(record.getES_FieldName())));
for (final ESFieldName esFieldName : esFieldNames)
{
I_ES_FTS_Config_Field record = records.remove(esFieldName);
if (record == null)
{
record = InterfaceWrapperHelper.newInstance(I_ES_FTS_Config_Field.class);
record.setES_FTS_Config_ID(configId.getRepoId());
record.setES_FieldName(esFieldName.getAsString());
}
record.setIsActive(true);
InterfaceWrapperHelper.saveRecord(record);
}
InterfaceWrapperHelper.deleteAll(records.values());
}
//
//
// ----------------------------------
//
//
public static class FTSConfigsMap
{
@Getter
private final ImmutableList<FTSConfig> configs;
private final ImmutableMap<String, FTSConfig> configsByESIndexName;
private final ImmutableMap<FTSConfigId, FTSConfig> configsById;
@Getter
private final FTSConfigSourceTablesMap sourceTables;
private FTSConfigsMap(
@NonNull final List<FTSConfig> configs,
@NonNull final FTSConfigSourceTablesMap sourceTables) | {
this.configs = ImmutableList.copyOf(configs);
this.configsByESIndexName = Maps.uniqueIndex(configs, FTSConfig::getEsIndexName);
this.configsById = Maps.uniqueIndex(configs, FTSConfig::getId);
this.sourceTables = sourceTables
.filter(sourceTable -> configsById.containsKey(sourceTable.getFtsConfigId())); // only active configs
}
public Optional<FTSConfig> getByESIndexName(@NonNull final String esIndexName)
{
return Optional.ofNullable(configsByESIndexName.get(esIndexName));
}
public FTSConfig getById(@NonNull final FTSConfigId ftsConfigId)
{
final FTSConfig config = configsById.get(ftsConfigId);
if (config == null)
{
throw new AdempiereException("No config found for " + ftsConfigId);
}
return config;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.elasticsearch\src\main\java\de\metas\fulltextsearch\config\FTSConfigRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public abstract class AbstractEntity implements Serializable
{
@Id
@GeneratedValue
private Long id;
private boolean deleted = false;
@NonNull
private String uuid = UUID.randomUUID().toString();
//
// Versioning and created/updated timestamps
protected static final int VERSION_INITIAL = 0;
@Version
private final int version = VERSION_INITIAL;
@Temporal(TemporalType.TIMESTAMP)
private Date dateCreated;
@Temporal(TemporalType.TIMESTAMP)
private Date dateUpdated;
AbstractEntity()
{
super();
}
@PreUpdate
@PrePersist
public void updateCreatedUpdated()
{
final Date now = new Date();
this.dateUpdated = now;
if (dateCreated == null)
{
dateCreated = now;
}
}
@Override
public String toString()
{
final MoreObjects.ToStringHelper toStringHelper = MoreObjects.toStringHelper(this);
toString(toStringHelper);
return toStringHelper
.add("id", id)
.add("version", version)
.add("deleted", deleted)
.add("uuid", uuid)
.toString();
}
protected void toString(final MoreObjects.ToStringHelper toStringHelper)
{
// nothing at this level
}
public Long getId()
{
return id;
}
public String getIdAsString()
{
return String.valueOf(getId());
}
public String getUuid()
{
return uuid;
}
public void setUuid(final String uuid)
{
this.uuid = uuid; | }
public int getVersion()
{
return version;
}
public void setDeleted(final boolean deleted)
{
this.deleted = deleted;
}
public boolean isDeleted()
{
return deleted;
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + Objects.hashCode(id);
return result;
}
@Override
public boolean equals(final Object obj)
{
if (this == obj)
{
return true;
}
if (obj == null)
{
return false;
}
if (getClass() != obj.getClass())
{
return false;
}
final AbstractEntity other = (AbstractEntity)obj;
return Objects.equals(id, other.id);
}
protected Date getDateCreated()
{
return dateCreated;
}
protected Date getDateUpdated()
{
return dateUpdated;
}
} | repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\model\AbstractEntity.java | 2 |
请完成以下Java代码 | private boolean isClientLevelOnly()
{
return getShareType().equals(SHARETYPE_ClientAllShared);
}
/**
* Is Org Level Only
*
* @return true if org level only (not shared)
*/
private boolean isOrgLevelOnly()
{
return getShareType().equals(SHARETYPE_OrgNotShared);
}
private String getTableName()
{
return Services.get(IADTableDAO.class).retrieveTableName(getAD_Table_ID());
}
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
if (isActive())
{
setDataToLevel();
listChildRecords();
}
return true;
}
private String setDataToLevel()
{
String info = "-";
if (isClientLevelOnly())
{
StringBuilder sql = new StringBuilder("UPDATE ")
.append(getTableName())
.append(" SET AD_Org_ID=0 WHERE AD_Org_ID<>0 AND AD_Client_ID=?");
int no = DB.executeUpdateAndSaveErrorOnFail(sql.toString(), getAD_Client_ID(), get_TrxName());
info = getTableName() + " set to Shared #" + no;
log.info(info);
}
else if (isOrgLevelOnly())
{
StringBuilder sql = new StringBuilder("SELECT COUNT(*) FROM ")
.append(getTableName())
.append(" WHERE AD_Org_ID=0 AND AD_Client_ID=?");
int no = DB.getSQLValue(get_TrxName(), sql.toString(), getAD_Client_ID());
info = getTableName() + " Shared records #" + no;
log.info(info);
}
return info;
} // setDataToLevel
private String listChildRecords()
{
final StringBuilder info = new StringBuilder();
String sql = "SELECT AD_Table_ID, TableName "
+ "FROM AD_Table t "
+ "WHERE AccessLevel='3' AND IsView='N'"
+ " AND EXISTS (SELECT * FROM AD_Column c "
+ "WHERE t.AD_Table_ID=c.AD_Table_ID" | + " AND c.IsParent='Y'"
+ " AND c.ColumnName IN (SELECT ColumnName FROM AD_Column cc "
+ "WHERE cc.IsKey='Y' AND cc.AD_Table_ID=?))";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, null);
pstmt.setInt(1, getAD_Table_ID());
rs = pstmt.executeQuery();
while (rs.next())
{
String TableName = rs.getString(2);
if (info.length() != 0)
{
info.append(", ");
}
info.append(TableName);
}
}
catch (Exception e)
{
log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
}
return info.toString();
}
@Override
protected boolean beforeSave(boolean newRecord)
{
if (getAD_Org_ID() != 0)
{
setAD_Org_ID(0);
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MClientShare.java | 1 |
请完成以下Java代码 | public void setQtyEntered (BigDecimal QtyEntered)
{
set_ValueNoCheck (COLUMNNAME_QtyEntered, QtyEntered);
}
/** Get Menge.
@return Die Eingegebene Menge basiert auf der gewaehlten Mengeneinheit
*/
public BigDecimal getQtyEntered ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyEntered);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Quantity Invoiced.
@param QtyInvoiced
Invoiced Quantity | */
public void setQtyInvoiced (BigDecimal QtyInvoiced)
{
set_ValueNoCheck (COLUMNNAME_QtyInvoiced, QtyInvoiced);
}
/** Get Quantity Invoiced.
@return Invoiced Quantity
*/
public BigDecimal getQtyInvoiced ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_QtyInvoiced);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\org\adempiere\model\X_RV_C_InvoiceLine_Overview.java | 1 |
请完成以下Java代码 | public void assertNoLoops(final I_AD_Role_Included roleIncluded)
{
final RoleId includedRoleId = RoleId.ofRepoIdOrNull(roleIncluded.getIncluded_Role_ID());
final List<RoleId> trace = new ArrayList<>();
if (hasLoop(includedRoleId, trace))
{
final IRoleDAO roleDAO = Services.get(IRoleDAO.class);
final StringBuilder roles = new StringBuilder();
for (final RoleId roleId : trace)
{
if (roles.length() > 0)
roles.append(" - ");
roles.append(roleDAO.getRoleName(roleId));
}
throw new AdempiereException("Loop has detected: " + roles);
}
}
/**
* @return true if loop detected. If you specified not null trace, you will have in that list the IDs from the loop
*/
// TODO: use recursive WITH sql clause
private static boolean hasLoop(final RoleId roleId, final List<RoleId> trace)
{
final List<RoleId> trace2;
if (trace == null)
{
trace2 = new ArrayList<>();
}
else
{
trace2 = new ArrayList<>(trace);
}
trace2.add(roleId);
//
final String sql = "SELECT "
+ I_AD_Role_Included.COLUMNNAME_Included_Role_ID
+ "," + I_AD_Role_Included.COLUMNNAME_AD_Role_ID
+ " FROM " + I_AD_Role_Included.Table_Name
+ " WHERE " + I_AD_Role_Included.COLUMNNAME_AD_Role_ID + "=?";
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_ThreadInherited);
DB.setParameters(pstmt, roleId);
rs = pstmt.executeQuery();
while (rs.next()) | {
final RoleId childId = RoleId.ofRepoId(rs.getInt(1));
if (trace2.contains(childId))
{
trace.clear();
trace.addAll(trace2);
trace.add(childId);
return true;
}
if (hasLoop(childId, trace2))
{
trace.clear();
trace.addAll(trace2);
return true;
}
}
}
catch (SQLException e)
{
throw new DBException(e, sql);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
//
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\model\interceptor\AD_Role_Included.java | 1 |
请完成以下Java代码 | 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 X_C_BankStatement_Import_File_Log extends org.compiere.model.PO implements I_C_BankStatement_Import_File_Log, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -943655227L;
/** Standard Constructor */
public X_C_BankStatement_Import_File_Log (final Properties ctx, final int C_BankStatement_Import_File_Log_ID, @Nullable final String trxName)
{
super (ctx, C_BankStatement_Import_File_Log_ID, trxName);
}
/** Load Constructor */
public X_C_BankStatement_Import_File_Log (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 setAD_Issue_ID (final int AD_Issue_ID)
{
if (AD_Issue_ID < 1)
set_Value (COLUMNNAME_AD_Issue_ID, null);
else
set_Value (COLUMNNAME_AD_Issue_ID, AD_Issue_ID);
}
@Override
public int getAD_Issue_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_Issue_ID);
}
@Override
public I_C_BankStatement_Import_File getC_BankStatement_Import_File()
{
return get_ValueAsPO(COLUMNNAME_C_BankStatement_Import_File_ID, I_C_BankStatement_Import_File.class);
}
@Override
public void setC_BankStatement_Import_File(final I_C_BankStatement_Import_File C_BankStatement_Import_File)
{
set_ValueFromPO(COLUMNNAME_C_BankStatement_Import_File_ID, I_C_BankStatement_Import_File.class, C_BankStatement_Import_File);
}
@Override | public void setC_BankStatement_Import_File_ID (final int C_BankStatement_Import_File_ID)
{
if (C_BankStatement_Import_File_ID < 1)
set_Value (COLUMNNAME_C_BankStatement_Import_File_ID, null);
else
set_Value (COLUMNNAME_C_BankStatement_Import_File_ID, C_BankStatement_Import_File_ID);
}
@Override
public int getC_BankStatement_Import_File_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BankStatement_Import_File_ID);
}
@Override
public void setC_BankStatement_Import_File_Log_ID (final int C_BankStatement_Import_File_Log_ID)
{
if (C_BankStatement_Import_File_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BankStatement_Import_File_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BankStatement_Import_File_Log_ID, C_BankStatement_Import_File_Log_ID);
}
@Override
public int getC_BankStatement_Import_File_Log_ID()
{
return get_ValueAsInt(COLUMNNAME_C_BankStatement_Import_File_Log_ID);
}
@Override
public void setLogmessage (final @Nullable java.lang.String Logmessage)
{
set_Value (COLUMNNAME_Logmessage, Logmessage);
}
@Override
public java.lang.String getLogmessage()
{
return get_ValueAsString(COLUMNNAME_Logmessage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\org\adempiere\banking\model\X_C_BankStatement_Import_File_Log.java | 1 |
请完成以下Java代码 | public class Person {
private SimpleIntegerProperty id;
private SimpleStringProperty name;
private SimpleBooleanProperty isEmployed;
public Person(Integer id, String name, boolean isEmployed) {
this.id = new SimpleIntegerProperty(id);
this.name = new SimpleStringProperty(name);
this.isEmployed = new SimpleBooleanProperty(isEmployed);
}
public int getId() {
return id.get();
}
public IntegerProperty idProperty() {
return id;
}
public void setId(int id) {
this.id.set(id);
}
public String getName() {
return name.get();
}
public StringProperty nameProperty() {
return name; | }
public void setName(String name) {
this.name.set(name);
}
public boolean getIsEmployed() {
return isEmployed.get();
}
public BooleanProperty isEmployedProperty() {
return isEmployed;
}
public void setIsEmployed(boolean isEmployed) {
this.isEmployed.set(isEmployed);
}
@Override
public String toString() {
return "Person{" +
"id=" + id +
", name='" + name + '\'' +
", isEmployed=" + isEmployed +
'}';
}
} | repos\tutorials-master\javafx\src\main\java\com\baeldung\model\Person.java | 1 |
请完成以下Java代码 | public int getM_TU_HU_ID()
{
return get_ValueAsInt(COLUMNNAME_M_TU_HU_ID);
}
@Override
public void setProcessed (final boolean Processed)
{
set_Value (COLUMNNAME_Processed, Processed);
}
@Override
public boolean isProcessed()
{
return get_ValueAsBoolean(COLUMNNAME_Processed);
}
@Override
public void setQtyDeliveredCatch (final @Nullable BigDecimal QtyDeliveredCatch)
{
set_Value (COLUMNNAME_QtyDeliveredCatch, QtyDeliveredCatch);
}
@Override
public BigDecimal getQtyDeliveredCatch()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyDeliveredCatch);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyLU (final @Nullable BigDecimal QtyLU)
{
set_Value (COLUMNNAME_QtyLU, QtyLU);
}
@Override
public BigDecimal getQtyLU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyLU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyPicked (final BigDecimal QtyPicked)
{
set_Value (COLUMNNAME_QtyPicked, QtyPicked);
}
@Override
public BigDecimal getQtyPicked()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyPicked);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyTU (final @Nullable BigDecimal QtyTU) | {
set_Value (COLUMNNAME_QtyTU, QtyTU);
}
@Override
public BigDecimal getQtyTU()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyTU);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setVHU_ID (final int VHU_ID)
{
if (VHU_ID < 1)
set_Value (COLUMNNAME_VHU_ID, null);
else
set_Value (COLUMNNAME_VHU_ID, VHU_ID);
}
@Override
public int getVHU_ID()
{
return get_ValueAsInt(COLUMNNAME_VHU_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_ShipmentSchedule_QtyPicked.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Connector tagTextConnector() {
return integrationContext -> {
LinkedHashMap contentToTag = (LinkedHashMap) integrationContext.getInBoundVariables().get("content");
contentToTag.put("tags", singletonList(" :) "));
integrationContext.addOutBoundVariable("content", contentToTag);
logger.info("Final Content: " + contentToTag);
return integrationContext;
};
}
@Bean
public Connector discardTextConnector() {
return integrationContext -> {
LinkedHashMap contentToDiscard = (LinkedHashMap) integrationContext.getInBoundVariables().get("content");
contentToDiscard.put("tags", singletonList(" :( "));
integrationContext.addOutBoundVariable("content", contentToDiscard);
logger.info("Final Content: " + contentToDiscard);
return integrationContext;
};
} | private LinkedHashMap pickRandomString() {
String[] texts = {
"hello from london",
"Hi there from activiti!",
"all good news over here.",
"I've tweeted about activiti today.",
"other boring projects.",
"activiti cloud - Cloud Native Java BPM",
};
LinkedHashMap<Object, Object> content = new LinkedHashMap<>();
content.put("body", texts[new Random().nextInt(texts.length)]);
return content;
}
} | repos\Activiti-develop\activiti-examples\activiti-api-basic-full-example-nobean\src\main\java\org\activiti\examples\DemoApplication.java | 2 |
请完成以下Java代码 | public void setSelectClause (String SelectClause)
{
set_Value (COLUMNNAME_SelectClause, SelectClause);
}
/** Get Sql SELECT.
@return SQL SELECT clause
*/
public String getSelectClause ()
{
return (String)get_Value(COLUMNNAME_SelectClause);
}
/** Set Reihenfolge.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Reihenfolge.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public boolean isTree()
{
Object oo = get_Value(COLUMNNAME_IsTree);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public void setIsTree(boolean IsTree)
{
set_Value (COLUMNNAME_IsTree, Boolean.valueOf(IsTree));
}
@Override
public boolean isParameterNextLine()
{
Object oo = get_Value(COLUMNNAME_IsParameterNextLine);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
@Override
public void setIsParameterNextLine(boolean IsParameterNextLine)
{
set_Value (COLUMNNAME_IsParameterNextLine, Boolean.valueOf(IsParameterNextLine));
}
public void setParameterSeqNo (int ParameterSeqNo)
{
set_Value (COLUMNNAME_ParameterSeqNo, Integer.valueOf(ParameterSeqNo));
}
public int getParameterSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_ParameterSeqNo); | if (ii == null)
return 0;
return ii.intValue();
}
public void setParameterDisplayLogic (String ParameterDisplayLogic)
{
set_Value (COLUMNNAME_ParameterDisplayLogic, ParameterDisplayLogic);
}
public String getParameterDisplayLogic ()
{
return (String)get_Value(COLUMNNAME_ParameterDisplayLogic);
}
public void setColumnName (String ColumnName)
{
set_Value (COLUMNNAME_ColumnName, ColumnName);
}
public String getColumnName ()
{
return (String)get_Value(COLUMNNAME_ColumnName);
}
/** Set Query Criteria Function.
@param QueryCriteriaFunction
column used for adding a sql function to query criteria
*/
public void setQueryCriteriaFunction (String QueryCriteriaFunction)
{
set_Value (COLUMNNAME_QueryCriteriaFunction, QueryCriteriaFunction);
}
/** Get Query Criteria Function.
@return column used for adding a sql function to query criteria
*/
public String getQueryCriteriaFunction ()
{
return (String)get_Value(COLUMNNAME_QueryCriteriaFunction);
}
@Override
public void setDefaultValue (String DefaultValue)
{
set_Value (COLUMNNAME_DefaultValue, DefaultValue);
}
@Override
public String getDefaultValue ()
{
return (String)get_Value(COLUMNNAME_DefaultValue);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_InfoColumn.java | 1 |
请完成以下Java代码 | public Mono<ArticleViewWrapper> updateArticle(@RequestBody UpdateArticleRequestWrapper request, @PathVariable String slug) {
return userSessionProvider.getCurrentUserOrEmpty()
.flatMap(currentUser -> articleFacade.updateArticle(slug, request.getContent(), currentUser))
.map(ArticleViewWrapper::new);
}
@DeleteMapping("/articles/{slug}")
public Mono<Void> deleteArticle(@PathVariable String slug) {
return userSessionProvider.getCurrentUserOrEmpty()
.flatMap(currentUser -> articleFacade.deleteArticle(slug, currentUser));
}
@GetMapping("/articles/{slug}/comments")
public Mono<MultipleCommentsView> getComments(@PathVariable String slug) {
return userSessionProvider.getCurrentUserOrEmpty()
.flatMap(currentUser -> articleFacade.getComments(slug, Optional.of(currentUser)))
.switchIfEmpty(articleFacade.getComments(slug, Optional.empty()));
}
@PostMapping("/articles/{slug}/comments")
@ResponseStatus(HttpStatus.CREATED)
public Mono<CommentViewWrapper> addComment(@PathVariable String slug, @RequestBody CreateCommentRequestWrapper request) {
return userSessionProvider.getCurrentUserOrEmpty()
.flatMap(currentUser -> articleFacade.addComment(slug, request.getContent(), currentUser))
.map(CommentViewWrapper::new);
}
@DeleteMapping("/articles/{slug}/comments/{commentId}")
public Mono<Void> deleteComment(@PathVariable String commentId, @PathVariable String slug) {
return userSessionProvider.getCurrentUserOrEmpty()
.flatMap(currentUser -> articleFacade.deleteComment(commentId, slug, currentUser));
} | @PostMapping("/articles/{slug}/favorite")
@ResponseStatus(HttpStatus.CREATED)
public Mono<ArticleViewWrapper> favoriteArticle(@PathVariable String slug) {
return userSessionProvider.getCurrentUserOrEmpty()
.flatMap(currentUser -> articleFacade.favoriteArticle(slug, currentUser))
.map(ArticleViewWrapper::new);
}
@DeleteMapping("/articles/{slug}/favorite")
public Mono<ArticleViewWrapper> unfavoriteArticle(@PathVariable String slug) {
return userSessionProvider.getCurrentUserOrEmpty()
.flatMap(currentUser -> articleFacade.unfavoriteArticle(slug, currentUser))
.map(ArticleViewWrapper::new);
}
@GetMapping("/tags")
public Mono<TagListView> getTags() {
return articleFacade.getTags();
}
} | repos\realworld-spring-webflux-master\src\main\java\com\realworld\springmongo\api\ArticleController.java | 1 |
请完成以下Java代码 | public String[] getExecutionIds() {
return executionIds;
}
/** the activity name */
public String getActivityName() {
return activityName;
}
/**
* deprecated; the JSON field with this name was never documented, but existed
* from 7.0 to 7.2
*/
public String getName() {
return activityName;
}
public String[] getIncidentIds() {
return incidentIds;
}
public ActivityInstanceIncidentDto[] getIncidents() {
return incidents;
}
public static ActivityInstanceDto fromActivityInstance(ActivityInstance instance) {
ActivityInstanceDto result = new ActivityInstanceDto();
result.id = instance.getId();
result.parentActivityInstanceId = instance.getParentActivityInstanceId(); | result.activityId = instance.getActivityId();
result.activityType = instance.getActivityType();
result.processInstanceId = instance.getProcessInstanceId();
result.processDefinitionId = instance.getProcessDefinitionId();
result.childActivityInstances = fromListOfActivityInstance(instance.getChildActivityInstances());
result.childTransitionInstances = TransitionInstanceDto.fromListOfTransitionInstance(instance.getChildTransitionInstances());
result.executionIds = instance.getExecutionIds();
result.activityName = instance.getActivityName();
result.incidentIds = instance.getIncidentIds();
result.incidents = ActivityInstanceIncidentDto.fromIncidents(instance.getIncidents());
return result;
}
public static ActivityInstanceDto[] fromListOfActivityInstance(ActivityInstance[] instances) {
ActivityInstanceDto[] result = new ActivityInstanceDto[instances.length];
for (int i = 0; i < result.length; i++) {
result[i] = fromActivityInstance(instances[i]);
}
return result;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\ActivityInstanceDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getTAXRATE() {
return taxrate;
}
/**
* Sets the value of the taxrate property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXRATE(String value) {
this.taxrate = value;
}
/**
* Gets the value of the taxcategory property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXCATEGORY() {
return taxcategory;
}
/**
* Sets the value of the taxcategory property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXCATEGORY(String value) {
this.taxcategory = value;
}
/**
* Gets the value of the taxamount property.
*
* @return
* possible object is
* {@link String }
*
*/ | public String getTAXAMOUNT() {
return taxamount;
}
/**
* Sets the value of the taxamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXAMOUNT(String value) {
this.taxamount = value;
}
/**
* Gets the value of the taxableamount property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getTAXABLEAMOUNT() {
return taxableamount;
}
/**
* Sets the value of the taxableamount property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setTAXABLEAMOUNT(String value) {
this.taxableamount = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DALCH1.java | 2 |
请完成以下Java代码 | public void deleteTenantProfiles(TenantId tenantId) {
log.trace("Executing deleteTenantProfiles");
tenantProfilesRemover.removeEntities(tenantId, null);
}
@Override
public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findTenantProfileById(tenantId, new TenantProfileId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(tenantProfileDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.TENANT_PROFILE;
} | private final PaginatedRemover<String, TenantProfile> tenantProfilesRemover = new PaginatedRemover<>() {
@Override
protected PageData<TenantProfile> findEntities(TenantId tenantId, String id, PageLink pageLink) {
return tenantProfileDao.findTenantProfiles(tenantId, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, TenantProfile entity) {
removeTenantProfile(tenantId, entity, entity.isDefault());
}
};
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\tenant\TenantProfileServiceImpl.java | 1 |
请完成以下Java代码 | private I_M_HU_PI_Item_Product getM_HU_PI_Item_Product()
{
Check.assumeNotNull(_huPIItemProduct, "_huPIItemProduct not null");
return _huPIItemProduct;
}
@Override
public IHUPIItemProductDisplayNameBuilder setQtyTUPlanned(final BigDecimal qtyTUPlanned)
{
_qtyTUPlanned = qtyTUPlanned;
return this;
}
@Override
public IHUPIItemProductDisplayNameBuilder setQtyTUPlanned(final int qtyTUPlanned)
{
setQtyTUPlanned(BigDecimal.valueOf(qtyTUPlanned));
return this;
}
@Override
public IHUPIItemProductDisplayNameBuilder setQtyTUMoved(final BigDecimal qtyTUMoved)
{
_qtyTUMoved = qtyTUMoved;
return this;
}
@Override
public IHUPIItemProductDisplayNameBuilder setQtyTUMoved(final int qtyTUMoved)
{
setQtyTUMoved(BigDecimal.valueOf(qtyTUMoved));
return this;
}
@Override
public HUPIItemProductDisplayNameBuilder setQtyCapacity(final BigDecimal qtyCapacity)
{ | _qtyCapacity = qtyCapacity;
return this;
}
@Override
public IHUPIItemProductDisplayNameBuilder setShowAnyProductIndicator(boolean showAnyProductIndicator)
{
this._showAnyProductIndicator = showAnyProductIndicator;
return this;
}
private boolean isShowAnyProductIndicator()
{
return _showAnyProductIndicator;
}
private boolean isAnyProductAllowed()
{
return getM_HU_PI_Item_Product().isAllowAnyProduct();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUPIItemProductDisplayNameBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public RuleOriginatedNotificationInfo constructNotificationInfo(AlarmAssignmentTrigger trigger) {
AlarmInfo alarmInfo = trigger.getAlarmInfo();
AlarmAssignee assignee = alarmInfo.getAssignee();
return AlarmAssignmentNotificationInfo.builder()
.action(trigger.getActionType() == ActionType.ALARM_ASSIGNED ? "assigned" : "unassigned")
.assigneeFirstName(assignee != null ? assignee.getFirstName() : null)
.assigneeLastName(assignee != null ? assignee.getLastName() : null)
.assigneeEmail(assignee != null ? assignee.getEmail() : null)
.assigneeId(assignee != null ? assignee.getId() : null)
.userEmail(trigger.getUser().getEmail())
.userFirstName(trigger.getUser().getFirstName())
.userLastName(trigger.getUser().getLastName())
.alarmId(alarmInfo.getUuidId())
.alarmType(alarmInfo.getType())
.alarmOriginator(alarmInfo.getOriginator()) | .alarmOriginatorName(alarmInfo.getOriginatorName())
.alarmOriginatorLabel(alarmInfo.getOriginatorLabel())
.alarmSeverity(alarmInfo.getSeverity())
.alarmStatus(alarmInfo.getStatus())
.alarmCustomerId(alarmInfo.getCustomerId())
.dashboardId(alarmInfo.getDashboardId())
.build();
}
@Override
public NotificationRuleTriggerType getTriggerType() {
return NotificationRuleTriggerType.ALARM_ASSIGNMENT;
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\notification\rule\trigger\AlarmAssignmentTriggerProcessor.java | 2 |
请完成以下Java代码 | public void setHR_ListBase_ID (int HR_ListBase_ID)
{
if (HR_ListBase_ID < 1)
set_Value (COLUMNNAME_HR_ListBase_ID, null);
else
set_Value (COLUMNNAME_HR_ListBase_ID, Integer.valueOf(HR_ListBase_ID));
}
/** Get Payroll List Base.
@return Payroll List Base */
public int getHR_ListBase_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListBase_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public org.eevolution.model.I_HR_List getHR_List() throws RuntimeException
{
return (org.eevolution.model.I_HR_List)MTable.get(getCtx(), org.eevolution.model.I_HR_List.Table_Name)
.getPO(getHR_List_ID(), get_TrxName()); }
/** Set Payroll List.
@param HR_List_ID Payroll List */
public void setHR_List_ID (int HR_List_ID)
{
if (HR_List_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_List_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_List_ID, Integer.valueOf(HR_List_ID));
}
/** Get Payroll List.
@return Payroll List */
public int getHR_List_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_List_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Payroll List Version.
@param HR_ListVersion_ID Payroll List Version */
public void setHR_ListVersion_ID (int HR_ListVersion_ID)
{
if (HR_ListVersion_ID < 1)
set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, null);
else
set_ValueNoCheck (COLUMNNAME_HR_ListVersion_ID, Integer.valueOf(HR_ListVersion_ID));
}
/** Get Payroll List Version.
@return Payroll List Version */
public int getHR_ListVersion_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_HR_ListVersion_ID);
if (ii == null)
return 0;
return ii.intValue();
} | /** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day)
*/
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_ListVersion.java | 1 |
请完成以下Java代码 | public class Customer extends RepresentationModel<Customer> {
private String customerId;
private String customerName;
private String companyName;
private Map<String, Order> orders;
public Customer() {
super();
}
public Customer(final String customerId, final String customerName, final String companyName) {
super();
this.customerId = customerId;
this.customerName = customerName;
this.companyName = companyName;
}
public String getCustomerId() {
return customerId;
}
public void setCustomerId(final String customerId) {
this.customerId = customerId;
}
public String getCustomerName() { | return customerName;
}
public void setCustomerName(final String customerName) {
this.customerName = customerName;
}
public String getCompanyName() {
return companyName;
}
public void setCompanyName(final String companyName) {
this.companyName = companyName;
}
public Map<String, Order> getOrders() {
return orders;
}
public void setOrders(final Map<String, Order> orders) {
this.orders = orders;
}
} | repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\persistence\model\Customer.java | 1 |
请完成以下Java代码 | public void setValue(Object value, VariableScope variableScope) {
setValue(value, variableScope, null);
}
public void setValue(Object value, VariableScope variableScope, BaseDelegateExecution contextExecution) {
ELContext elContext = expressionManager.getElContext(variableScope);
try {
ExpressionSetInvocation invocation = new ExpressionSetInvocation(valueExpression, elContext, value, contextExecution);
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(invocation);
} catch (Exception e) {
throw new ProcessEngineException("Error while evaluating expression: " + expressionText+". Cause: "+e.getMessage(), e);
}
} | @Override
public String toString() {
if(valueExpression != null) {
return valueExpression.getExpressionString();
}
return super.toString();
}
@Override
public boolean isLiteralText() {
return valueExpression.isLiteralText();
}
public String getExpressionText() {
return expressionText;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\el\JuelExpression.java | 1 |
请完成以下Java代码 | public JdbcCustomConversions jdbcCustomConversions() {
return new JdbcCustomConversions(asList(new Converter<Clob, String>() {
@Nullable
@Override
public String convert(Clob clob) {
try {
return Math.toIntExact(clob.length()) == 0 //
? "" //
: clob.getSubString(1, Math.toIntExact(clob.length()));
} catch (SQLException e) {
throw new IllegalStateException("Failed to convert CLOB to String.", e);
}
}
}));
}
@Bean
public NamedParameterJdbcTemplate namedParameterJdbcTemplate(JdbcOperations operations) {
return new NamedParameterJdbcTemplate(operations); | }
@Bean
DataSourceInitializer initializer(DataSource dataSource) {
var initializer = new DataSourceInitializer();
initializer.setDataSource(dataSource);
var script = new ClassPathResource("schema.sql");
var populator = new ResourceDatabasePopulator(script);
initializer.setDatabasePopulator(populator);
return initializer;
}
} | repos\spring-data-examples-main\jdbc\basics\src\main\java\example\springdata\jdbc\basics\aggregate\AggregateConfiguration.java | 1 |
请完成以下Java代码 | public class MSchedulerLog extends X_AD_SchedulerLog
implements AdempiereProcessorLog
{
/**
*
*/
private static final long serialVersionUID = -8105976307507562851L;
/**
* Standard Constructor
* @param ctx context
* @param AD_SchedulerLog_ID id
* @param trxName transaction
*/
public MSchedulerLog (Properties ctx, int AD_SchedulerLog_ID, String trxName)
{
super (ctx, AD_SchedulerLog_ID, trxName);
if (AD_SchedulerLog_ID == 0)
setIsError(false);
} // MSchedulerLog
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MSchedulerLog (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MSchedulerLog | /**
* Parent Constructor
* @param parent parent
* @param summary summary
*/
public MSchedulerLog (MScheduler parent, String summary)
{
this (parent.getCtx(), 0, parent.get_TrxName());
setClientOrg(parent);
setAD_Scheduler_ID(parent.getAD_Scheduler_ID());
setSummary(summary);
} // MSchedulerLog
} // MSchedulerLog | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MSchedulerLog.java | 1 |
请完成以下Java代码 | public String postStatusUpdate(String message) {
try {
FacebookType response = facebookClient.publish("me/feed", FacebookType.class, Parameter.with("message", message));
return "Post ID: " + response.getId();
} catch (Exception e) {
logger.log(Level.SEVERE,"Failed to post status: " + e.getMessage());
return null;
}
}
public void uploadPhotoToFeed() {
try (InputStream imageStream = getClass().getResourceAsStream("/static/image.jpg")) {
FacebookType response = facebookClient.publish("me/photos", FacebookType.class, BinaryAttachment.with("image.jpg", imageStream),
Parameter.with("message", "Uploaded with RestFB"));
logger.log(Level.INFO,"Photo uploaded. ID: " + response.getId());
} catch (IOException e) {
logger.log(Level.SEVERE,"Failed to read image file: " + e.getMessage());
}
} | public String postToPage(String pageId, String message) {
try {
Page page = facebookClient.fetchObject(pageId, Page.class, Parameter.with("fields", "access_token"));
FacebookClient pageClient = new DefaultFacebookClient(page.getAccessToken(), appSecret, Version.LATEST);
FacebookType response = pageClient.publish(pageId + "/feed", FacebookType.class, Parameter.with("message", message));
return "Page Post ID: " + response.getId();
} catch (Exception e) {
logger.log(Level.SEVERE,"Failed to post to page: " + e.getMessage());
return null;
}
}
} | repos\tutorials-master\libraries-http-3\src\main\java\com\baeldung\facebook\FacebookService.java | 1 |
请完成以下Java代码 | public void setServiceDate (Timestamp ServiceDate)
{
set_Value (COLUMNNAME_ServiceDate, ServiceDate);
}
/** Get Service date.
@return Date service was provided
*/
public Timestamp getServiceDate ()
{
return (Timestamp)get_Value(COLUMNNAME_ServiceDate);
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
/** Set Valid from.
@param ValidFrom
Valid from including this date (first day)
*/
public void setValidFrom (Timestamp ValidFrom)
{
set_Value (COLUMNNAME_ValidFrom, ValidFrom);
}
/** Get Valid from.
@return Valid from including this date (first day) | */
public Timestamp getValidFrom ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidFrom);
}
/** Set Valid to.
@param ValidTo
Valid to including this date (last day)
*/
public void setValidTo (Timestamp ValidTo)
{
set_Value (COLUMNNAME_ValidTo, ValidTo);
}
/** Get Valid to.
@return Valid to including this date (last day)
*/
public Timestamp getValidTo ()
{
return (Timestamp)get_Value(COLUMNNAME_ValidTo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Attribute.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public static SettModeTypeEnum getEnum(String enumName) {
SettModeTypeEnum resultEnum = null;
SettModeTypeEnum[] enumAry = SettModeTypeEnum.values();
for (int i = 0; i < enumAry.length; i++) {
if (enumAry[i].name().equals(enumName)) {
resultEnum = enumAry[i];
break;
}
}
return resultEnum;
}
public static Map<String, Map<String, Object>> toMap() {
SettModeTypeEnum[] ary = SettModeTypeEnum.values();
Map<String, Map<String, Object>> enumMap = new HashMap<String, Map<String, Object>>();
for (int num = 0; num < ary.length; num++) {
Map<String, Object> map = new HashMap<String, Object>();
String key = ary[num].name();
map.put("desc", ary[num].getDesc());
enumMap.put(key, map); | }
return enumMap;
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public static List toList() {
SettModeTypeEnum[] ary = SettModeTypeEnum.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());
list.add(map);
}
return list;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\enums\SettModeTypeEnum.java | 2 |
请完成以下Java代码 | public class X_M_DiscountSchema_Calculated_Surcharge extends org.compiere.model.PO implements I_M_DiscountSchema_Calculated_Surcharge, org.compiere.model.I_Persistent
{
private static final long serialVersionUID = -1307637385L;
/** Standard Constructor */
public X_M_DiscountSchema_Calculated_Surcharge (final Properties ctx, final int M_DiscountSchema_Calculated_Surcharge_ID, @Nullable final String trxName)
{
super (ctx, M_DiscountSchema_Calculated_Surcharge_ID, trxName);
}
/** Load Constructor */
public X_M_DiscountSchema_Calculated_Surcharge (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 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代码 | private void update(byte[] block, int offset) {
for (int i = 0; i < 16; i++) {
this.tmp[i] = (block[offset++] & 0xFF) | (block[offset++] & 0xFF) << 8 | (block[offset++] & 0xFF) << 16
| (block[offset++] & 0xFF) << 24;
}
int A = this.state[0];
int B = this.state[1];
int C = this.state[2];
int D = this.state[3];
A = FF(A, B, C, D, this.tmp[0], 3);
D = FF(D, A, B, C, this.tmp[1], 7);
C = FF(C, D, A, B, this.tmp[2], 11);
B = FF(B, C, D, A, this.tmp[3], 19);
A = FF(A, B, C, D, this.tmp[4], 3);
D = FF(D, A, B, C, this.tmp[5], 7);
C = FF(C, D, A, B, this.tmp[6], 11);
B = FF(B, C, D, A, this.tmp[7], 19);
A = FF(A, B, C, D, this.tmp[8], 3);
D = FF(D, A, B, C, this.tmp[9], 7);
C = FF(C, D, A, B, this.tmp[10], 11);
B = FF(B, C, D, A, this.tmp[11], 19);
A = FF(A, B, C, D, this.tmp[12], 3);
D = FF(D, A, B, C, this.tmp[13], 7);
C = FF(C, D, A, B, this.tmp[14], 11);
B = FF(B, C, D, A, this.tmp[15], 19);
A = GG(A, B, C, D, this.tmp[0], 3);
D = GG(D, A, B, C, this.tmp[4], 5);
C = GG(C, D, A, B, this.tmp[8], 9);
B = GG(B, C, D, A, this.tmp[12], 13);
A = GG(A, B, C, D, this.tmp[1], 3);
D = GG(D, A, B, C, this.tmp[5], 5);
C = GG(C, D, A, B, this.tmp[9], 9);
B = GG(B, C, D, A, this.tmp[13], 13);
A = GG(A, B, C, D, this.tmp[2], 3);
D = GG(D, A, B, C, this.tmp[6], 5);
C = GG(C, D, A, B, this.tmp[10], 9);
B = GG(B, C, D, A, this.tmp[14], 13);
A = GG(A, B, C, D, this.tmp[3], 3);
D = GG(D, A, B, C, this.tmp[7], 5);
C = GG(C, D, A, B, this.tmp[11], 9);
B = GG(B, C, D, A, this.tmp[15], 13); | A = HH(A, B, C, D, this.tmp[0], 3);
D = HH(D, A, B, C, this.tmp[8], 9);
C = HH(C, D, A, B, this.tmp[4], 11);
B = HH(B, C, D, A, this.tmp[12], 15);
A = HH(A, B, C, D, this.tmp[2], 3);
D = HH(D, A, B, C, this.tmp[10], 9);
C = HH(C, D, A, B, this.tmp[6], 11);
B = HH(B, C, D, A, this.tmp[14], 15);
A = HH(A, B, C, D, this.tmp[1], 3);
D = HH(D, A, B, C, this.tmp[9], 9);
C = HH(C, D, A, B, this.tmp[5], 11);
B = HH(B, C, D, A, this.tmp[13], 15);
A = HH(A, B, C, D, this.tmp[3], 3);
D = HH(D, A, B, C, this.tmp[11], 9);
C = HH(C, D, A, B, this.tmp[7], 11);
B = HH(B, C, D, A, this.tmp[15], 15);
this.state[0] += A;
this.state[1] += B;
this.state[2] += C;
this.state[3] += D;
}
private int FF(int a, int b, int c, int d, int x, int s) {
int t = a + ((b & c) | (~b & d)) + x;
return t << s | t >>> (32 - s);
}
private int GG(int a, int b, int c, int d, int x, int s) {
int t = a + ((b & (c | d)) | (c & d)) + x + 0x5A827999;
return t << s | t >>> (32 - s);
}
private int HH(int a, int b, int c, int d, int x, int s) {
int t = a + (b ^ c ^ d) + x + 0x6ED9EBA1;
return t << s | t >>> (32 - s);
}
} | repos\spring-security-main\crypto\src\main\java\org\springframework\security\crypto\password\Md4.java | 1 |
请完成以下Java代码 | public void put(long hash, T instance) {
circle.put(hash, instance);
}
public void remove(long hash) {
circle.remove(hash);
}
public boolean isEmpty() {
return circle.isEmpty();
}
public boolean containsKey(Long hash) {
return circle.containsKey(hash);
} | public ConcurrentNavigableMap<Long, T> tailMap(Long hash) {
return circle.tailMap(hash);
}
public Long firstKey() {
return circle.firstKey();
}
public T get(Long hash) {
return circle.get(hash);
}
public void log() {
circle.forEach((key, value) -> log.debug("{} -> {}", key, value));
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\discovery\ConsistentHashCircle.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getAlbumId() {
return albumId;
}
public void setAlbumId(Long albumId) {
this.albumId = albumId;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic; | }
@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(", albumId=").append(albumId);
sb.append(", pic=").append(pic);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsAlbumPic.java | 1 |
请完成以下Java代码 | public boolean isWithoutTenantId() {
return withoutTenantId;
}
public void setWithoutTenantId(boolean withoutTenantId) {
this.withoutTenantId = withoutTenantId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
} | public boolean isResultEnabled() {
return resultEnabled;
}
public void setResultEnabled(boolean resultEnabled) {
this.resultEnabled = resultEnabled;
}
public boolean isVariablesInResultEnabled() {
return variablesInResultEnabled;
}
public void setVariablesInResultEnabled(boolean variablesInResultEnabled) {
this.variablesInResultEnabled = variablesInResultEnabled;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\message\CorrelationMessageDto.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public int hashCode() {
final int prime = 31; | int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj) return true;
if (obj == null) return false;
if (getClass() != obj.getClass()) return false;
EventSubscriptionEntityImpl other = (EventSubscriptionEntityImpl) obj;
if (id == null) {
if (other.id != null) return false;
} else if (!id.equals(other.id)) return false;
return true;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\EventSubscriptionEntityImpl.java | 1 |
请完成以下Java代码 | public org.compiere.model.I_AD_Color getInsufficientQtyAvailableForSalesColor()
{
return get_ValueAsPO(COLUMNNAME_InsufficientQtyAvailableForSalesColor_ID, org.compiere.model.I_AD_Color.class);
}
@Override
public void setInsufficientQtyAvailableForSalesColor(final org.compiere.model.I_AD_Color InsufficientQtyAvailableForSalesColor)
{
set_ValueFromPO(COLUMNNAME_InsufficientQtyAvailableForSalesColor_ID, org.compiere.model.I_AD_Color.class, InsufficientQtyAvailableForSalesColor);
}
@Override
public void setInsufficientQtyAvailableForSalesColor_ID (final int InsufficientQtyAvailableForSalesColor_ID)
{
if (InsufficientQtyAvailableForSalesColor_ID < 1)
set_Value (COLUMNNAME_InsufficientQtyAvailableForSalesColor_ID, null);
else
set_Value (COLUMNNAME_InsufficientQtyAvailableForSalesColor_ID, InsufficientQtyAvailableForSalesColor_ID);
}
@Override
public int getInsufficientQtyAvailableForSalesColor_ID()
{
return get_ValueAsInt(COLUMNNAME_InsufficientQtyAvailableForSalesColor_ID);
}
@Override
public void setIsAsync (final boolean IsAsync)
{
set_Value (COLUMNNAME_IsAsync, IsAsync);
}
@Override
public boolean isAsync()
{
return get_ValueAsBoolean(COLUMNNAME_IsAsync);
}
@Override
public void setIsFeatureActivated (final boolean IsFeatureActivated)
{
set_Value (COLUMNNAME_IsFeatureActivated, IsFeatureActivated);
}
@Override
public boolean isFeatureActivated()
{
return get_ValueAsBoolean(COLUMNNAME_IsFeatureActivated);
}
@Override
public void setIsQtyPerWarehouse (final boolean IsQtyPerWarehouse)
{
set_Value (COLUMNNAME_IsQtyPerWarehouse, IsQtyPerWarehouse);
} | @Override
public boolean isQtyPerWarehouse()
{
return get_ValueAsBoolean(COLUMNNAME_IsQtyPerWarehouse);
}
@Override
public void setMD_AvailableForSales_Config_ID (final int MD_AvailableForSales_Config_ID)
{
if (MD_AvailableForSales_Config_ID < 1)
set_ValueNoCheck (COLUMNNAME_MD_AvailableForSales_Config_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MD_AvailableForSales_Config_ID, MD_AvailableForSales_Config_ID);
}
@Override
public int getMD_AvailableForSales_Config_ID()
{
return get_ValueAsInt(COLUMNNAME_MD_AvailableForSales_Config_ID);
}
@Override
public void setSalesOrderLookBehindHours (final int SalesOrderLookBehindHours)
{
set_Value (COLUMNNAME_SalesOrderLookBehindHours, SalesOrderLookBehindHours);
}
@Override
public int getSalesOrderLookBehindHours()
{
return get_ValueAsInt(COLUMNNAME_SalesOrderLookBehindHours);
}
@Override
public void setShipmentDateLookAheadHours (final int ShipmentDateLookAheadHours)
{
set_Value (COLUMNNAME_ShipmentDateLookAheadHours, ShipmentDateLookAheadHours);
}
@Override
public int getShipmentDateLookAheadHours()
{
return get_ValueAsInt(COLUMNNAME_ShipmentDateLookAheadHours);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java-gen\de\metas\material\cockpit\model\X_MD_AvailableForSales_Config.java | 1 |
请完成以下Java代码 | public static OrderLineId cast(@NonNull final RepoIdAware id)
{
return (OrderLineId)id;
}
public static int toRepoId(@Nullable final OrderLineId orderLineId)
{
return orderLineId != null ? orderLineId.getRepoId() : -1;
}
public static Set<Integer> toIntSet(final Collection<OrderLineId> orderLineIds)
{
return orderLineIds.stream().map(OrderLineId::getRepoId).collect(ImmutableSet.toImmutableSet());
}
int repoId; | private OrderLineId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "repoId");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
public static boolean equals(@Nullable final OrderLineId id1, @Nullable final OrderLineId id2) {return Objects.equals(id1, id2);}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\OrderLineId.java | 1 |
请完成以下Java代码 | public List<ActivityInstanceEntity> findActivityInstancesByProcessInstanceId(String processInstanceId, boolean includeDeleted) {
List<ActivityInstanceEntity> activityInstances = getList(getDbSqlSession(), "selectActivityInstancesByProcessInstanceId", processInstanceId,
activitiesByProcessInstanceIdMatcher, true, includeDeleted);
activityInstances.sort(Comparator.comparing(ActivityInstanceEntity::getStartTime)
.thenComparing(ActivityInstanceEntity::getTransactionOrder, Comparator.nullsFirst(Comparator.naturalOrder())));
return activityInstances;
}
@Override
public ActivityInstanceEntity findActivityInstanceByTaskId(String taskId) {
return getEntity("selectActivityInstanceByTaskId", taskId, activityInstanceByTaskIdMatcher, true);
}
@Override
public void deleteActivityInstancesByProcessInstanceId(String processInstanceId) {
DbSqlSession dbSqlSession = getDbSqlSession();
deleteCachedEntities(dbSqlSession, activitiesByProcessInstanceIdMatcher, processInstanceId);
if (!isEntityInserted(dbSqlSession, "execution", processInstanceId)) {
dbSqlSession.delete("deleteActivityInstancesByProcessInstanceId", processInstanceId, ActivityInstanceEntityImpl.class);
}
}
@Override
public long findActivityInstanceCountByQueryCriteria(ActivityInstanceQueryImpl activityInstanceQuery) {
setSafeInValueLists(activityInstanceQuery);
return (Long) getDbSqlSession().selectOne("selectActivityInstanceCountByQueryCriteria", activityInstanceQuery);
}
@Override
@SuppressWarnings("unchecked")
public List<ActivityInstance> findActivityInstancesByQueryCriteria(ActivityInstanceQueryImpl activityInstanceQuery) {
setSafeInValueLists(activityInstanceQuery);
return getDbSqlSession().selectList("selectActivityInstancesByQueryCriteria", activityInstanceQuery);
}
@Override | @SuppressWarnings("unchecked")
public List<ActivityInstance> findActivityInstancesByNativeQuery(Map<String, Object> parameterMap) {
return getDbSqlSession().selectListWithRawParameter("selectActivityInstanceByNativeQuery", parameterMap);
}
@Override
public long findActivityInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectActivityInstanceCountByNativeQuery", parameterMap);
}
protected void setSafeInValueLists(ActivityInstanceQueryImpl activityInstanceQuery) {
if (activityInstanceQuery.getProcessInstanceIds() != null) {
activityInstanceQuery.setSafeProcessInstanceIds(createSafeInValuesList(activityInstanceQuery.getProcessInstanceIds()));
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\data\impl\MybatisActivityInstanceDataManager.java | 1 |
请完成以下Java代码 | private static boolean isEnabled() {
if (enabled == Enabled.DETECT) {
if (ansiCapable == null) {
ansiCapable = detectIfAnsiCapable();
}
return ansiCapable;
}
return enabled == Enabled.ALWAYS;
}
private static boolean detectIfAnsiCapable() {
try {
if (Boolean.FALSE.equals(consoleAvailable)) {
return false;
}
if (consoleAvailable == null) {
Console console = System.console();
if (console == null) {
return false;
}
Method isTerminalMethod = ClassUtils.getMethodIfAvailable(Console.class, "isTerminal");
if (isTerminalMethod != null) {
Boolean isTerminal = (Boolean) isTerminalMethod.invoke(console);
if (Boolean.FALSE.equals(isTerminal)) {
return false;
}
}
}
return !(OPERATING_SYSTEM_NAME.contains("win"));
}
catch (Throwable ex) {
return false;
}
} | /**
* Possible values to pass to {@link AnsiOutput#setEnabled}. Determines when to output
* ANSI escape sequences for coloring application output.
*/
public enum Enabled {
/**
* Try to detect whether ANSI coloring capabilities are available. The default
* value for {@link AnsiOutput}.
*/
DETECT,
/**
* Enable ANSI-colored output.
*/
ALWAYS,
/**
* Disable ANSI-colored output.
*/
NEVER
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ansi\AnsiOutput.java | 1 |
请完成以下Java代码 | protected void queueVariableEvent(VariableEvent variableEvent, boolean includeCustomerListeners) {
Queue<VariableEvent> variableEventsQueue = getVariableEventQueue();
variableEventsQueue.add(variableEvent);
// if this is the first event added, trigger listener invocation
if (variableEventsQueue.size() == 1) {
invokeVariableListeners(includeCustomerListeners);
}
}
protected void invokeVariableListeners(boolean includeCustomerListeners) {
Queue<VariableEvent> variableEventsQueue = getVariableEventQueue();
while (!variableEventsQueue.isEmpty()) {
// do not remove the event yet, as otherwise new events will immediately be dispatched
VariableEvent nextEvent = variableEventsQueue.peek();
CmmnExecution sourceExecution = (CmmnExecution) nextEvent.getSourceScope();
DelegateCaseVariableInstanceImpl delegateVariable =
DelegateCaseVariableInstanceImpl.fromVariableInstance(nextEvent.getVariableInstance());
delegateVariable.setEventName(nextEvent.getEventName());
delegateVariable.setSourceExecution(sourceExecution);
Map<String, List<VariableListener<?>>> listenersByActivity =
sourceExecution.getActivity().getVariableListeners(delegateVariable.getEventName(), includeCustomerListeners);
CmmnExecution currentExecution = sourceExecution;
while (currentExecution != null) {
if (currentExecution.getActivityId() != null) {
List<VariableListener<?>> listeners = listenersByActivity.get(currentExecution.getActivityId());
if (listeners != null) {
delegateVariable.setScopeExecution(currentExecution);
for (VariableListener<?> listener : listeners) {
try {
CaseVariableListener caseVariableListener = (CaseVariableListener) listener;
CaseVariableListenerInvocation invocation = new CaseVariableListenerInvocation(caseVariableListener, delegateVariable, currentExecution);
Context.getProcessEngineConfiguration()
.getDelegateInterceptor()
.handleInvocation(invocation);
} catch (Exception e) {
throw LOG.invokeVariableListenerException(e);
} | }
}
}
currentExecution = currentExecution.getParent();
}
// finally remove the event from the queue
variableEventsQueue.remove();
}
}
protected Queue<VariableEvent> getVariableEventQueue() {
if (variableEventsQueue == null) {
variableEventsQueue = new LinkedList<VariableEvent>();
}
return variableEventsQueue;
}
// toString() ////////////////////////////////////// ///////////
public String toString() {
if (isCaseInstanceExecution()) {
return "CaseInstance["+getToStringIdentity()+"]";
} else {
return "CmmnExecution["+getToStringIdentity() + "]";
}
}
protected String getToStringIdentity() {
return id;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\execution\CmmnExecution.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class S3ResponseReader implements FileReader {
private final S3Client s3Client;
public S3ResponseReader(S3Client s3Client) {
this.s3Client = s3Client;
}
@Override
public FileData readResponse(S3ObjectRequest s3ObjectRequest) throws IOException {
GetObjectRequest getObjectRequest = GetObjectRequest.builder()
.bucket(s3ObjectRequest.getBucketName())
.key(s3ObjectRequest.getObjectKey())
.build();
try (ResponseInputStream<GetObjectResponse> responseInputStream = s3Client.getObject(getObjectRequest)) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); | byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = responseInputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
byte[] fileContent = outputStream.toByteArray();
String contentType = responseInputStream.response()
.contentType();
String contentDisposition = responseInputStream.response()
.contentDisposition();
return new FileData(fileContent, contentType, contentDisposition, getObjectRequest);
}
}
} | repos\tutorials-master\aws-modules\aws-rest\src\main\java\com\baeldung\aws\rest\s3\download\dto\S3ResponseReader.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private CachingProvider getCachingProvider(@Nullable String cachingProviderFqn) {
if (StringUtils.hasText(cachingProviderFqn)) {
return Caching.getCachingProvider(cachingProviderFqn);
}
return Caching.getCachingProvider();
}
private Properties createCacheManagerProperties(
ObjectProvider<JCachePropertiesCustomizer> cachePropertiesCustomizers) {
Properties properties = new Properties();
cachePropertiesCustomizers.orderedStream().forEach((customizer) -> customizer.customize(properties));
return properties;
}
/**
* Determine if JCache is available. This either kicks in if a provider is available
* as defined per {@link JCacheProviderAvailableCondition} or if a
* {@link CacheManager} has already been defined.
*/
@Order(Ordered.LOWEST_PRECEDENCE)
static class JCacheAvailableCondition extends AnyNestedCondition {
JCacheAvailableCondition() {
super(ConfigurationPhase.REGISTER_BEAN);
}
@Conditional(JCacheProviderAvailableCondition.class)
static class JCacheProvider {
}
@ConditionalOnSingleCandidate(CacheManager.class)
static class CustomJCacheCacheManager {
} | }
/**
* Determine if a JCache provider is available. This either kicks in if a default
* {@link CachingProvider} has been found or if the property referring to the provider
* to use has been set.
*/
@Order(Ordered.LOWEST_PRECEDENCE)
static class JCacheProviderAvailableCondition extends SpringBootCondition {
@Override
public ConditionOutcome getMatchOutcome(ConditionContext context, AnnotatedTypeMetadata metadata) {
ConditionMessage.Builder message = ConditionMessage.forCondition("JCache");
String providerProperty = "spring.cache.jcache.provider";
if (context.getEnvironment().containsProperty(providerProperty)) {
return ConditionOutcome.match(message.because("JCache provider specified"));
}
Iterator<CachingProvider> providers = Caching.getCachingProviders().iterator();
if (!providers.hasNext()) {
return ConditionOutcome.noMatch(message.didNotFind("JSR-107 provider").atAll());
}
providers.next();
if (providers.hasNext()) {
return ConditionOutcome.noMatch(message.foundExactly("multiple JSR-107 providers"));
}
return ConditionOutcome.match(message.foundExactly("single JSR-107 provider"));
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\JCacheCacheConfiguration.java | 2 |
请完成以下Java代码 | public void setSurname(String surname) {
this.surname = surname;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age; | }
@Override
public boolean equals(Object o) {
if (this == o)
return true;
if (o == null || getClass() != o.getClass())
return false;
User book = (User) o;
return Objects.equals(id, book.id);
}
@Override
public int hashCode() {
return Objects.hash(id);
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb\src\main\java\com\baeldung\multipledb\model\User.java | 1 |
请完成以下Java代码 | public void setIsRequiredLocation (boolean IsRequiredLocation)
{
set_Value (COLUMNNAME_IsRequiredLocation, Boolean.valueOf(IsRequiredLocation));
}
/** Get Requires Location.
@return Requires Location */
@Override
public boolean isRequiredLocation ()
{
Object oo = get_Value(COLUMNNAME_IsRequiredLocation);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Requires Mail Address.
@param IsRequiredMailAddres Requires Mail Address */
@Override
public void setIsRequiredMailAddres (boolean IsRequiredMailAddres)
{
set_Value (COLUMNNAME_IsRequiredMailAddres, Boolean.valueOf(IsRequiredMailAddres));
}
/** Get Requires Mail Address.
@return Requires Mail Address */
@Override
public boolean isRequiredMailAddres ()
{
Object oo = get_Value(COLUMNNAME_IsRequiredMailAddres);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/**
* MarketingPlatformGatewayId AD_Reference_ID=540858
* Reference name: MarketingPlatformGatewayId
*/
public static final int MARKETINGPLATFORMGATEWAYID_AD_Reference_ID=540858;
/** CleverReach = CleverReach */
public static final String MARKETINGPLATFORMGATEWAYID_CleverReach = "CleverReach";
/** Set Marketing Platform GatewayId.
@param MarketingPlatformGatewayId Marketing Platform GatewayId */
@Override
public void setMarketingPlatformGatewayId (java.lang.String MarketingPlatformGatewayId) | {
set_Value (COLUMNNAME_MarketingPlatformGatewayId, MarketingPlatformGatewayId);
}
/** Get Marketing Platform GatewayId.
@return Marketing Platform GatewayId */
@Override
public java.lang.String getMarketingPlatformGatewayId ()
{
return (java.lang.String)get_Value(COLUMNNAME_MarketingPlatformGatewayId);
}
/** Set MKTG_Platform.
@param MKTG_Platform_ID MKTG_Platform */
@Override
public void setMKTG_Platform_ID (int MKTG_Platform_ID)
{
if (MKTG_Platform_ID < 1)
set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MKTG_Platform_ID, Integer.valueOf(MKTG_Platform_ID));
}
/** Get MKTG_Platform.
@return MKTG_Platform */
@Override
public int getMKTG_Platform_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MKTG_Platform_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
@Override
public void setName (java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
@Override
public java.lang.String getName ()
{
return (java.lang.String)get_Value(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Platform.java | 1 |
请完成以下Java代码 | public class CommonResult<T> {
/**
* 状态码
*/
private long code;
/**
* 提示信息
*/
private String message;
/**
* 数据封装
*/
private T data;
protected CommonResult() {
}
protected CommonResult(long code, String message, T data) {
this.code = code;
this.message = message;
this.data = data;
}
/**
* 成功返回结果
*
* @param data 获取的数据
*/
public static <T> CommonResult<T> success(T data) {
return new CommonResult<T>(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
}
/**
* 成功返回结果
*
* @param data 获取的数据
* @param message 提示信息
*/
public static <T> CommonResult<T> success(T data, String message) {
return new CommonResult<T>(ResultCode.SUCCESS.getCode(), message, data);
}
/**
* 失败返回结果
* @param errorCode 错误码
*/
public static <T> CommonResult<T> failed(IErrorCode errorCode) {
return new CommonResult<T>(errorCode.getCode(), errorCode.getMessage(), null);
}
/**
* 失败返回结果
* @param errorCode 错误码
* @param message 错误信息
*/
public static <T> CommonResult<T> failed(IErrorCode errorCode,String message) {
return new CommonResult<T>(errorCode.getCode(), message, null);
}
/**
* 失败返回结果
* @param message 提示信息
*/
public static <T> CommonResult<T> failed(String message) {
return new CommonResult<T>(ResultCode.FAILED.getCode(), message, null);
}
/** | * 失败返回结果
*/
public static <T> CommonResult<T> failed() {
return failed(ResultCode.FAILED);
}
/**
* 参数验证失败返回结果
*/
public static <T> CommonResult<T> validateFailed() {
return failed(ResultCode.VALIDATE_FAILED);
}
/**
* 参数验证失败返回结果
* @param message 提示信息
*/
public static <T> CommonResult<T> validateFailed(String message) {
return new CommonResult<T>(ResultCode.VALIDATE_FAILED.getCode(), message, null);
}
/**
* 未登录返回结果
*/
public static <T> CommonResult<T> unauthorized(T data) {
return new CommonResult<T>(ResultCode.UNAUTHORIZED.getCode(), ResultCode.UNAUTHORIZED.getMessage(), data);
}
/**
* 未授权返回结果
*/
public static <T> CommonResult<T> forbidden(T data) {
return new CommonResult<T>(ResultCode.FORBIDDEN.getCode(), ResultCode.FORBIDDEN.getMessage(), data);
}
public long getCode() {
return code;
}
public void setCode(long code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
} | repos\mall-master\mall-common\src\main\java\com\macro\mall\common\api\CommonResult.java | 1 |
请完成以下Java代码 | public boolean hasFailures() {
return !failures.isEmpty() || !activityInstanceReports.isEmpty() || !transitionInstanceReports.isEmpty();
}
public void writeTo(StringBuilder sb) {
sb.append("Cannot migrate process instance '")
.append(processInstanceId)
.append("':\n");
for (String failure : failures) {
sb.append("\t").append(failure).append("\n");
}
for (MigratingActivityInstanceValidationReport report : activityInstanceReports) {
sb.append("\tCannot migrate activity instance '")
.append(report.getActivityInstanceId())
.append("':\n"); | for (String failure : report.getFailures()) {
sb.append("\t\t").append(failure).append("\n");
}
}
for (MigratingTransitionInstanceValidationReport report : transitionInstanceReports) {
sb.append("\tCannot migrate transition instance '")
.append(report.getTransitionInstanceId())
.append("':\n");
for (String failure : report.getFailures()) {
sb.append("\t\t").append(failure).append("\n");
}
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\validation\instance\MigratingProcessInstanceValidationReportImpl.java | 1 |
请完成以下Java代码 | public class ProcessDefinitionStatisticsEntity extends ProcessDefinitionEntity implements ProcessDefinitionStatistics {
protected static final long serialVersionUID = 1L;
protected int instances;
protected int failedJobs;
protected List<IncidentStatistics> incidentStatistics;
public int getInstances() {
return instances;
}
public void setInstances(int instances) {
this.instances = instances;
}
public int getFailedJobs() {
return failedJobs;
}
public void setFailedJobs(int failedJobs) {
this.failedJobs = failedJobs;
}
public List<IncidentStatistics> getIncidentStatistics() {
return incidentStatistics;
}
public void setIncidentStatistics(List<IncidentStatistics> incidentStatistics) {
this.incidentStatistics = incidentStatistics;
} | @Override
public String toString() {
return this.getClass().getSimpleName()
+ "[instances=" + instances
+ ", failedJobs=" + failedJobs
+ ", id=" + id
+ ", deploymentId=" + deploymentId
+ ", description=" + description
+ ", historyLevel=" + historyLevel
+ ", category=" + category
+ ", hasStartFormKey=" + hasStartFormKey
+ ", diagramResourceName=" + diagramResourceName
+ ", key=" + key
+ ", name=" + name
+ ", resourceName=" + resourceName
+ ", revision=" + revision
+ ", version=" + version
+ ", suspensionState=" + suspensionState
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\ProcessDefinitionStatisticsEntity.java | 1 |
请完成以下Java代码 | public static MessagePropertiesBuilder fromProperties(MessageProperties properties) {
return new MessagePropertiesBuilder(properties);
}
/**
* Performs a shallow copy of the properties for the initial value.
* @param properties The properties.
* @return The builder.
*/
public static MessagePropertiesBuilder fromClonedProperties(MessageProperties properties) {
MessagePropertiesBuilder builder = newInstance();
return builder.copyProperties(properties);
}
private MessagePropertiesBuilder() {
} | private MessagePropertiesBuilder(MessageProperties properties) {
super(properties);
}
@Override
public MessagePropertiesBuilder copyProperties(MessageProperties properties) {
super.copyProperties(properties);
return this;
}
@Override
public MessageProperties build() {
return this.buildProperties();
}
} | repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\MessagePropertiesBuilder.java | 1 |
请完成以下Java代码 | protected void copyVariablesToBodyAsMap(Map<String, Object> variables, Exchange exchange) {
exchange.getIn().setBody(new HashMap<>(variables));
}
protected void copyVariablesToBody(Map<String, Object> variables, Exchange exchange) {
Object camelBody = variables.get(ExchangeUtils.CAMELBODY);
if (camelBody != null) {
exchange.getIn().setBody(camelBody);
}
}
protected String getProcessDefinitionKey(DelegateExecution execution, boolean isV5Execution) {
Process process = null;
if (isV5Execution) {
process = Flowable5CompatibilityContext.getFallbackFlowable5CompatibilityHandler().getProcessDefinitionProcessObject(execution.getProcessDefinitionId());
} else {
process = ProcessDefinitionUtil.getProcess(execution.getProcessDefinitionId());
}
return process.getId();
}
protected boolean isASync(DelegateExecution execution) {
boolean async = false;
if (execution.getCurrentFlowElement() instanceof Activity) {
async = ((Activity) execution.getCurrentFlowElement()).isAsynchronous();
}
return async; | }
protected String getStringFromField(Expression expression, DelegateExecution execution) {
if (expression != null) {
Object value = expression.getValue(execution);
if (value != null) {
return value.toString();
}
}
return null;
}
public void setCamelContext(Expression camelContext) {
this.camelContext = camelContext;
}
} | repos\flowable-engine-main\modules\flowable-camel\src\main\java\org\flowable\camel\CamelBehavior.java | 1 |
请在Spring Boot框架中完成以下Java代码 | CalculationWebClient calculationWebClient(WebClient webClient) {
WebClientAdapter adapter = WebClientAdapter.create(webClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
return factory.createClient(CalculationWebClient.class);
}
//--- Routing with WebFilter --- START ---
@Bean
public SimpleRoutingFilter simpleRoutingFilter() {
LOGGER.info("Bean 'simpleRoutingFilter' created");
return new SimpleRoutingFilter();
}
//--- Routing with WebFilter --- END ---
//--- Routing with RouterFunction --- START ---
@Bean
public RouterFunction<ServerResponse> routingSample1(ServiceController serviceController) {
LOGGER.info("Bean 'routingSample1' created");
return route() | .GET("sleep2", request -> callSleepBasedOnHeaderValue(serviceController, request.headers().header("mode")))
.build();
}
static Mono<ServerResponse> callSleepBasedOnHeaderValue(ServiceController serviceController, List<String> modeHeaderValue) {
final int value = extractSleepValue(modeHeaderValue);
LOGGER.info("ROUTING from /sleep2 to /sleep/{}", value);
return serviceController.sleep(value).flatMap(result -> ServerResponse.ok().body(result, Integer.class));
}
static int extractSleepValue(List<String> modeHeaderValue) {
return !modeHeaderValue.isEmpty() && modeHeaderValue.getFirst().equals("short") ? 1000 : 10000;
}
//--- Routing with RouterFunction --- END ---
} | repos\spring-boot3-demo-master\src\main\java\com\giraone\sb3\demo\config\WebClientConfig.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public LocalDate getPublished() {
return published;
}
public void setPublished(LocalDate published) {
this.published = published;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
} | @Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BookDTO bookDTO = (BookDTO) o;
if (bookDTO.getId() == null || getId() == null) {
return false;
}
return Objects.equals(getId(), bookDTO.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "BookDTO{" +
"id=" + getId() +
", title='" + getTitle() + "'" +
", author='" + getAuthor() + "'" +
", published='" + getPublished() + "'" +
", quantity=" + getQuantity() +
", price=" + getPrice() +
"}";
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\BookDTO.java | 2 |
请完成以下Java代码 | public class TbLwM2mStoreFactory {
private final Optional<TBRedisCacheConfiguration> redisConfiguration;
private final LwM2MTransportServerConfig config;
private final LwM2mCredentialsSecurityInfoValidator validator;
private final LwM2mVersionedModelProvider modelProvider;
@Bean
private RegistrationStore registrationStore() {
return redisConfiguration.isPresent() ?
new TbLwM2mRedisRegistrationStore(config, getConnectionFactory(), modelProvider) :
new TbInMemoryRegistrationStore(config, config.getCleanPeriodInSec(), modelProvider);
}
@Bean
private TbMainSecurityStore securityStore() {
return new TbLwM2mSecurityStore(redisConfiguration.isPresent() ?
new TbLwM2mRedisSecurityStore(getConnectionFactory()) : new TbInMemorySecurityStore(), validator);
}
@Bean
private TbLwM2MClientStore clientStore() {
return redisConfiguration.isPresent() ? new TbRedisLwM2MClientStore(getConnectionFactory()) : new TbDummyLwM2MClientStore();
}
@Bean
private TbLwM2MModelConfigStore modelConfigStore() {
return redisConfiguration.isPresent() ? new TbRedisLwM2MModelConfigStore(getConnectionFactory()) : new TbDummyLwM2MModelConfigStore(); | }
@Bean
private TbLwM2MClientOtaInfoStore otaStore() {
return redisConfiguration.isPresent() ? new TbLwM2mRedisClientOtaInfoStore(getConnectionFactory()) : new TbDummyLwM2MClientOtaInfoStore();
}
@Bean
private TbLwM2MDtlsSessionStore sessionStore() {
return redisConfiguration.isPresent() ? new TbLwM2MDtlsSessionRedisStore(getConnectionFactory()) : new TbL2M2MDtlsSessionInMemoryStore();
}
private RedisConnectionFactory getConnectionFactory() {
return redisConfiguration.get().redisConnectionFactory();
}
} | repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbLwM2mStoreFactory.java | 1 |
请完成以下Java代码 | protected int[] extractFeature(String sentence, FeatureMap featureMap, int position)
{
StringBuilder sbFeature = new StringBuilder();
List<Integer> featureVec = new LinkedList<Integer>();
for (int i = 0; i < featureTemplateArray.length; i++)
{
Iterator<int[]> offsetIterator = featureTemplateArray[i].offsetList.iterator();
Iterator<String> delimiterIterator = featureTemplateArray[i].delimiterList.iterator();
delimiterIterator.next(); // ignore U0 之类的id
while (offsetIterator.hasNext())
{
int offset = offsetIterator.next()[0] + position;
if (offset < 0)
sbFeature.append(FeatureIndex.BOS[-(offset + 1)]);
else if (offset >= sentence.length())
sbFeature.append(FeatureIndex.EOS[offset - sentence.length()]);
else
sbFeature.append(sentence.charAt(offset));
if (delimiterIterator.hasNext())
sbFeature.append(delimiterIterator.next());
else
sbFeature.append(i);
}
addFeatureThenClear(sbFeature, featureVec, featureMap);
}
return toFeatureArray(featureVec);
}
};
} | @Override
protected String getDefaultFeatureTemplate()
{
return "# Unigram\n" +
"U0:%x[-1,0]\n" +
"U1:%x[0,0]\n" +
"U2:%x[1,0]\n" +
"U3:%x[-2,0]%x[-1,0]\n" +
"U4:%x[-1,0]%x[0,0]\n" +
"U5:%x[0,0]%x[1,0]\n" +
"U6:%x[1,0]%x[2,0]\n" +
"\n" +
"# Bigram\n" +
"B";
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\CRFSegmenter.java | 1 |
请完成以下Java代码 | public class SimpleAsymmetricConfig {
private String privateKey = null;
private String publicKey = null;
private String privateKeyLocation = null;
private String publicKeyLocation = null;
private Resource privateKeyResource = null;
private Resource publicKeyResource = null;
private ResourceLoader resourceLoader = new DefaultResourceLoader();
private KeyFormat privateKeyFormat = KeyFormat.DER;
private KeyFormat publicKeyFormat = KeyFormat.DER;
private Resource loadResource(Resource asResource, String asString, String asLocation, KeyFormat format, String type) {
return Optional.ofNullable(asResource)
.orElseGet(() ->
Optional.ofNullable(asString)
.map(pk -> (Resource) new ByteArrayResource(format == KeyFormat.DER ? Base64.getDecoder().decode(pk) : pk.getBytes(StandardCharsets.UTF_8)))
.orElseGet(() ->
Optional.ofNullable(asLocation)
.map(resourceLoader::getResource)
.orElseThrow(() -> new IllegalArgumentException("Unable to load " + type + " key. Either resource, key as string, or resource location must be provided"))));
}
/**
* <p>loadPrivateKeyResource.</p>
*
* @return a {@link org.springframework.core.io.Resource} object
*/ | public Resource loadPrivateKeyResource() {
return loadResource(privateKeyResource, privateKey, privateKeyLocation, privateKeyFormat, "Private");
}
/**
* <p>loadPublicKeyResource.</p>
*
* @return a {@link org.springframework.core.io.Resource} object
*/
public Resource loadPublicKeyResource() {
return loadResource(publicKeyResource, publicKey, publicKeyLocation, publicKeyFormat, "Public");
}
/**
* <p>setKeyFormat.</p>
*
* @param keyFormat a {@link com.ulisesbocchio.jasyptspringboot.util.AsymmetricCryptography.KeyFormat} object
*/
public void setKeyFormat(KeyFormat keyFormat) {
setPublicKeyFormat(keyFormat);
setPrivateKeyFormat(keyFormat);
}
} | repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\encryptor\SimpleAsymmetricConfig.java | 1 |
请完成以下Java代码 | protected void executeExecutionListeners(
HasExecutionListeners elementWithExecutionListeners,
ExecutionEntity executionEntity,
String eventType
) {
commandContext
.getProcessEngineConfiguration()
.getListenerNotificationHelper()
.executeExecutionListeners(elementWithExecutionListeners, executionEntity, eventType);
}
/**
* Returns the first parent execution of the provided execution that is a scope.
*/
protected ExecutionEntity findFirstParentScopeExecution(ExecutionEntity executionEntity) {
ExecutionEntityManager executionEntityManager = commandContext.getExecutionEntityManager();
ExecutionEntity parentScopeExecution = null;
ExecutionEntity currentlyExaminedExecution = executionEntityManager.findById(executionEntity.getParentId());
while (currentlyExaminedExecution != null && parentScopeExecution == null) {
if (currentlyExaminedExecution.isScope()) {
parentScopeExecution = currentlyExaminedExecution;
} else {
currentlyExaminedExecution = executionEntityManager.findById(currentlyExaminedExecution.getParentId());
}
}
return parentScopeExecution;
}
public CommandContext getCommandContext() {
return commandContext;
} | public void setCommandContext(CommandContext commandContext) {
this.commandContext = commandContext;
}
public Agenda getAgenda() {
return agenda;
}
public void setAgenda(DefaultActivitiEngineAgenda agenda) {
this.agenda = agenda;
}
public ExecutionEntity getExecution() {
return execution;
}
public void setExecution(ExecutionEntity execution) {
this.execution = execution;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\agenda\AbstractOperation.java | 1 |
请完成以下Java代码 | public static List<AuthorizationDto> fromAuthorizationList(List<Authorization> resultList, ProcessEngineConfiguration engineConfiguration) {
ArrayList<AuthorizationDto> result = new ArrayList<AuthorizationDto>();
for (Authorization authorization : resultList) {
result.add(fromAuthorization(authorization, engineConfiguration));
}
return result;
}
//////////////////////////////////////////////////////
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public int getType() {
return type;
}
public void setType(int type) {
this.type = type;
}
public String[] getPermissions() {
return permissions;
}
public void setPermissions(String[] permissions) {
this.permissions = permissions;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getGroupId() {
return groupId;
} | public void setGroupId(String groupId) {
this.groupId = groupId;
}
public Integer getResourceType() {
return resourceType;
}
public void setResourceType(Integer resourceType) {
this.resourceType = resourceType;
}
public String getResourceId() {
return resourceId;
}
public void setResourceId(String resourceId) {
this.resourceId = resourceId;
}
public String getRootProcessInstanceId() {
return rootProcessInstanceId;
}
public void setRootProcessInstanceId(String rootProcessInstanceId) {
this.rootProcessInstanceId = rootProcessInstanceId;
}
public Date getRemovalTime() {
return removalTime;
}
public void setRemovalTime(Date removalTime) {
this.removalTime = removalTime;
}
private static Permission[] getPermissions(Authorization dbAuthorization, ProcessEngineConfiguration engineConfiguration) {
int givenResourceType = dbAuthorization.getResourceType();
Permission[] permissionsByResourceType = ((ProcessEngineConfigurationImpl) engineConfiguration).getPermissionProvider().getPermissionsForResource(givenResourceType);
return dbAuthorization.getPermissions(permissionsByResourceType);
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\authorization\AuthorizationDto.java | 1 |
请完成以下Java代码 | public void setPA_ReportLine_ID (int PA_ReportLine_ID)
{
if (PA_ReportLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_PA_ReportLine_ID, Integer.valueOf(PA_ReportLine_ID));
}
/** Get Report Line.
@return Report Line */
public int getPA_ReportLine_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_PA_ReportLine_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Record ID.
@param Record_ID
Direct internal record ID
*/
public void setRecord_ID (int Record_ID)
{
if (Record_ID < 0)
set_ValueNoCheck (COLUMNNAME_Record_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID));
}
/** Get Record ID. | @return Direct internal record ID
*/
public int getRecord_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_Report.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class HierarchyContract implements CommissionContract
{
FlatrateTermId id;
Percent commissionPercent;
int pointsPrecision;
boolean isSimulation;
/**
* Technically not needed, but useful to help users retain a minimum level of sanity when analyzing why a particular commission was granted
*/
CommissionSettingsLineId commissionSettingsLineId;
public static boolean isInstance(@NonNull final CommissionContract contract)
{
return contract instanceof HierarchyContract;
}
@NonNull
public static Optional<HierarchyContract> castOrEmpty(@Nullable final CommissionContract contract)
{
if (contract == null)
{
return Optional.empty();
}
if (contract instanceof HierarchyContract)
{
return Optional.of((HierarchyContract)contract);
}
return Optional.empty();
}
@NonNull
public static HierarchyContract cast(@Nullable final CommissionContract contract)
{
return castOrEmpty(contract)
.orElseThrow(() -> new AdempiereException("Cannot cast the given contract to HierarchyContract")
.appendParametersToMessage()
.setParameter("contract", contract));
}
@JsonCreator
@Builder
public HierarchyContract(
@JsonProperty("id") @NonNull final FlatrateTermId id,
@JsonProperty("percent") @NonNull final Percent commissionPercent,
@JsonProperty("pointsPrecision") final int pointsPrecision, | @JsonProperty("commissionSettingsLineId") @Nullable final CommissionSettingsLineId commissionSettingsLineId,
@JsonProperty("isSimulation") final boolean isSimulation)
{
this.id = id;
this.commissionPercent = commissionPercent;
this.pointsPrecision = assumeGreaterOrEqualToZero(pointsPrecision, "pointsPrecision");
this.commissionSettingsLineId = commissionSettingsLineId;
this.isSimulation = isSimulation;
}
/**
* Note: add "Hierarchy" as method parameters if and when we have a commission type where it makes a difference.
*/
public Percent getCommissionPercent()
{
return commissionPercent;
}
public int getPointsPrecision()
{
return pointsPrecision;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\commission\commissioninstance\businesslogic\algorithms\hierarchy\HierarchyContract.java | 2 |
请完成以下Java代码 | private int getNextIntInRange(Range<Integer> range) {
OptionalInt first = getSource().ints(1, range.getMin(), range.getMax()).findFirst();
assertPresent(first.isPresent(), range);
return first.getAsInt();
}
private long getNextLongInRange(Range<Long> range) {
OptionalLong first = getSource().longs(1, range.getMin(), range.getMax()).findFirst();
assertPresent(first.isPresent(), range);
return first.getAsLong();
}
private void assertPresent(boolean present, Range<?> range) {
Assert.state(present, () -> "Could not get random number for range '" + range + "'");
}
private Object getRandomBytes() {
byte[] bytes = new byte[16];
getSource().nextBytes(bytes);
return HexFormat.of().withLowerCase().formatHex(bytes);
}
/**
* Add a {@link RandomValuePropertySource} to the given {@link Environment}.
* @param environment the environment to add the random property source to
*/
public static void addToEnvironment(ConfigurableEnvironment environment) {
addToEnvironment(environment, logger);
}
/**
* Add a {@link RandomValuePropertySource} to the given {@link Environment}.
* @param environment the environment to add the random property source to
* @param logger logger used for debug and trace information
* @since 4.0.0
*/
public static void addToEnvironment(ConfigurableEnvironment environment, Log logger) {
MutablePropertySources sources = environment.getPropertySources();
PropertySource<?> existing = sources.get(RANDOM_PROPERTY_SOURCE_NAME);
if (existing != null) {
logger.trace("RandomValuePropertySource already present");
return;
}
RandomValuePropertySource randomSource = new RandomValuePropertySource(RANDOM_PROPERTY_SOURCE_NAME);
if (sources.get(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME) != null) {
sources.addAfter(StandardEnvironment.SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME, randomSource);
}
else {
sources.addLast(randomSource);
}
logger.trace("RandomValuePropertySource add to Environment");
}
static final class Range<T extends Number> {
private final String value; | private final T min;
private final T max;
private Range(String value, T min, T max) {
this.value = value;
this.min = min;
this.max = max;
}
T getMin() {
return this.min;
}
T getMax() {
return this.max;
}
@Override
public String toString() {
return this.value;
}
static <T extends Number & Comparable<T>> Range<T> of(String value, Function<String, T> parse) {
T zero = parse.apply("0");
String[] tokens = StringUtils.commaDelimitedListToStringArray(value);
T min = parse.apply(tokens[0]);
if (tokens.length == 1) {
Assert.state(min.compareTo(zero) > 0, "Bound must be positive.");
return new Range<>(value, zero, min);
}
T max = parse.apply(tokens[1]);
Assert.state(min.compareTo(max) < 0, "Lower bound must be less than upper bound.");
return new Range<>(value, min, max);
}
}
} | repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\env\RandomValuePropertySource.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ChunkController {
@Autowired
private ChunkService chunkService;
/**
* upload by part
*
* @param chunk
* @return
*/
@PostMapping(value = "chunk")
public ResponseEntity<String> chunk(Chunk chunk) {
chunkService.chunk(chunk);
return ResponseEntity.ok("File Chunk Upload Success");
}
/**
* merge
*
* @param filename
* @return
*/
@GetMapping(value = "merge")
public ResponseEntity<Void> merge(@RequestParam("filename") String filename) {
chunkService.merge(filename);
return ResponseEntity.ok().build();
}
/**
* get fileName
*
* @return files
*/
@GetMapping("/files")
public ResponseEntity<List<FileInfo>> list() { | return ResponseEntity.ok(chunkService.list());
}
/**
* get single file
*
* @param filename
* @return file
*/
@GetMapping("/files/{filename:.+}")
public ResponseEntity<Resource> getFile(@PathVariable("filename") String filename) {
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION,
"attachment; filename=\"" + filename + "\"").body(chunkService.getFile(filename));
}
} | repos\springboot-demo-master\file\src\main\java\com\et\controller\ChunkController.java | 2 |
请完成以下Java代码 | private String toJsonString(Object o) {
try {
ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().build();
return objectMapper.writeValueAsString(o);
}
catch (Exception ex) {
log.warn("Failed to serialize JSON object", ex);
}
return null;
}
public URI getWebhookUrl() {
return this.webhookUrl;
}
public void setWebhookUrl(URI webhookUrl) {
this.webhookUrl = webhookUrl;
}
public void setRestTemplate(RestTemplate restTemplate) {
this.restTemplate = restTemplate;
}
public boolean isAtAll() {
return atAll;
}
public void setAtAll(boolean atAll) {
this.atAll = atAll;
}
public String getSecret() {
return secret;
}
public void setSecret(String secret) {
this.secret = secret;
}
public MessageType getMessageType() {
return messageType;
}
public void setMessageType(MessageType messageType) {
this.messageType = messageType;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
public enum MessageType {
text, interactive | }
public static class Card {
/**
* This is header title.
*/
private String title = "Codecentric's Spring Boot Admin notice";
private String themeColor = "red";
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getThemeColor() {
return themeColor;
}
public void setThemeColor(String themeColor) {
this.themeColor = themeColor;
}
}
} | repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\FeiShuNotifier.java | 1 |
请完成以下Java代码 | public QueueProcessorId getQueueProcessorForPackageProcessor(@NonNull final QueuePackageProcessorId packageProcessorId)
{
final I_C_Queue_Processor queueProcessor = getQueueProcessor(packageProcessorId);
return QueueProcessorId.ofRepoId(queueProcessor.getC_Queue_Processor_ID());
}
@NonNull
public I_C_Queue_Processor getQueueProcessor(@NonNull final QueuePackageProcessorId packageProcessorId)
{
final Map<QueueProcessorId, QueueProcessorDescriptor> queueProcessorDescriptors = getQueueProcessorIndex();
return queueProcessorDescriptors
.values()
.stream()
.filter(descriptor -> descriptor.hasPackageProcessor(packageProcessorId))
.map(QueueProcessorDescriptor::getQueueProcessor)
.findFirst()
.orElseThrow(() -> new AdempiereException("There is no C_Queue_Processor assigned to C_Queue_PackageProcessor!")
.appendParametersToMessage()
.setParameter("C_Queue_PackageProcessor_ID", packageProcessorId.getRepoId()));
}
@NonNull
public I_C_Queue_PackageProcessor getPackageProcessor(@NonNull final QueuePackageProcessorId packageProcessorId)
{
final Map<QueueProcessorId, QueueProcessorDescriptor> queueProcessorDescriptors = getQueueProcessorIndex();
return queueProcessorDescriptors
.values()
.stream()
.map(descriptor -> descriptor.getPackageProcessor(packageProcessorId))
.filter(Optional::isPresent)
.map(Optional::get)
.findFirst() | .orElseThrow(() -> new AdempiereException("There is no C_Queue_PackageProcessor found!")
.appendParametersToMessage()
.setParameter("C_Queue_PackageProcessor_ID", packageProcessorId.getRepoId()));
}
@NonNull
private Map<QueueProcessorId, QueueProcessorDescriptor> getQueueProcessorIndex()
{
return queueProcessorDescriptorIndexCCache.getOrLoad(QUEUE_PROCESSOR_DESCRIPTOR_CCACHE_KEY, this::loadQueueProcessorIndex);
}
@NonNull
private Map<QueueProcessorId, QueueProcessorDescriptor> loadQueueProcessorIndex(@NonNull final String ignoredCacheKey)
{
return queueProcessorDAO.getAllQueueProcessors()
.stream()
.map(queueProcessor -> {
final List<I_C_Queue_PackageProcessor> packageProcessors = queueDAO.retrieveWorkpackageProcessors(queueProcessor);
return new QueueProcessorDescriptor(queueProcessor, packageProcessors);
})
.collect(ImmutableMap.toImmutableMap(QueueProcessorDescriptor::getQueueProcessorId, Function.identity()));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\QueueProcessorDescriptorIndex.java | 1 |
请完成以下Java代码 | public BPartnerId getBPartnerIdByUserId(@NonNull final UserId userId)
{
final org.compiere.model.I_AD_User userRecord = getById(userId);
return BPartnerId.ofRepoIdOrNull(userRecord.getC_BPartner_ID());
}
@Override
public <T extends org.compiere.model.I_AD_User> T getByIdInTrx(final UserId userId, final Class<T> modelClass)
{
return load(userId, modelClass);
}
@Override
@Nullable
public UserId retrieveUserIdByLogin(@NonNull final String login)
{
return queryBL
.createQueryBuilderOutOfTrx(I_AD_User.class)
.addEqualsFilter(org.compiere.model.I_AD_User.COLUMNNAME_Login, login)
.create()
.firstId(UserId::ofRepoIdOrNull);
}
@Override
public void save(@NonNull final org.compiere.model.I_AD_User user)
{
InterfaceWrapperHelper.save(user);
}
@Override
public Optional<I_AD_User> getCounterpartUser(
@NonNull final UserId sourceUserId,
@NonNull final OrgId targetOrgId)
{
final OrgMappingId orgMappingId = getOrgMappingId(sourceUserId).orElse(null);
if (orgMappingId == null)
{
return Optional.empty();
}
final UserId targetUserId = queryBL.createQueryBuilder(I_AD_User.class)
.addEqualsFilter(I_AD_User.COLUMNNAME_AD_Org_Mapping_ID, orgMappingId)
.addEqualsFilter(I_AD_User.COLUMNNAME_AD_Org_ID, targetOrgId)
.orderByDescending(I_AD_User.COLUMNNAME_AD_User_ID)
.create() | .firstId(UserId::ofRepoIdOrNull);
if (targetUserId == null)
{
return Optional.empty();
}
return Optional.of(getById(targetUserId));
}
@Override
public ImmutableSet<UserId> retrieveUsersByJobId(@NonNull final JobId jobId)
{
return queryBL.createQueryBuilder(I_AD_User.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_User.COLUMNNAME_C_Job_ID, jobId)
.create()
.idsAsSet(UserId::ofRepoId);
}
private Optional<OrgMappingId> getOrgMappingId(@NonNull final UserId sourceUserId)
{
final I_AD_User sourceUserRecord = getById(sourceUserId);
return OrgMappingId.optionalOfRepoId(sourceUserRecord.getAD_Org_Mapping_ID());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\impl\UserDAO.java | 1 |
请完成以下Java代码 | public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
JpaOrderLine other = (JpaOrderLine) obj;
if (product == null) {
if (other.product != null) {
return false;
}
} else if (!product.equals(other.product)) {
return false;
}
if (quantity != other.quantity) {
return false;
}
return true;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1; | result = prime * result + ((product == null) ? 0 : product.hashCode());
result = prime * result + quantity;
return result;
}
@Override
public String toString() {
return "JpaOrderLine [product=" + product + ", quantity=" + quantity + "]";
}
JpaProduct getProduct() {
return product;
}
int getQuantity() {
return quantity;
}
} | repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\ddd\order\jpa\JpaOrderLine.java | 1 |
请完成以下Java代码 | public void forEachShipmentScheduleId(@NonNull final BiConsumer<ShipmentScheduleId, Set<PickingJobScheduleId>> consumer)
{
final LinkedHashMap<ShipmentScheduleId, HashSet<PickingJobScheduleId>> map = new LinkedHashMap<>();
ids.forEach(id -> {
final HashSet<PickingJobScheduleId> jobScheduleIds = map.computeIfAbsent(id.getShipmentScheduleId(), key -> new HashSet<>());
final PickingJobScheduleId jobScheduleId = id.getJobScheduleId();
if (jobScheduleId != null)
{
jobScheduleIds.add(jobScheduleId);
}
});
map.forEach(consumer);
}
public ShipmentScheduleAndJobScheduleIdSet retainOnlyShipmentScheduleIds(@NonNull final Collection<ShipmentScheduleId> shipmentScheduleIds)
{
if (isEmpty()) {return this;}
Check.assumeNotEmpty(shipmentScheduleIds, "shipmentScheduleIds is not empty"); | final ImmutableSet<ShipmentScheduleAndJobScheduleId> retainedIds = ids.stream()
.filter(id -> shipmentScheduleIds.contains(id.getShipmentScheduleId()))
.collect(ImmutableSet.toImmutableSet());
return Objects.equals(this.ids, retainedIds)
? this
: ofCollection(retainedIds);
}
@Nullable
public ShipmentScheduleAndJobScheduleId singleOrNull()
{
return ids.size() == 1 ? ids.iterator().next() : null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\picking\api\ShipmentScheduleAndJobScheduleIdSet.java | 1 |
请完成以下Java代码 | public int getK_EntryRelated_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_K_EntryRelated_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), String.valueOf(getK_EntryRelated_ID()));
}
/** 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_K_EntryRelated.java | 1 |
请完成以下Java代码 | public void registerConverter(final Class<?> xmlRequestClass, final Converter<Object, Object> converter)
{
handlers.put(xmlRequestClass, converter);
}
public void setJAXBContext(final JAXBContext jaxbContext)
{
this.jaxbContext = jaxbContext;
}
public void setJAXBObjectFactory(final DynamicObjectFactory jaxbObjectFactory)
{
this.jaxbObjectFactory = jaxbObjectFactory;
}
private Object createXMLObject(final String xml)
{
try
{
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
final Source source = createXMLSourceFromString(xml);
final JAXBElement<?> jaxbElement = (JAXBElement<?>)unmarshaller.unmarshal(source);
final Object xmlRequestObj = jaxbElement.getValue();
return xmlRequestObj;
}
catch (JAXBException e)
{
throw new AdempiereException("Cannot convert string to xml object: " + xml, e); | }
}
private String createStringFromXMLObject(final Object xmlObject)
{
try
{
final JAXBElement<Object> jaxbElement = jaxbObjectFactory.createJAXBElement(xmlObject);
final Marshaller marshaller = jaxbContext.createMarshaller();
final StringWriter writer = new StringWriter();
marshaller.marshal(jaxbElement, writer);
final String xmlObjectStr = writer.toString();
return xmlObjectStr;
}
catch (JAXBException e)
{
throw new AdempiereException("Cannot convert xml object to string: " + xmlObject, e);
}
}
private Source createXMLSourceFromString(final String xmlStr)
{
final InputStream inputStream = new ByteArrayInputStream(xmlStr == null ? new byte[0] : xmlStr.getBytes(StandardCharsets.UTF_8));
return new StreamSource(inputStream);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\api\impl\MockedImportHelper.java | 1 |
请完成以下Java代码 | public Optional<ComponentDescriptor> saveIfNotExist(TenantId tenantId, ComponentDescriptor component) {
if (component.getId() == null) {
UUID uuid = Uuids.timeBased();
component.setId(new ComponentDescriptorId(uuid));
component.setCreatedTime(Uuids.unixTimestamp(uuid));
}
if (!componentDescriptorRepository.existsById(component.getId().getId())) {
ComponentDescriptorEntity componentDescriptorEntity = new ComponentDescriptorEntity(component);
ComponentDescriptorEntity savedEntity = componentDescriptorInsertRepository.saveOrUpdate(componentDescriptorEntity);
return Optional.of(savedEntity.toData());
}
return Optional.empty();
}
@Override
public ComponentDescriptor findById(TenantId tenantId, ComponentDescriptorId componentId) {
return findById(tenantId, componentId.getId());
}
@Override
public ComponentDescriptor findByClazz(TenantId tenantId, String clazz) {
return DaoUtil.getData(componentDescriptorRepository.findByClazz(clazz));
}
@Override
public PageData<ComponentDescriptor> findByTypeAndPageLink(TenantId tenantId, ComponentType type, PageLink pageLink) {
return DaoUtil.toPageData(componentDescriptorRepository
.findByType( | type,
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));
}
@Override
public PageData<ComponentDescriptor> findByScopeAndTypeAndPageLink(TenantId tenantId, ComponentScope scope, ComponentType type, PageLink pageLink) {
return DaoUtil.toPageData(componentDescriptorRepository
.findByScopeAndType(
type,
scope,
pageLink.getTextSearch(),
DaoUtil.toPageable(pageLink)));
}
@Override
@Transactional
public void deleteById(TenantId tenantId, ComponentDescriptorId componentId) {
removeById(tenantId, componentId.getId());
}
@Override
@Transactional
public void deleteByClazz(TenantId tenantId, String clazz) {
componentDescriptorRepository.deleteByClazz(clazz);
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\component\JpaBaseComponentDescriptorDao.java | 1 |
请完成以下Java代码 | public static boolean isValid(final String pzn)
{
if (pzn.length() != PZN7_Length && pzn.length() != PZN8_Length)
{
return false;
}
if (!pzn.equals(StringUtils.getDigits(pzn)))
{
return false;
}
final int codeLimit = pzn.length() - 1;
final int checkDigit = Character.getNumericValue(pzn.charAt(codeLimit));
final String code = pzn.substring(0, codeLimit);
final int initialMultiplier;
if (pzn.length() == PZN7_Length)
{
initialMultiplier = PZN7_InitialMultiplier;
}
else
{
initialMultiplier = PZN8_InitialMultiplier;
}
final int codeModuloResult = calculateModulo11(code, initialMultiplier);
return codeModuloResult == checkDigit;
}
private static int calculateModulo11(final String code, final int initialMultiplier) | {
int total = 0;
int multiplier = initialMultiplier;
final int codeLength = code.length();
for (int i = 0; i < codeLength; i++)
{
int value = Character.getNumericValue(code.charAt(i));
total += value * multiplier;
multiplier++;
}
if (total == 0)
{
throw new AdempiereException("Invalid code, sum is zero");
}
return total % PZN_MODULO11;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma\src\main\java\de\metas\vertical\pharma\PharmaModulo11Validator.java | 1 |
请完成以下Java代码 | public static BPGroupId ofRepoId(final int repoId)
{
final BPGroupId id = ofRepoIdOrNull(repoId);
if (id == null)
{
throw new AdempiereException("Invalid C_BP_Group_ID: " + repoId);
}
return id;
}
@Nullable
public static BPGroupId ofRepoIdOrNull(final int repoId)
{
if (repoId == STANDARD.repoId)
{
return STANDARD;
}
else if (repoId <= 0)
{
return null;
}
else
{
return new BPGroupId(repoId);
}
}
public static Optional<BPGroupId> optionalOfRepoId(final int repoId) {return Optional.ofNullable(ofRepoIdOrNull(repoId));} | public static int toRepoId(@Nullable final BPGroupId bpGroupId)
{
return bpGroupId != null ? bpGroupId.getRepoId() : -1;
}
@JsonValue
public int toJson()
{
return getRepoId();
}
public static boolean equals(@Nullable final BPGroupId o1, @Nullable final BPGroupId o2)
{
return Objects.equals(o1, o2);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPGroupId.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StandardMongoClientSettingsBuilderCustomizer implements MongoClientSettingsBuilderCustomizer, Ordered {
private final UuidRepresentation uuidRepresentation;
private final MongoConnectionDetails connectionDetails;
private int order;
public StandardMongoClientSettingsBuilderCustomizer(MongoConnectionDetails connectionDetails,
UuidRepresentation uuidRepresentation) {
this.connectionDetails = connectionDetails;
this.uuidRepresentation = uuidRepresentation;
}
@Override
public void customize(MongoClientSettings.Builder settingsBuilder) {
settingsBuilder.uuidRepresentation(this.uuidRepresentation);
settingsBuilder.applyConnectionString(this.connectionDetails.getConnectionString());
settingsBuilder.applyToSslSettings(this::configureSslIfNeeded);
}
private void configureSslIfNeeded(SslSettings.Builder settings) {
SslBundle sslBundle = this.connectionDetails.getSslBundle();
if (sslBundle != null) {
settings.enabled(true);
Assert.state(!sslBundle.getOptions().isSpecified(), "SSL options cannot be specified with MongoDB");
settings.context(sslBundle.createSslContext());
}
} | @Override
public int getOrder() {
return this.order;
}
/**
* Set the order value of this object.
* @param order the new order value
* @see #getOrder()
*/
public void setOrder(int order) {
this.order = order;
}
} | repos\spring-boot-4.0.1\module\spring-boot-mongodb\src\main\java\org\springframework\boot\mongodb\autoconfigure\StandardMongoClientSettingsBuilderCustomizer.java | 2 |
请完成以下Java代码 | public Integer getWidth() {
return 17;
}
@Override
public Integer getHeight() {
return 15;
}
@Override
public String getAnchorValue() {
return null;
}
@Override
public String getFillValue() {
return "#585858";
}
@Override
public String getStyleValue() {
return "stroke-width:1.4;stroke-miterlimit:4;stroke-dasharray:none";
}
@Override
public String getDValue() {
return " M7.7124971 20.247342 L22.333334 20.247342 L15.022915000000001 7.575951200000001 L7.7124971 20.247342 z";
}
@Override
public void drawIcon(int imageX, int imageY, int iconPadding, ProcessDiagramSVGGraphics2D svgGenerator) { | Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG);
gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 7) + "," + (imageY - 7) + ")");
Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG);
pathTag.setAttributeNS(null, "d", this.getDValue());
pathTag.setAttributeNS(null, "style", this.getStyleValue());
pathTag.setAttributeNS(null, "fill", this.getFillValue());
pathTag.setAttributeNS(null, "stroke", this.getStrokeValue());
gTag.appendChild(pathTag);
svgGenerator.getExtendDOMGroupManager().addElement(gTag);
}
@Override
public String getStrokeValue() {
return "#585858";
}
@Override
public String getStrokeWidth() {
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\SignalThrowIconType.java | 1 |
请完成以下Java代码 | public JobDto findCleanupJob() {
Job job = processEngine.getHistoryService().findHistoryCleanupJob();
if (job == null) {
throw new RestException(Status.NOT_FOUND, "History cleanup job does not exist");
}
return JobDto.fromJob(job);
}
public List<JobDto> findCleanupJobs() {
List<Job> jobs = processEngine.getHistoryService().findHistoryCleanupJobs();
if (jobs == null || jobs.isEmpty()) {
throw new RestException(Status.NOT_FOUND, "History cleanup jobs are empty");
}
List<JobDto> dtos = new ArrayList<JobDto>();
for (Job job : jobs) {
JobDto dto = JobDto.fromJob(job);
dtos.add(dto);
}
return dtos;
}
public HistoryCleanupConfigurationDto getHistoryCleanupConfiguration() {
ProcessEngineConfigurationImpl engineConfiguration = | (ProcessEngineConfigurationImpl) processEngine.getProcessEngineConfiguration();
HistoryCleanupConfigurationDto configurationDto = new HistoryCleanupConfigurationDto();
configurationDto.setEnabled(engineConfiguration.isHistoryCleanupEnabled());
BatchWindow batchWindow = engineConfiguration.getBatchWindowManager()
.getCurrentOrNextBatchWindow(ClockUtil.getCurrentTime(), engineConfiguration);
if (batchWindow != null) {
configurationDto.setBatchWindowStartTime(batchWindow.getStart());
configurationDto.setBatchWindowEndTime(batchWindow.getEnd());
}
return configurationDto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\HistoryCleanupRestServiceImpl.java | 1 |
请完成以下Java代码 | protected void closeLdapCtx(LdapContext context) {
if (context != null) {
try {
context.close();
} catch (NamingException e) {
// ignore
LdapPluginLogger.INSTANCE.exceptionWhenClosingLdapContext(e);
}
}
}
public LdapSearchResults search(String baseDn, String searchFilter) {
try {
return new LdapSearchResults(initialContext.search(baseDn, searchFilter, ldapConfiguration.getSearchControls()));
} catch (NamingException e) {
throw new IdentityProviderException("LDAP search request failed.", e);
}
}
public void setRequestControls(List<Control> listControls) {
try {
initialContext.setRequestControls(listControls.toArray(new Control[0]));
} catch (NamingException e) {
throw new IdentityProviderException("LDAP server failed to set request controls.", e);
}
}
public Control[] getResponseControls() {
try {
return initialContext.getResponseControls();
} catch (NamingException e) {
throw new IdentityProviderException("Error occurred while getting the response controls from the LDAP server.", e);
}
}
public static void addPaginationControl(List<Control> listControls, byte[] cookie, Integer pageSize) {
try {
listControls.add(new PagedResultsControl(pageSize, cookie, Control.NONCRITICAL));
} catch (IOException e) {
throw new IdentityProviderException("Pagination couldn't be enabled.", e);
}
}
public static void addSortKey(SortKey sortKey, List<Control> controls) {
try {
controls.add(new SortControl(new SortKey[] { sortKey }, Control.CRITICAL));
} catch (IOException e) {
throw new IdentityProviderException("Sorting couldn't be enabled.", e);
}
} | protected static String getValue(String attrName, Attributes attributes) {
Attribute attribute = attributes.get(attrName);
if (attribute != null) {
try {
return (String) attribute.get();
} catch (NamingException e) {
throw new IdentityProviderException("Error occurred while retrieving the value.", e);
}
} else {
return null;
}
}
@SuppressWarnings("unchecked")
public static NamingEnumeration<String> getAllMembers(String attributeId, LdapSearchResults searchResults) {
SearchResult result = searchResults.nextElement();
Attributes attributes = result.getAttributes();
if (attributes != null) {
Attribute memberAttribute = attributes.get(attributeId);
if (memberAttribute != null) {
try {
return (NamingEnumeration<String>) memberAttribute.getAll();
} catch (NamingException e) {
throw new IdentityProviderException("Value couldn't be retrieved.", e);
}
}
}
return null;
}
} | repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\LdapClient.java | 1 |
请完成以下Java代码 | private void contribute(Map<String, Object> details, Dependency dependency) {
if (!ObjectUtils.isEmpty(dependency.getMappings())) {
Map<String, VersionRange> dep = new LinkedHashMap<>();
dependency.getMappings().forEach((it) -> {
if (it.getRange() != null && it.getVersion() != null) {
dep.put(it.getVersion(), it.getRange());
}
});
if (!dep.isEmpty()) {
if (dependency.getRange() == null) {
boolean openRange = dep.values().stream().anyMatch((v) -> v.getHigherVersion() == null);
if (!openRange) {
Version higher = getHigher(dep);
dep.put("managed", new VersionRange(higher));
}
}
Map<String, Object> depInfo = new LinkedHashMap<>();
dep.forEach((k, r) -> depInfo.put(k, "Spring Boot " + r));
details.put(dependency.getId(), depInfo);
}
}
else if (dependency.getVersion() != null && dependency.getRange() != null) {
Map<String, Object> dep = new LinkedHashMap<>();
String requirement = "Spring Boot " + dependency.getRange();
dep.put(dependency.getVersion(), requirement); | details.put(dependency.getId(), dep);
}
}
private Version getHigher(Map<String, VersionRange> dep) {
Version higher = null;
for (VersionRange versionRange : dep.values()) {
Version candidate = versionRange.getHigherVersion();
if (higher == null) {
higher = candidate;
}
else if (candidate.compareTo(higher) > 0) {
higher = candidate;
}
}
return higher;
}
} | repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\info\DependencyRangesInfoContributor.java | 1 |
请完成以下Java代码 | private final String buildUIDefaultsKey(final String name)
{
return buildUIDefaultsKey(uiSubClassID, name);
}
private static final String buildUIDefaultsKey(final String uiSubClassID, final String name)
{
if (uiSubClassID == null)
{
return name;
}
else
{
return uiSubClassID + "." + name;
}
}
public boolean getBoolean(final String name, final boolean defaultValue)
{
Object value = UIManager.getDefaults().get(buildUIDefaultsKey(name));
if (value instanceof Boolean)
{
return (boolean)value;
}
if (uiSubClassID != null)
{
value = UIManager.getDefaults().get(name);
if (value instanceof Boolean)
{
return (boolean)value;
}
}
return defaultValue;
}
/**
* Convert all keys from given UI defaults key-value list by applying the <code>uiSubClassID</code> prefix to them.
*
* @param uiSubClassID
* @param keyValueList
* @return converted <code>keyValueList</code>
*/
public static final Object[] applyUISubClassID(final String uiSubClassID, final Object[] keyValueList)
{
if (keyValueList == null || keyValueList.length <= 0)
{ | return keyValueList;
}
Check.assumeNotEmpty(uiSubClassID, "uiSubClassID not empty");
final Object[] keyValueListConverted = new Object[keyValueList.length];
for (int i = 0, max = keyValueList.length; i < max; i += 2)
{
final Object keyOrig = keyValueList[i];
final Object value = keyValueList[i + 1];
final Object key;
if (keyOrig instanceof String)
{
key = buildUIDefaultsKey(uiSubClassID, (String)keyOrig);
}
else
{
key = keyOrig;
}
keyValueListConverted[i] = key;
keyValueListConverted[i + 1] = value;
}
return keyValueListConverted;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\UISubClassIDHelper.java | 1 |
请完成以下Java代码 | private void setConstraintInfo(@NonNull final Throwable e)
{
if (!isUniqueContraintError(e))
{
return; // not unique constraint, nothing to do
}
else if (DB.isPostgreSQL())
{
this.constraintName = extractConstraintNameFromPostgreSQLErrorMessage(e.getMessage());
}
//
if (!Check.isBlank(this.constraintName))
{
this.index = MIndexTable.getByNameIgnoringCase(this.constraintName);
}
if (this.index != null)
{
markAsUserValidationError();
}
}
private static String extractConstraintNameFromPostgreSQLErrorMessage(final String msg)
{
String constraintName = StringUtils.trimBlankToNull(parseConstraintName(msg, "\"", "\""));
if (constraintName != null)
{
return constraintName;
}
// Check for german errors (e.g. Bitte Informationen �ndern.
// org.postgresql.util.PSQLException: FEHLER: duplizierter Schl�ssel
// verletzt Unique-Constraint �bpl_billto_unique�)
return StringUtils.trimBlankToNull(parseConstraintName(msg, "»", "«"));
}
@Override
protected ITranslatableString buildMessage()
{
if (index != null)
{
final ITranslatableString errorMsg = index.getErrorMsgTrl();
if (!TranslatableStrings.isBlank(errorMsg))
{
final TranslatableStringBuilder message = TranslatableStrings.builder();
final ITranslatableString indexErrorMsg = index.get_ModelTranslationMap().getColumnTrl(MIndexTable.COLUMNNAME_ErrorMsg, index.getErrorMsg());
message.append(indexErrorMsg);
if (Services.get(IDeveloperModeBL.class).isEnabled())
{
message.append(" (AD_Index_Table:" + index.getName() + ")");
}
return message.build();
}
else
{
return TranslatableStrings.builder().appendADMessage(MSG_SaveErrorNotUnique).append(" ").appendADElement(I_AD_Index_Table.COLUMNNAME_AD_Index_Table_ID).append(": ").append(index.getName()).build();
} | }
else if (!Check.isBlank(constraintName))
{
return TranslatableStrings.builder().appendADMessage(MSG_SaveErrorNotUnique).append(": ").append(constraintName).build();
}
else
{
final TranslatableStringBuilder message = TranslatableStrings.builder().appendADMessage(MSG_SaveErrorNotUnique);
final Throwable cause = getCause();
if (cause != null)
{
message.append(": ").append(AdempiereException.extractMessageTrl(cause));
}
return message.build();
}
}
private static String parseConstraintName(final String sqlException, final String quoteStart, final String quoteEnd)
{
final int i = sqlException.indexOf(quoteStart);
if (i >= 0)
{
final int i2 = sqlException.indexOf(quoteEnd, i + quoteStart.length());
if (i2 >= 0)
{
return sqlException.substring(i + quoteStart.length(), i2);
}
}
return null;
}
@Nullable
@Override
public String getErrorCode()
{
return DB_UNIQUE_CONSTRAINT_ERROR_CODE;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\exceptions\DBUniqueConstraintException.java | 1 |
请完成以下Java代码 | public int getIMP_Processor_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IMP_Processor_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Import Processor Log.
@param IMP_ProcessorLog_ID Import Processor Log */
public void setIMP_ProcessorLog_ID (int IMP_ProcessorLog_ID)
{
if (IMP_ProcessorLog_ID < 1)
set_ValueNoCheck (COLUMNNAME_IMP_ProcessorLog_ID, null);
else
set_ValueNoCheck (COLUMNNAME_IMP_ProcessorLog_ID, Integer.valueOf(IMP_ProcessorLog_ID));
}
/** Get Import Processor Log.
@return Import Processor Log */
public int getIMP_ProcessorLog_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_IMP_ProcessorLog_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Error.
@param IsError
An Error occurred in the execution
*/
public void setIsError (boolean IsError)
{
set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError));
}
/** Get Error.
@return An Error occurred in the execution
*/
public boolean isError ()
{
Object oo = get_Value(COLUMNNAME_IsError);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** 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 Summary.
@param Summary
Textual summary of this request
*/
public void setSummary (String Summary)
{
set_Value (COLUMNNAME_Summary, Summary);
}
/** Get Summary.
@return Textual summary of this request
*/
public String getSummary ()
{
return (String)get_Value(COLUMNNAME_Summary);
}
/** Set Text Message.
@param TextMsg
Text Message
*/
public void setTextMsg (String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
/** Get Text Message.
@return Text Message
*/
public String getTextMsg ()
{
return (String)get_Value(COLUMNNAME_TextMsg);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_IMP_ProcessorLog.java | 1 |
请完成以下Java代码 | public void setIsDisplayed (boolean IsDisplayed)
{
set_Value (COLUMNNAME_IsDisplayed, Boolean.valueOf(IsDisplayed));
}
/** Get Displayed.
@return Determines, if this field is displayed
*/
public boolean isDisplayed ()
{
Object oo = get_Value(COLUMNNAME_IsDisplayed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Multi Row Only.
@param IsMultiRowOnly
This applies to Multi-Row view only
*/
public void setIsMultiRowOnly (boolean IsMultiRowOnly)
{
set_Value (COLUMNNAME_IsMultiRowOnly, Boolean.valueOf(IsMultiRowOnly));
}
/** Get Multi Row Only.
@return This applies to Multi-Row view only
*/
public boolean isMultiRowOnly ()
{
Object oo = get_Value(COLUMNNAME_IsMultiRowOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Read Only.
@param IsReadOnly
Field is read only
*/
public void setIsReadOnly (boolean IsReadOnly)
{
set_Value (COLUMNNAME_IsReadOnly, Boolean.valueOf(IsReadOnly));
}
/** Get Read Only.
@return Field is read only
*/
public boolean isReadOnly ()
{
Object oo = get_Value(COLUMNNAME_IsReadOnly);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
} | /** Set Single Row Layout.
@param IsSingleRow
Default for toggle between Single- and Multi-Row (Grid) Layout
*/
public void setIsSingleRow (boolean IsSingleRow)
{
set_Value (COLUMNNAME_IsSingleRow, Boolean.valueOf(IsSingleRow));
}
/** Get Single Row Layout.
@return Default for toggle between Single- and Multi-Row (Grid) Layout
*/
public boolean isSingleRow ()
{
Object oo = get_Value(COLUMNNAME_IsSingleRow);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity
*/
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Tab.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public ProcessInstanceModificationBuilderImpl getModificationBuilder() {
return modificationBuilder;
}
public String getBusinessKey() {
return businessKey;
}
public String getCaseInstanceId() {
return caseInstanceId;
}
public Map<String, Object> getVariables() {
return modificationBuilder.getProcessVariables();
}
public String getTenantId() {
return tenantId;
}
public String getProcessDefinitionTenantId() {
return processDefinitionTenantId;
}
public boolean isProcessDefinitionTenantIdSet() {
return isProcessDefinitionTenantIdSet;
} | public void setModificationBuilder(ProcessInstanceModificationBuilderImpl modificationBuilder) {
this.modificationBuilder = modificationBuilder;
}
public void setRestartedProcessInstanceId(String restartedProcessInstanceId){
this.restartedProcessInstanceId = restartedProcessInstanceId;
}
public String getRestartedProcessInstanceId(){
return restartedProcessInstanceId;
}
public static ProcessInstantiationBuilder createProcessInstanceById(CommandExecutor commandExecutor, String processDefinitionId) {
ProcessInstantiationBuilderImpl builder = new ProcessInstantiationBuilderImpl(commandExecutor);
builder.processDefinitionId = processDefinitionId;
return builder;
}
public static ProcessInstantiationBuilder createProcessInstanceByKey(CommandExecutor commandExecutor, String processDefinitionKey) {
ProcessInstantiationBuilderImpl builder = new ProcessInstantiationBuilderImpl(commandExecutor);
builder.processDefinitionKey = processDefinitionKey;
return builder;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstantiationBuilderImpl.java | 1 |
请完成以下Java代码 | public class PMM_PurchaseCandidate_Product_FacetCollector extends SingleFacetCategoryCollectorTemplate<I_PMM_PurchaseCandidate>
{
public PMM_PurchaseCandidate_Product_FacetCollector()
{
super(FacetCategory.builder()
.setDisplayNameAndTranslate(I_PMM_PurchaseCandidate.COLUMNNAME_M_Product_ID)
.setCollapsed(true) // 08755: default collapsed
.build());
}
@Override
protected List<IFacet<I_PMM_PurchaseCandidate>> collectFacets(final IQueryBuilder<I_PMM_PurchaseCandidate> queryBuilder)
{
final List<Map<String, Object>> bpartners = queryBuilder
.andCollect(I_PMM_PurchaseCandidate.COLUMN_M_Product_ID)
.create()
.listDistinct(I_M_Product.COLUMNNAME_M_Product_ID, I_M_Product.COLUMNNAME_Name, I_M_Product.COLUMNNAME_Value);
final List<IFacet<I_PMM_PurchaseCandidate>> facets = new ArrayList<>(bpartners.size());
for (final Map<String, Object> row : bpartners)
{
final IFacet<I_PMM_PurchaseCandidate> facet = createFacet(row);
facets.add(facet);
}
return facets; | }
private IFacet<I_PMM_PurchaseCandidate> createFacet(final Map<String, Object> row)
{
final IFacetCategory facetCategoryBPartners = getFacetCategory();
final int bpartnerId = (int)row.get(I_M_Product.COLUMNNAME_M_Product_ID);
final String bpartnerName = new StringBuilder()
.append(row.get(I_M_Product.COLUMNNAME_Value))
.append(" - ")
.append(row.get(I_M_Product.COLUMNNAME_Name))
.toString();
final Facet<I_PMM_PurchaseCandidate> facet = Facet.<I_PMM_PurchaseCandidate> builder()
.setFacetCategory(facetCategoryBPartners)
.setDisplayName(bpartnerName)
.setFilter(TypedSqlQueryFilter.of(I_PMM_PurchaseCandidate.COLUMNNAME_M_Product_ID + "=" + bpartnerId))
.build();
return facet;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\facet\impl\PMM_PurchaseCandidate_Product_FacetCollector.java | 1 |
请完成以下Java代码 | public class RemittanceLocation2 {
@XmlElement(name = "RmtId")
protected String rmtId;
@XmlElement(name = "RmtLctnMtd")
@XmlSchemaType(name = "string")
protected RemittanceLocationMethod2Code rmtLctnMtd;
@XmlElement(name = "RmtLctnElctrncAdr")
protected String rmtLctnElctrncAdr;
@XmlElement(name = "RmtLctnPstlAdr")
protected NameAndAddress10 rmtLctnPstlAdr;
/**
* Gets the value of the rmtId property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRmtId() {
return rmtId;
}
/**
* Sets the value of the rmtId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRmtId(String value) {
this.rmtId = value;
}
/**
* Gets the value of the rmtLctnMtd property.
*
* @return
* possible object is
* {@link RemittanceLocationMethod2Code }
*
*/
public RemittanceLocationMethod2Code getRmtLctnMtd() {
return rmtLctnMtd;
}
/**
* Sets the value of the rmtLctnMtd property.
*
* @param value
* allowed object is
* {@link RemittanceLocationMethod2Code }
* | */
public void setRmtLctnMtd(RemittanceLocationMethod2Code value) {
this.rmtLctnMtd = value;
}
/**
* Gets the value of the rmtLctnElctrncAdr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getRmtLctnElctrncAdr() {
return rmtLctnElctrncAdr;
}
/**
* Sets the value of the rmtLctnElctrncAdr property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setRmtLctnElctrncAdr(String value) {
this.rmtLctnElctrncAdr = value;
}
/**
* Gets the value of the rmtLctnPstlAdr property.
*
* @return
* possible object is
* {@link NameAndAddress10 }
*
*/
public NameAndAddress10 getRmtLctnPstlAdr() {
return rmtLctnPstlAdr;
}
/**
* Sets the value of the rmtLctnPstlAdr property.
*
* @param value
* allowed object is
* {@link NameAndAddress10 }
*
*/
public void setRmtLctnPstlAdr(NameAndAddress10 value) {
this.rmtLctnPstlAdr = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\RemittanceLocation2.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getUPCTU() {
return upctu;
}
/**
* Sets the value of the upctu property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setUPCTU(String value) {
this.upctu = value;
}
/**
* Gets the value of the isDeliveryClosed property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIsDeliveryClosed() {
return isDeliveryClosed;
}
/**
* Sets the value of the isDeliveryClosed property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setIsDeliveryClosed(String value) {
this.isDeliveryClosed = value;
}
/**
* Gets the value of the gtincu property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGTINCU() {
return gtincu;
}
/**
* Sets the value of the gtincu property. | *
* @param value
* allowed object is
* {@link String }
*
*/
public void setGTINCU(String value) {
this.gtincu = value;
}
/**
* Gets the value of the gtintu property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getGTINTU() {
return gtintu;
}
/**
* Sets the value of the gtintu property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setGTINTU(String value) {
this.gtintu = value;
}
} | repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev2\de\metas\edi\esb\jaxb\metasfreshinhousev2\EXPMInOutDesadvLineVType.java | 2 |
请完成以下Java代码 | protected org.compiere.model.POInfo initPO(final Properties ctx)
{
return org.compiere.model.POInfo.getPOInfo(Table_Name);
}
@Override
public void setMKTG_Channel_ID (final int MKTG_Channel_ID)
{
if (MKTG_Channel_ID < 1)
set_ValueNoCheck (COLUMNNAME_MKTG_Channel_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MKTG_Channel_ID, MKTG_Channel_ID);
}
@Override
public int getMKTG_Channel_ID() | {
return get_ValueAsInt(COLUMNNAME_MKTG_Channel_ID);
}
@Override
public void setName (final java.lang.String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_MKTG_Channel.java | 1 |
请完成以下Java代码 | public abstract class KeywordExtractor
{
/**
* 默认分词器
*/
protected Segment defaultSegment;
public KeywordExtractor(Segment defaultSegment)
{
this.defaultSegment = defaultSegment;
}
public KeywordExtractor()
{
this(StandardTokenizer.SEGMENT);
}
/**
* 是否应当将这个term纳入计算,词性属于名词、动词、副词、形容词
*
* @param term
* @return 是否应当
*/
protected boolean shouldInclude(Term term)
{
// 除掉停用词
return CoreStopWordDictionary.shouldInclude(term);
}
/**
* 设置关键词提取器使用的分词器
*
* @param segment 任何开启了词性标注的分词器
* @return 自己
*/
public KeywordExtractor setSegment(Segment segment)
{
defaultSegment = segment;
return this;
}
public Segment getSegment()
{
return defaultSegment; | }
/**
* 提取关键词
*
* @param document 关键词
* @param size 需要几个关键词
* @return
*/
public List<String> getKeywords(String document, int size)
{
return getKeywords(defaultSegment.seg(document), size);
}
/**
* 提取关键词(top 10)
*
* @param document 文章
* @return
*/
public List<String> getKeywords(String document)
{
return getKeywords(defaultSegment.seg(document), 10);
}
protected void filter(List<Term> termList)
{
ListIterator<Term> listIterator = termList.listIterator();
while (listIterator.hasNext())
{
if (!shouldInclude(listIterator.next()))
listIterator.remove();
}
}
abstract public List<String> getKeywords(List<Term> termList, int size);
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\summary\KeywordExtractor.java | 1 |
请完成以下Java代码 | public CountResultDto queryUserOperationCount(UriInfo uriInfo) {
UserOperationLogQueryDto queryDto = new UserOperationLogQueryDto(objectMapper, uriInfo.getQueryParameters());
UserOperationLogQuery query = queryDto.toQuery(processEngine);
return new CountResultDto(query.count());
}
@Override
public List<UserOperationLogEntryDto> queryUserOperationEntries(UriInfo uriInfo, Integer firstResult, Integer maxResults) {
UserOperationLogQueryDto queryDto = new UserOperationLogQueryDto(objectMapper, uriInfo.getQueryParameters());
UserOperationLogQuery query = queryDto.toQuery(processEngine);
return UserOperationLogEntryDto.map(QueryUtil.list(query, firstResult, maxResults));
}
@Override
public Response setAnnotation(String operationId, AnnotationDto annotationDto) {
String annotation = annotationDto.getAnnotation(); | processEngine.getHistoryService()
.setAnnotationForOperationLogById(operationId, annotation);
return Response.noContent().build();
}
@Override
public Response clearAnnotation(String operationId) {
processEngine.getHistoryService()
.clearAnnotationForOperationLogById(operationId);
return Response.noContent().build();
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\history\UserOperationLogRestServiceImpl.java | 1 |
请完成以下Java代码 | private void configureSessionCookie(SessionCookieConfig config) {
Cookie cookie = this.session.getCookie();
PropertyMapper map = PropertyMapper.get();
map.from(cookie::getName).to(config::setName);
map.from(cookie::getDomain).to(config::setDomain);
map.from(cookie::getPath).to(config::setPath);
map.from(cookie::getHttpOnly).to(config::setHttpOnly);
map.from(cookie::getSecure).to(config::setSecure);
map.from(cookie::getMaxAge).asInt(Duration::getSeconds).to(config::setMaxAge);
map.from(cookie::getPartitioned)
.as(Object::toString)
.to((partitioned) -> config.setAttribute("Partitioned", partitioned));
}
@Contract("!null -> !null") | private @Nullable Set<jakarta.servlet.SessionTrackingMode> unwrap(
@Nullable Set<Session.SessionTrackingMode> modes) {
if (modes == null) {
return null;
}
Set<jakarta.servlet.SessionTrackingMode> result = new LinkedHashSet<>();
for (Session.SessionTrackingMode mode : modes) {
result.add(jakarta.servlet.SessionTrackingMode.valueOf(mode.name()));
}
return result;
}
}
} | repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletContextInitializers.java | 1 |
请完成以下Java代码 | public QuickInput build()
{
return new QuickInput(this);
}
public Builder setRootDocumentPath(final DocumentPath rootDocumentPath)
{
_rootDocumentPath = Preconditions.checkNotNull(rootDocumentPath, "rootDocumentPath");
return this;
}
private DocumentPath getRootDocumentPath()
{
Check.assumeNotNull(_rootDocumentPath, "Parameter rootDocumentPath is not null");
return _rootDocumentPath;
}
public Builder setQuickInputDescriptor(final QuickInputDescriptor quickInputDescriptor)
{
_quickInputDescriptor = quickInputDescriptor;
return this;
}
private QuickInputDescriptor getQuickInputDescriptor()
{
Check.assumeNotNull(_quickInputDescriptor, "Parameter quickInputDescriptor is not null"); | return _quickInputDescriptor;
}
private DetailId getTargetDetailId()
{
final DetailId targetDetailId = getQuickInputDescriptor().getDetailId();
Check.assumeNotNull(targetDetailId, "Parameter targetDetailId is not null");
return targetDetailId;
}
private Document buildQuickInputDocument()
{
return Document.builder(getQuickInputDescriptor().getEntityDescriptor())
.initializeAsNewDocument(nextQuickInputDocumentId::getAndIncrement, VERSION_DEFAULT);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInput.java | 1 |
请完成以下Java代码 | public ProcessInstance from(org.activiti.engine.runtime.ProcessInstance internalProcessInstance) {
ProcessInstanceImpl processInstance = new ProcessInstanceImpl();
processInstance.setId(internalProcessInstance.getId());
processInstance.setParentId(internalProcessInstance.getParentProcessInstanceId());
processInstance.setName(internalProcessInstance.getName());
processInstance.setProcessDefinitionId(internalProcessInstance.getProcessDefinitionId());
processInstance.setProcessDefinitionKey(internalProcessInstance.getProcessDefinitionKey());
processInstance.setProcessDefinitionVersion(internalProcessInstance.getProcessDefinitionVersion());
processInstance.setInitiator(internalProcessInstance.getStartUserId());
processInstance.setStartDate(internalProcessInstance.getStartTime());
processInstance.setProcessDefinitionKey(internalProcessInstance.getProcessDefinitionKey());
processInstance.setBusinessKey(internalProcessInstance.getBusinessKey());
processInstance.setStatus(calculateStatus(internalProcessInstance));
processInstance.setProcessDefinitionVersion(internalProcessInstance.getProcessDefinitionVersion());
processInstance.setAppVersion(Objects.toString(internalProcessInstance.getAppVersion(), null));
processInstance.setProcessDefinitionName(internalProcessInstance.getProcessDefinitionName()); | processInstance.setRootProcessInstanceId(internalProcessInstance.getRootProcessInstanceId());
return processInstance;
}
private ProcessInstance.ProcessInstanceStatus calculateStatus(
org.activiti.engine.runtime.ProcessInstance internalProcessInstance
) {
if (internalProcessInstance.isSuspended()) {
return ProcessInstance.ProcessInstanceStatus.SUSPENDED;
} else if (internalProcessInstance.isEnded()) {
return ProcessInstance.ProcessInstanceStatus.COMPLETED;
} else if (internalProcessInstance.getStartTime() == null) {
return ProcessInstance.ProcessInstanceStatus.CREATED;
}
return ProcessInstance.ProcessInstanceStatus.RUNNING;
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\model\impl\APIProcessInstanceConverter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ArithmeticController {
@Autowired
private ArithmeticService arithmeticService;
@GetMapping("/sum/{number1}/{number2}")
public float getSum(@PathVariable("number1") float number1, @PathVariable("number2") float number2) {
return arithmeticService.add(number1, number2);
}
@GetMapping("/subtract/{number1}/{number2}")
public float getDifference(@PathVariable("number1") float number1, @PathVariable("number2") float number2) {
return arithmeticService.subtract(number1, number2);
}
@GetMapping("/multiply/{number1}/{number2}")
public float getMultiplication(@PathVariable("number1") float number1, @PathVariable("number2") float number2) {
return arithmeticService.multiply(number1, number2);
}
@GetMapping("/divide/{number1}/{number2}")
public float getDivision(@PathVariable("number1") float number1, @PathVariable("number2") float number2) {
return arithmeticService.divide(number1, number2);
}
@GetMapping("/memory")
public String getMemoryStatus() {
MemoryMXBean memoryBean = ManagementFactory.getMemoryMXBean(); | String memoryStats = "";
String init = String.format(
"Initial: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getInit() /1073741824);
String usedHeap = String.format("Used: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getUsed() /1073741824);
String maxHeap = String.format("Max: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getMax() /1073741824);
String committed = String.format("Committed: %.2f GB \n",
(double)memoryBean.getHeapMemoryUsage().getCommitted() /1073741824);
memoryStats += init;
memoryStats += usedHeap;
memoryStats += maxHeap;
memoryStats += committed;
return memoryStats;
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-mvc-3\src\main\java\com\baeldung\micronaut\vs\springboot\controller\ArithmeticController.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public class JsonKPIDataSetValue
{
@JsonProperty("_key") Object _key;
@JsonIgnore Map<String, Object> map;
public static JsonKPIDataSetValue of(@NonNull final KPIDataSetValuesMap dataSetValue, @NonNull final KPIJsonOptions jsonOpts)
{
return new JsonKPIDataSetValue(dataSetValue.getKey(), dataSetValue.getValues(), jsonOpts);
}
public JsonKPIDataSetValue(
@NonNull final KPIDataSetValuesAggregationKey key,
@NonNull final Map<String, KPIDataValue> map,
@NonNull final KPIJsonOptions jsonOpts)
{
_key = key.toJsonValue(jsonOpts);
this.map = map.entrySet()
.stream()
.map(e -> toJson(e, jsonOpts)) | .collect(GuavaCollectors.toImmutableMap());
}
private static Map.Entry<String, Object> toJson(@NonNull final Map.Entry<String, KPIDataValue> entry, @NonNull final KPIJsonOptions jsonOpts)
{
return GuavaCollectors.entry(
entry.getKey(),
entry.getValue().toJsonValue(jsonOpts));
}
@JsonAnyGetter
private Map<String, Object> getMap()
{
return map;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\json\JsonKPIDataSetValue.java | 2 |
请完成以下Java代码 | /* package */class CompositeQueryUpdater<T> implements ICompositeQueryUpdater<T>
{
private final List<IQueryUpdater<T>> queryUpdaters = new ArrayList<>();
private String sql = null;
private List<Object> sqlParams = null;
private boolean sqlBuilt = false;
public CompositeQueryUpdater()
{
}
@Override
public ICompositeQueryUpdater<T> addQueryUpdater(@NonNull final IQueryUpdater<T> updater)
{
queryUpdaters.add(updater);
sqlBuilt = false;
return this;
}
@Override
public ICompositeQueryUpdater<T> addSetColumnValue(final String columnName, @Nullable final Object value)
{
final IQueryUpdater<T> updater = new SetColumnNameQueryUpdater<>(columnName, value);
return addQueryUpdater(updater);
}
@Override
public ICompositeQueryUpdater<T> addSetColumnFromColumn(final String columnName, final ModelColumnNameValue<T> fromColumnName)
{
final IQueryUpdater<T> updater = new SetColumnNameQueryUpdater<>(columnName, fromColumnName);
return addQueryUpdater(updater);
}
@Override
public ICompositeQueryUpdater<T> addAddValueToColumn(final String columnName, final BigDecimal valueToAdd)
{
final IQueryFilter<T> onlyWhenFilter = null;
final IQueryUpdater<T> updater = new AddToColumnQueryUpdater<>(columnName, valueToAdd, onlyWhenFilter);
return addQueryUpdater(updater);
}
@Override
public ICompositeQueryUpdater<T> addAddValueToColumn(final String columnName, final BigDecimal valueToAdd, final IQueryFilter<T> onlyWhenFilter)
{
final IQueryUpdater<T> updater = new AddToColumnQueryUpdater<>(columnName, valueToAdd, onlyWhenFilter);
return addQueryUpdater(updater);
}
@Override
public boolean update(final T model)
{
boolean updated = false;
for (final IQueryUpdater<T> updater : queryUpdaters)
{
if (updater.update(model))
{
updated = true;
} | }
return updated;
}
@Override
public String getSql(final Properties ctx, final List<Object> params)
{
buildSql(ctx);
params.addAll(sqlParams);
return sql;
}
private void buildSql(final Properties ctx)
{
if (sqlBuilt)
{
return;
}
if (queryUpdaters.isEmpty())
{
throw new AdempiereException("Cannot build sql update query for an empty " + CompositeQueryUpdater.class);
}
final StringBuilder sql = new StringBuilder();
final List<Object> params = new ArrayList<>();
for (final IQueryUpdater<T> updater : queryUpdaters)
{
final ISqlQueryUpdater<T> sqlUpdater = (ISqlQueryUpdater<T>)updater;
final String sqlChunk = sqlUpdater.getSql(ctx, params);
if (Check.isEmpty(sqlChunk))
{
continue;
}
if (sql.length() > 0)
{
sql.append(", ");
}
sql.append(sqlChunk);
}
this.sql = sql.toString();
this.sqlParams = params;
this.sqlBuilt = true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\CompositeQueryUpdater.java | 1 |
请完成以下Java代码 | public String toString() {
return "ParaModel{" +
"provice='" + provice + '\'' +
", area='" + area + '\'' +
", streets=" + streets +
'}';
}
public String getProvice() {
return provice;
}
public void setProvice(String provice) {
this.provice = provice;
}
public String getArea() { | return area;
}
public void setArea(String area) {
this.area = area;
}
public List<Street> getStreets() {
return streets;
}
public void setStreets(List<Street> streets) {
this.streets = streets;
}
} | repos\spring-boot-quick-master\quick-swagger\src\main\java\com\quick\po\ParaModel.java | 1 |
请完成以下Java代码 | public Builder add(
@NonNull final String fieldName,
@Nullable final Collection<String> dependsOnFieldNames,
@NonNull final DependencyType dependencyType)
{
if (dependsOnFieldNames == null || dependsOnFieldNames.isEmpty())
{
return this;
}
final ImmutableSetMultimap.Builder<String, String> fieldName2dependsOnFieldNames
= type2name2dependencies.computeIfAbsent(dependencyType, k -> ImmutableSetMultimap.builder());
for (final String dependsOnFieldName : dependsOnFieldNames)
{
fieldName2dependsOnFieldNames.put(dependsOnFieldName, fieldName);
}
return this;
}
public Builder add(@Nullable final DocumentFieldDependencyMap dependencies)
{
if (dependencies == null || dependencies == EMPTY)
{ | return this;
}
for (final Map.Entry<DependencyType, Multimap<String, String>> l1 : dependencies.type2name2dependencies.entrySet())
{
final DependencyType dependencyType = l1.getKey();
final ImmutableSetMultimap.Builder<String, String> name2dependencies
= type2name2dependencies.computeIfAbsent(dependencyType, k -> ImmutableSetMultimap.builder());
name2dependencies.putAll(l1.getValue());
}
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentFieldDependencyMap.java | 1 |
请在Spring Boot框架中完成以下Java代码 | protected <T> T postProcess(T object) {
return (T) this.objectPostProcessor.postProcess(object);
}
/**
* Adds an {@link ObjectPostProcessor} to be used for this
* {@link SecurityConfigurerAdapter}. The default implementation does nothing to the
* object.
* @param objectPostProcessor the {@link ObjectPostProcessor} to use
*/
public void addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
this.objectPostProcessor.addObjectPostProcessor(objectPostProcessor);
}
/**
* Sets the {@link SecurityBuilder} to be used. This is automatically set when using
* {@link AbstractConfiguredSecurityBuilder#with(SecurityConfigurerAdapter, Customizer)}
* @param builder the {@link SecurityBuilder} to set
*/
public void setBuilder(B builder) {
this.securityBuilder = builder;
}
/**
* An {@link ObjectPostProcessor} that delegates work to numerous
* {@link ObjectPostProcessor} implementations.
*
* @author Rob Winch
*/
private static final class CompositeObjectPostProcessor implements ObjectPostProcessor<Object> {
private List<ObjectPostProcessor<?>> postProcessors = new ArrayList<>();
@Override
@SuppressWarnings({ "rawtypes", "unchecked" })
public Object postProcess(Object object) { | for (ObjectPostProcessor opp : this.postProcessors) {
Class<?> oppClass = opp.getClass();
Class<?> oppType = GenericTypeResolver.resolveTypeArgument(oppClass, ObjectPostProcessor.class);
if (oppType == null || oppType.isAssignableFrom(object.getClass())) {
object = opp.postProcess(object);
}
}
return object;
}
/**
* Adds an {@link ObjectPostProcessor} to use
* @param objectPostProcessor the {@link ObjectPostProcessor} to add
* @return true if the {@link ObjectPostProcessor} was added, else false
*/
private boolean addObjectPostProcessor(ObjectPostProcessor<?> objectPostProcessor) {
boolean result = this.postProcessors.add(objectPostProcessor);
this.postProcessors.sort(AnnotationAwareOrderComparator.INSTANCE);
return result;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\SecurityConfigurerAdapter.java | 2 |
请在Spring Boot框架中完成以下Java代码 | public String addDictByLowAppId(SysDictVo sysDictVo) {
String[] dictResult = this.addDict(sysDictVo.getDictName(),sysDictVo.getLowAppId(),sysDictVo.getTenantId());
String id = dictResult[0];
String code = dictResult[1];
this.addDictItem(id,sysDictVo.getDictItemsList());
return code;
}
@Override
public void editDictByLowAppId(SysDictVo sysDictVo) {
String id = sysDictVo.getId();
SysDict dict = baseMapper.selectById(id);
if(null == dict){
throw new JeecgBootException("字典数据不存在");
}
//判断应用id和数据库中的是否一致,不一致不让修改
if(!dict.getLowAppId().equals(sysDictVo.getLowAppId())){
throw new JeecgBootException("字典数据不存在");
}
SysDict sysDict = new SysDict();
sysDict.setDictName(sysDictVo.getDictName());
sysDict.setId(id);
baseMapper.updateById(sysDict);
this.updateDictItem(id,sysDictVo.getDictItemsList());
// 删除字典缓存
redisUtil.removeAll(CacheConstant.SYS_DICT_CACHE + "::" + dict.getDictCode());
}
/**
* 还原逻辑删除
* @param ids
*/
@Override
public boolean revertLogicDeleted(List<String> ids) {
return baseMapper.revertLogicDeleted(ids) > 0;
}
/**
* 彻底删除
* @param ids
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public boolean removeLogicDeleted(List<String> ids) {
// 1. 删除字典
int line = this.baseMapper.removeLogicDeleted(ids);
// 2. 删除字典选项配置
line += this.sysDictItemMapper.delete(new LambdaQueryWrapper<SysDictItem>().in(SysDictItem::getDictId, ids));
return line > 0;
} | /**
* 添加字典
* @param dictName
*/
private String[] addDict(String dictName,String lowAppId, Integer tenantId) {
SysDict dict = new SysDict();
dict.setDictName(dictName);
dict.setDictCode(RandomUtil.randomString(10));
dict.setDelFlag(Integer.valueOf(CommonConstant.STATUS_0));
dict.setLowAppId(lowAppId);
dict.setTenantId(tenantId);
baseMapper.insert(dict);
String[] dictResult = new String[]{dict.getId(), dict.getDictCode()};
return dictResult;
}
/**
* 添加字典子项
* @param id
* @param dictItemList
*/
private void addDictItem(String id,List<SysDictItem> dictItemList) {
if(null!=dictItemList && dictItemList.size()>0){
for (SysDictItem dictItem:dictItemList) {
SysDictItem sysDictItem = new SysDictItem();
BeanUtils.copyProperties(dictItem,sysDictItem);
sysDictItem.setDictId(id);
sysDictItem.setId("");
sysDictItem.setStatus(Integer.valueOf(CommonConstant.STATUS_1));
sysDictItemMapper.insert(sysDictItem);
}
}
}
/**
* 更新字典子项
* @param id
* @param dictItemList
*/
private void updateDictItem(String id,List<SysDictItem> dictItemList){
//先删除在新增 因为排序可能不一致
LambdaQueryWrapper<SysDictItem> query = new LambdaQueryWrapper<>();
query.eq(SysDictItem::getDictId,id);
sysDictItemMapper.delete(query);
//新增子项
this.addDictItem(id,dictItemList);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysDictServiceImpl.java | 2 |
请完成以下Java代码 | private void resizeBuf(int size)
{
int capacity;
if (size >= _capacity * 2)
{
capacity = size;
}
else
{
capacity = 1;
while (capacity < size)
{
capacity <<= 1;
}
}
byte[] buf = new byte[capacity];
if (_size > 0)
{
System.arraycopy(_buf, 0, buf, 0, _size); | }
_buf = buf;
_capacity = capacity;
}
/**
* 缓冲区
*/
private byte[] _buf;
/**
* 大小
*/
private int _size;
/**
* 容量
*/
private int _capacity;
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\AutoBytePool.java | 1 |
请完成以下Java代码 | public void setLabel(String label)
{
this.label = label;
}
@Override
public void setValue(String value)
{
innerList.clear();
innerList.add(new Word(value, label));
}
@Override
public int length()
{
return getValue().length();
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append('[');
int i = 1;
for (Word word : innerList)
{
sb.append(word.getValue());
String label = word.getLabel();
if (label != null)
{
sb.append('/').append(label);
}
if (i != innerList.size())
{
sb.append(' ');
}
++i;
}
sb.append("]/");
sb.append(label);
return sb.toString();
}
/**
* 转换为一个简单词 | * @return
*/
public Word toWord()
{
return new Word(getValue(), getLabel());
}
public CompoundWord(List<Word> innerList, String label)
{
this.innerList = innerList;
this.label = label;
}
public static CompoundWord create(String param)
{
if (param == null) return null;
int cutIndex = param.lastIndexOf(']');
if (cutIndex <= 2 || cutIndex == param.length() - 1) return null;
String wordParam = param.substring(1, cutIndex);
List<Word> wordList = new LinkedList<Word>();
for (String single : wordParam.split("\\s+"))
{
if (single.length() == 0) continue;
Word word = Word.create(single);
if (word == null)
{
Predefine.logger.warning("使用参数" + single + "构造单词时发生错误");
return null;
}
wordList.add(word);
}
String labelParam = param.substring(cutIndex + 1);
if (labelParam.startsWith("/"))
{
labelParam = labelParam.substring(1);
}
return new CompoundWord(wordList, labelParam);
}
@Override
public Iterator<Word> iterator()
{
return innerList.iterator();
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\sentence\word\CompoundWord.java | 1 |
请完成以下Java代码 | public String getContentType()
{
return contentType;
}
/** @return true if the format is about displaying tabular data (e.g. Excel, CSV etc). */
public boolean isTabular()
{
return tabular;
}
/** @return file extension to be used for this format, without dot (e.g. xls, html, csv etc) */
public String getFileExtension()
{
return fileExtension;
} | /**
* @return {@link OutputType} for the given file extension.
*/
public static Optional<OutputType> getOutputTypeByFileExtension(final String fileExtension )
{
return Stream.of( values() )
.filter( v -> v.getFileExtension().equalsIgnoreCase(fileExtension) )
.findFirst();
}
public static OutputType getDefault()
{
return OutputType.PDF;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\de.metas.report.jasper.commons\src\main\java\de\metas\report\server\OutputType.java | 1 |
请完成以下Java代码 | private ExternalSystemMap getMap() {return cache.getOrLoad(0, this::retrieveMap);}
private ExternalSystemMap retrieveMap()
{
return queryBL.createQueryBuilder(I_ExternalSystem.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(ExternalSystemRepository::fromRecord)
.collect(ExternalSystemMap.collect());
}
@NonNull
public ExternalSystem getByType(@NonNull final ExternalSystemType type)
{
return getMap().getByType(type);
}
@NonNull
public ExternalSystemId getIdByType(@NonNull final ExternalSystemType type)
{
return getMap().getByType(type).getId();
}
public Optional<ExternalSystem> getOptionalByType(@NonNull final ExternalSystemType type)
{
return getMap().getOptionalByType(type);
}
public Optional<ExternalSystem> getOptionalByValue(@NonNull final String value)
{
return getMap().getOptionalByType(ExternalSystemType.ofValue(value));
}
@NonNull
public ExternalSystem getById(@NonNull final ExternalSystemId id) | {
return getMap().getById(id);
}
private static ExternalSystem fromRecord(@NonNull final I_ExternalSystem externalSystemRecord)
{
return ExternalSystem.builder()
.id(ExternalSystemId.ofRepoId(externalSystemRecord.getExternalSystem_ID()))
.type(ExternalSystemType.ofValue(externalSystemRecord.getValue()))
.name(externalSystemRecord.getName())
.build();
}
public ExternalSystem create(@NonNull final ExternalSystemCreateRequest request)
{
final I_ExternalSystem record = InterfaceWrapperHelper.newInstance(I_ExternalSystem.class);
record.setName(request.getName());
record.setValue(request.getType().getValue());
InterfaceWrapperHelper.save(record);
return fromRecord(record);
}
@Nullable
public ExternalSystem getByLegacyCodeOrValueOrNull(@NonNull final String value)
{
final ExternalSystemMap map = getMap();
return CoalesceUtil.coalesceSuppliers(
() -> map.getByTypeOrNull(ExternalSystemType.ofValue(value)),
() -> {
final ExternalSystemType externalSystemType = ExternalSystemType.ofLegacyCodeOrNull(value);
return externalSystemType != null ? map.getByTypeOrNull(externalSystemType) : null;
}
);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\externalsystem\ExternalSystemRepository.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.