instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | public class MNewsItem extends X_CM_NewsItem
{
/**
*
*/
private static final long serialVersionUID = -8217571535161436997L;
/***
* Standard Constructor
*
* @param ctx context
* @param CM_NewsItem_ID id
* @param trxName transaction
*/
public MNewsItem (Properties ctx, int CM_NewsItem_ID, String trxName)
{
super (ctx, CM_NewsItem_ID, trxName);
} // MNewsItem
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MNewsItem (Properties ctx, ResultSet rs, String trxName)
{
super (ctx, rs, trxName);
} // MNewsItem
/**
* getNewsChannel
* @return NewsChannel
*/
public MNewsChannel getNewsChannel()
{
int[] thisNewsChannel = MNewsChannel.getAllIDs("CM_NewsChannel","CM_NewsChannel_ID=" + this.getCM_NewsChannel_ID(), get_TrxName());
if (thisNewsChannel!=null)
{
if (thisNewsChannel.length==1)
return new MNewsChannel(getCtx(), thisNewsChannel[0], get_TrxName());
}
return null;
} // getNewsChannel
/**
* Get rss2 Item Code
* @param xmlCode xml
* @param thisChannel channel
* @return rss item code
*/
public StringBuffer get_rss2ItemCode(StringBuffer xmlCode, MNewsChannel thisChannel)
{
if (this != null) // never null ??
{
xmlCode.append ("<item>");
xmlCode.append ("<CM_NewsItem_ID>"+ this.get_ID() + "</CM_NewsItem_ID>");
xmlCode.append (" <title><![CDATA["
+ this.getTitle () + "]]></title>");
xmlCode.append (" <description><![CDATA["
+ this.getDescription ()
+ "]]></description>");
xmlCode.append (" <content><![CDATA["
+ this.getContentHTML ()
+ "]]></content>");
xmlCode.append (" <link>"
+ thisChannel.getLink ()
+ "?CM_NewsItem_ID=" + this.get_ID() + "</link>");
xmlCode.append (" <author><![CDATA["
+ this.getAuthor () + "]]></author>");
xmlCode.append (" <pubDate>"
+ this.getPubDate () + "</pubDate>");
xmlCode.append ("</item>");
}
return xmlCode;
}
/**
* After Save. | * Insert
* - create / update index
* @param newRecord insert
* @param success save success
* @return true if saved
*/
protected boolean afterSave (boolean newRecord, boolean success)
{
if (!success)
return success;
if (!newRecord)
{
MIndex.cleanUp(get_TrxName(), getAD_Client_ID(), get_Table_ID(), get_ID());
}
reIndex(newRecord);
return success;
} // afterSave
/**
* reIndex
* @param newRecord
*/
public void reIndex(boolean newRecord)
{
int CMWebProjectID = 0;
if (getNewsChannel()!=null)
CMWebProjectID = getNewsChannel().getCM_WebProject_ID();
String [] toBeIndexed = new String[4];
toBeIndexed[0] = this.getAuthor();
toBeIndexed[1] = this.getDescription();
toBeIndexed[2] = this.getTitle();
toBeIndexed[3] = this.getContentHTML();
MIndex.reIndex (newRecord, toBeIndexed, getCtx(), getAD_Client_ID(), get_Table_ID(), get_ID(), CMWebProjectID, this.getUpdated());
} // reIndex
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MNewsItem.java | 1 |
请完成以下Java代码 | public static Function<ServerRequest, ServerRequest> uri(String uri) {
return uri(URI.create(uri));
}
public static Function<ServerRequest, ServerRequest> uri(URI uri) {
return request -> {
MvcUtils.setRequestUrl(request, uri);
return request;
};
}
public static class FallbackHeadersConfig {
private String executionExceptionTypeHeaderName = CB_EXECUTION_EXCEPTION_TYPE;
private String executionExceptionMessageHeaderName = CB_EXECUTION_EXCEPTION_MESSAGE;
private String rootCauseExceptionTypeHeaderName = CB_ROOT_CAUSE_EXCEPTION_TYPE;
private String rootCauseExceptionMessageHeaderName = CB_ROOT_CAUSE_EXCEPTION_MESSAGE;
public String getExecutionExceptionTypeHeaderName() {
return executionExceptionTypeHeaderName;
}
public void setExecutionExceptionTypeHeaderName(String executionExceptionTypeHeaderName) {
this.executionExceptionTypeHeaderName = executionExceptionTypeHeaderName;
}
public String getExecutionExceptionMessageHeaderName() {
return executionExceptionMessageHeaderName;
} | public void setExecutionExceptionMessageHeaderName(String executionExceptionMessageHeaderName) {
this.executionExceptionMessageHeaderName = executionExceptionMessageHeaderName;
}
public String getRootCauseExceptionTypeHeaderName() {
return rootCauseExceptionTypeHeaderName;
}
public void setRootCauseExceptionTypeHeaderName(String rootCauseExceptionTypeHeaderName) {
this.rootCauseExceptionTypeHeaderName = rootCauseExceptionTypeHeaderName;
}
public String getRootCauseExceptionMessageHeaderName() {
return rootCauseExceptionMessageHeaderName;
}
public void setRootCauseExceptionMessageHeaderName(String rootCauseExceptionMessageHeaderName) {
this.rootCauseExceptionMessageHeaderName = rootCauseExceptionMessageHeaderName;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\filter\BeforeFilterFunctions.java | 1 |
请完成以下Java代码 | private void writeLine(final CharSequence line)
{
try
{
writer.append(line.toString());
writer.append(lineEnding);
}
catch (final IOException ex)
{
throw new AdempiereException("Failed writing CSV line: " + line, ex);
}
linesWrote++;
}
private String toCsvValue(@Nullable final Object valueObj)
{
final String valueStr;
if (valueObj == null)
{
valueStr = "";
}
else if (TimeUtil.isDateOrTimeObject(valueObj))
{
final java.util.Date valueDate = TimeUtil.asDate(valueObj);
valueStr = dateFormat.format(valueDate);
}
else
{
valueStr = valueObj.toString();
}
return quoteCsvValue(valueStr);
}
private String quoteCsvValue(@NonNull final String valueStr)
{
return fieldQuote
+ valueStr.replace(fieldQuote, fieldQuote + fieldQuote)
+ fieldQuote;
}
public void close()
{
if (writer == null)
{
return;
}
try
{ | writer.flush();
}
catch (IOException ex)
{
throw new AdempiereException("Failed flushing CSV data to file", ex);
}
finally
{
if (writer != null)
{
try
{
writer.close();
}
catch (IOException e)
{
// shall not happen
e.printStackTrace(); // NOPMD by tsa on 3/13/13 1:46 PM
}
writer = null;
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\spreadsheet\csv\CSVWriter.java | 1 |
请完成以下Java代码 | public String getInvolvedUser() {
return involvedUser;
}
public IdentityLinkQueryObject getInvolvedUserIdentityLink() {
return involvedUserIdentityLink;
}
public Set<String> getInvolvedGroups() {
return involvedGroups;
}
public IdentityLinkQueryObject getInvolvedGroupIdentityLink() {
return involvedGroupIdentityLink;
}
public boolean isIncludeCaseVariables() {
return includeCaseVariables;
}
public Collection<String> getVariableNamesToInclude() {
return variableNamesToInclude;
}
public List<HistoricCaseInstanceQueryImpl> getOrQueryObjects() {
return orQueryObjects;
}
public String getDeploymentId() {
return deploymentId;
}
public List<String> getDeploymentIds() {
return deploymentIds;
}
public Set<String> getCaseInstanceIds() {
return caseInstanceIds;
}
public boolean isNeedsCaseDefinitionOuterJoin() {
if (isNeedsPaging()) {
if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType)
|| AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType)
|| AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) {
// When using oracle, db2 or mssql we don't need outer join for the process definition join.
// It is not needed because the outer join order by is done by the row number instead
return false;
}
}
return hasOrderByForColumn(HistoricCaseInstanceQueryProperty.CASE_DEFINITION_KEY.getName());
} | public List<List<String>> getSafeCaseInstanceIds() {
return safeCaseInstanceIds;
}
public void setSafeCaseInstanceIds(List<List<String>> safeCaseInstanceIds) {
this.safeCaseInstanceIds = safeCaseInstanceIds;
}
public List<List<String>> getSafeInvolvedGroups() {
return safeInvolvedGroups;
}
public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) {
this.safeInvolvedGroups = safeInvolvedGroups;
}
public String getRootScopeId() {
return rootScopeId;
}
public String getParentScopeId() {
return parentScopeId;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\history\HistoricCaseInstanceQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class LotteryService {
private final String contractAddress;
private final Web3j web3j;
private final LotteryProperties config;
public LotteryService(String contractAddress, Web3j web3j, LotteryProperties config) {
this.contractAddress = contractAddress;
this.web3j = web3j;
this.config = config;
}
public BigInteger getBalance() throws IOException {
return web3j.ethGetBalance(contractAddress, DefaultBlockParameterName.LATEST).send().getBalance();
}
public void join(Player player) throws Exception {
Lottery lottery = loadContract(player.getAddress());
lottery.enter(Convert.toWei(player.getEthers(), Unit.ETHER).toBigInteger()).send();
}
@SuppressWarnings("unchecked")
public List<String> getPlayers(String ownerAddress) throws Exception {
Lottery lottery = loadContract(ownerAddress);
return lottery.getPlayers().send(); | }
public void pickWinner(String ownerAddress) throws Exception {
Lottery lottery = loadContract(ownerAddress);
lottery.pickWinner().send();
}
private Lottery loadContract(String accountAddress) {
return Lottery.load(contractAddress, web3j, txManager(accountAddress), config.gas());
}
private TransactionManager txManager(String accountAddress) {
return new ClientTransactionManager(web3j, accountAddress);
}
} | repos\springboot-demo-master\Blockchain\src\main\java\com\et\bc\service\LotteryService.java | 2 |
请完成以下Java代码 | public String getOuterOrderBy() {
String outerOrderBy = getOrderBy();
if (outerOrderBy == null || outerOrderBy.isEmpty()) {
return "ID_ asc";
}
else if (outerOrderBy.contains(".")) {
return outerOrderBy.substring(outerOrderBy.lastIndexOf(".") + 1);
}
else {
return outerOrderBy;
}
}
private List<QueryVariableValue> createQueryVariableValues(VariableSerializers variableTypes, List<VariableQueryParameterDto> variables, String dbType) {
List<QueryVariableValue> values = new ArrayList<QueryVariableValue>();
if (variables == null) {
return values; | }
for (VariableQueryParameterDto variable : variables) {
QueryVariableValue value = new QueryVariableValue(
variable.getName(),
resolveVariableValue(variable.getValue()),
ConditionQueryParameterDto.getQueryOperator(variable.getOperator()),
false);
value.initialize(variableTypes, dbType);
values.add(value);
}
return values;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\AbstractProcessInstanceQueryDto.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public void setProcessDefinitionKey(String processDefinitionKey) {
this.processDefinitionKey = processDefinitionKey;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public void setProcessDefinitionName(String processDefinitionName) {
this.processDefinitionName = processDefinitionName;
}
public String getTaskName() {
return taskName;
}
public void setTaskName(String taskName) {
this.taskName = taskName;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) { | this.tenantId = tenantId;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[" +
"count=" + count +
", processDefinitionKey='" + processDefinitionKey + '\'' +
", processDefinitionId='" + processDefinitionId + '\'' +
", processDefinitionName='" + processDefinitionName + '\'' +
", taskName='" + taskName + '\'' +
", tenantId='" + tenantId + '\'' +
']';
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\TaskReportResultEntity.java | 1 |
请完成以下Java代码 | public class ProcessApplicationReferenceImpl implements ProcessApplicationReference {
private static ProcessApplicationLogger LOG = ProcessEngineLogger.PROCESS_APPLICATION_LOGGER;
/** the weak reference to the process application */
protected WeakReference<AbstractProcessApplication> processApplication;
protected String name;
public ProcessApplicationReferenceImpl(AbstractProcessApplication processApplication) {
this.processApplication = new WeakReference<AbstractProcessApplication>(processApplication);
this.name = processApplication.getName();
}
public String getName() {
return name;
}
public AbstractProcessApplication getProcessApplication() throws ProcessApplicationUnavailableException {
AbstractProcessApplication application = processApplication.get();
if (application == null) { | throw LOG.processApplicationUnavailableException(name);
}
else {
return application;
}
}
public void processEngineStopping(ProcessEngine processEngine) throws ProcessApplicationUnavailableException {
// do nothing
}
public void clear() {
processApplication.clear();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\application\impl\ProcessApplicationReferenceImpl.java | 1 |
请完成以下Java代码 | public V remove(K key) throws CacheException {
BoundHashOperations<String, K, V> hash = redisTemplate.boundHashOps(cacheKey);
V value = null;
try {
Object k = hashKey(key);
value = hash.get(k);
hash.delete(k);
} catch (Exception e) {
e.printStackTrace();
}
return value;
}
@Override
public void clear() throws CacheException {
redisTemplate.delete(cacheKey);
}
@Override
public int size() {
BoundHashOperations<String, K, V> hash = redisTemplate.boundHashOps(cacheKey);
return hash.size().intValue();
}
@Override
public Set<K> keys() {
BoundHashOperations<String, K, V> hash = redisTemplate.boundHashOps(cacheKey);
return hash.keys();
} | @Override
public Collection<V> values() {
BoundHashOperations<String, K, V> hash = redisTemplate.boundHashOps(cacheKey);
return hash.values();
}
protected Object hashKey(K key) {
//此处很重要,如果key是登录凭证,那么这是访问用户的授权缓存;将登录凭证转为user对象,返回user的id属性做为hash key,否则会以user对象做为hash key,这样就不好清除指定用户的缓存了
if (key instanceof PrincipalCollection) {
PrincipalCollection pc = (PrincipalCollection) key;
ShiroUser user = (ShiroUser) pc.getPrimaryPrincipal();
return user.getUserId();
}
return key;
}
}
} | repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\ShiroRedisCacheManager.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DocOutboundConfigRepository
{
@NonNull private final IQueryBL queryBL = Services.get(IQueryBL.class);
@NonNull private final CCache<Integer, DocOutboundConfigMap> cache = CCache.<Integer, DocOutboundConfigMap>builder()
.tableName(I_C_Doc_Outbound_Config.Table_Name)
.maximumSize(1)
.build();
public static DocOutboundConfigRepository newInstanceForUnitTesting()
{
Adempiere.assertUnitTestMode();
return new DocOutboundConfigRepository();
}
public void addCacheResetListener(@NonNull final DocOutboundConfigChangedListener listener)
{
final ICacheResetListener cacheResetListener = (request) -> {
listener.onConfigChanged();
return 1L;
};
final CacheMgt cacheMgt = CacheMgt.get();
cacheMgt.addCacheResetListener(I_C_Doc_Outbound_Config.Table_Name, cacheResetListener);
}
@Nullable
public DocOutboundConfig getByQuery(@NonNull final DocOutboundConfigQuery query)
{
return getDocOutboundConfigMap().getByQuery(query);
}
@NonNull
private DocOutboundConfigMap getDocOutboundConfigMap()
{
return cache.getOrLoadNonNull(0, this::retrieveDocOutboundConfigMap);
}
@NotNull
private DocOutboundConfigMap retrieveDocOutboundConfigMap()
{
final ImmutableList<DocOutboundConfig> docOutboundConfig = queryBL.createQueryBuilder(I_C_Doc_Outbound_Config.class)
.addOnlyActiveRecordsFilter()
.create()
.stream() | .map(DocOutboundConfigRepository::ofRecord)
.collect(ImmutableList.toImmutableList());
return new DocOutboundConfigMap(docOutboundConfig);
}
private static DocOutboundConfig ofRecord(@NotNull final I_C_Doc_Outbound_Config record)
{
return DocOutboundConfig.builder()
.id(DocOutboundConfigId.ofRepoId(record.getC_Doc_Outbound_Config_ID()))
.tableId(AdTableId.ofRepoId(record.getAD_Table_ID()))
.docBaseType(DocBaseType.ofNullableCode(record.getDocBaseType()))
.printFormatId(PrintFormatId.ofRepoIdOrNull(record.getAD_PrintFormat_ID()))
.ccPath(record.getCCPath())
.isDirectProcessQueueItem(record.isDirectProcessQueueItem())
.isDirectEnqueue(record.isDirectEnqueue())
.isAutoSendDocument(record.isAutoSendDocument())
.orgId(OrgId.ofRepoId(record.getAD_Org_ID()))
.build();
}
@NonNull
public ImmutableSet<AdTableId> getDistinctConfigTableIds()
{
return getDocOutboundConfigMap().getTableIds();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\config\DocOutboundConfigRepository.java | 2 |
请完成以下Java代码 | public void setA_Proceeds (BigDecimal A_Proceeds)
{
set_Value (COLUMNNAME_A_Proceeds, A_Proceeds);
}
/** Get A_Proceeds.
@return A_Proceeds */
public BigDecimal getA_Proceeds ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Proceeds);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_C_Period getC_Period() throws RuntimeException
{
return (I_C_Period)MTable.get(getCtx(), I_C_Period.Table_Name)
.getPO(getC_Period_ID(), get_TrxName()); }
/** Set Period.
@param C_Period_ID
Period of the Calendar
*/
public void setC_Period_ID (int C_Period_ID)
{
if (C_Period_ID < 1)
set_Value (COLUMNNAME_C_Period_ID, null);
else
set_Value (COLUMNNAME_C_Period_ID, Integer.valueOf(C_Period_ID));
}
/** Get Period.
@return Period of the Calendar
*/
public int getC_Period_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_Period_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Account Date.
@param DateAcct
Accounting Date
*/
public void setDateAcct (Timestamp DateAcct)
{
set_Value (COLUMNNAME_DateAcct, DateAcct);
}
/** Get Account Date.
@return Accounting Date
*/
public Timestamp getDateAcct ()
{
return (Timestamp)get_Value(COLUMNNAME_DateAcct);
}
/** Set Document Date.
@param DateDoc
Date of the Document
*/
public void setDateDoc (Timestamp DateDoc)
{
set_Value (COLUMNNAME_DateDoc, DateDoc);
}
/** Get Document Date.
@return Date of the Document
*/
public Timestamp getDateDoc ()
{
return (Timestamp)get_Value(COLUMNNAME_DateDoc);
}
/** Set Processed.
@param Processed
The document has been processed
*/
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); | }
/** Get Processed.
@return The document has been processed
*/
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Disposed.java | 1 |
请完成以下Java代码 | protected void validateParams(String userId, String groupId, String type, String taskId) {
if (taskId == null) {
throw new FlowableIllegalArgumentException("taskId is null");
}
if (type == null) {
throw new FlowableIllegalArgumentException("type is required when adding a new task identity link");
}
// Special treatment for assignee and owner: group cannot be used and userId may be null
if (IdentityLinkType.ASSIGNEE.equals(type) || IdentityLinkType.OWNER.equals(type)) {
if (groupId != null) {
throw new FlowableIllegalArgumentException("Incompatible usage: cannot use type '" + type + "' together with a groupId");
}
} else {
if (userId == null && groupId == null) {
throw new FlowableIllegalArgumentException("userId and groupId cannot both be null");
}
}
} | @Override
protected Void execute(CommandContext commandContext, TaskEntity task) {
CmmnEngineConfiguration cmmnEngineConfiguration = CommandContextUtil.getCmmnEngineConfiguration(commandContext);
if (IdentityLinkType.ASSIGNEE.equals(type)) {
TaskHelper.changeTaskAssignee(task, null, cmmnEngineConfiguration);
} else if (IdentityLinkType.OWNER.equals(type)) {
TaskHelper.changeTaskOwner(task, null, cmmnEngineConfiguration);
} else {
IdentityLinkUtil.deleteTaskIdentityLinks(task, userId, groupId, type, cmmnEngineConfiguration);
}
return null;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\cmd\DeleteIdentityLinkCmd.java | 1 |
请完成以下Java代码 | public class MDistributionRun extends X_M_DistributionRun
{
/**
*
*/
private static final long serialVersionUID = -4355723603388382287L;
/**
* Standard Constructor
* @param ctx context
* @param M_DistributionRun_ID id
* @param trxName transaction
*/
public MDistributionRun (Properties ctx, int M_DistributionRun_ID, String trxName)
{
super (ctx, M_DistributionRun_ID, trxName);
} // MDistributionRun
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MDistributionRun (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MDistributionRun
/** Cached Lines */
private MDistributionRunLine[] m_lines = null;
/**
* Get active, non zero lines
* @param reload true if reload
* @return lines
*/
public MDistributionRunLine[] getLines (boolean reload)
{ | if (!reload && m_lines != null) {
set_TrxName(m_lines, get_TrxName());
return m_lines;
}
//
String sql = "SELECT * FROM M_DistributionRunLine "
+ "WHERE M_DistributionRun_ID=? AND IsActive='Y' AND TotalQty IS NOT NULL AND TotalQty<> 0 ORDER BY Line";
ArrayList<MDistributionRunLine> list = new ArrayList<MDistributionRunLine>();
PreparedStatement pstmt = null;
try
{
pstmt = DB.prepareStatement (sql, get_TrxName());
pstmt.setInt (1, getM_DistributionRun_ID());
ResultSet rs = pstmt.executeQuery ();
while (rs.next ())
list.add (new MDistributionRunLine(getCtx(), rs, get_TrxName()));
rs.close ();
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
log.error(sql, e);
}
try
{
if (pstmt != null)
pstmt.close ();
pstmt = null;
}
catch (Exception e)
{
pstmt = null;
}
m_lines = new MDistributionRunLine[list.size()];
list.toArray (m_lines);
return m_lines;
} // getLines
} // MDistributionRun | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MDistributionRun.java | 1 |
请完成以下Java代码 | public void setMessage(String[] messageParts) {
StringBuilder stringBuilder = new StringBuilder();
for (String part : messageParts) {
if (part != null) {
stringBuilder.append(part.replace(MESSAGE_PARTS_MARKER, " | "));
stringBuilder.append(MESSAGE_PARTS_MARKER);
} else {
stringBuilder.append("null");
stringBuilder.append(MESSAGE_PARTS_MARKER);
}
}
for (int i = 0; i < MESSAGE_PARTS_MARKER.length(); i++) {
stringBuilder.deleteCharAt(stringBuilder.length() - 1);
}
message = stringBuilder.toString();
}
public List<String> getMessageParts() {
if (message == null) {
return null;
}
List<String> messageParts = new ArrayList<String>();
String[] parts = MESSAGE_PARTS_MARKER_REGEX.split(message);
for (String part : parts) {
if ("null".equals(part)) {
messageParts.add(null);
} else {
messageParts.add(part);
}
}
return messageParts;
}
// getters and setters
// //////////////////////////////////////////////////////
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) { | this.taskId = taskId;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getFullMessage() {
return fullMessage;
}
public void setFullMessage(String fullMessage) {
this.fullMessage = fullMessage;
}
public String getAction() {
return action;
}
public void setAction(String action) {
this.action = action;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\CommentEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PersonProperties implements Serializable {
private String name;
private int age;
private String sex = "M";
public PersonProperties() {
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age; | }
public void setAge(int age) {
this.age = age;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
} | repos\springboot-demo-master\xxx-spring-boot-starter\src\main\java\com\et\starter\PersonProperties.java | 2 |
请完成以下Java代码 | public class Bpmn20NamespaceContext implements NamespaceContext {
public static final String BPMN = "bpmn";
public static final String BPMNDI = "bpmndi";
public static final String OMGDC = "omgdc";
public static final String OMGDI = "omgdi";
/**
* This is a protected filed so you can extend that context with your own namespaces if necessary
*/
protected Map<String, String> namespaceUris = new HashMap<String, String>();
public Bpmn20NamespaceContext() {
namespaceUris.put(BPMN, "http://www.omg.org/spec/BPMN/20100524/MODEL");
namespaceUris.put(BPMNDI, "http://www.omg.org/spec/BPMN/20100524/DI");
namespaceUris.put(OMGDC, "http://www.omg.org/spec/DD/20100524/DI");
namespaceUris.put(OMGDI, "http://www.omg.org/spec/DD/20100524/DC");
}
public String getNamespaceURI(String prefix) {
return namespaceUris.get(prefix);
}
public String getPrefix(String namespaceURI) {
return getKeyByValue(namespaceUris, namespaceURI);
}
public Iterator<String> getPrefixes(String namespaceURI) {
return getKeysByValue(namespaceUris, namespaceURI).iterator(); | }
private static <T, E> Set<T> getKeysByValue(Map<T, E> map, E value) {
Set<T> keys = new HashSet<T>();
for (Entry<T, E> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
keys.add(entry.getKey());
}
}
return keys;
}
private static <T, E> T getKeyByValue(Map<T, E> map, E value) {
for (Entry<T, E> entry : map.entrySet()) {
if (value.equals(entry.getValue())) {
return entry.getKey();
}
}
return null;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\diagram\Bpmn20NamespaceContext.java | 1 |
请完成以下Java代码 | public BigDecimal getLowOrderAmount() {
return lowOrderAmount;
}
public void setLowOrderAmount(BigDecimal lowOrderAmount) {
this.lowOrderAmount = lowOrderAmount;
}
public Integer getMaxPointPerOrder() {
return maxPointPerOrder;
}
public void setMaxPointPerOrder(Integer maxPointPerOrder) {
this.maxPointPerOrder = maxPointPerOrder;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type; | }
@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(", continueSignDay=").append(continueSignDay);
sb.append(", continueSignPoint=").append(continueSignPoint);
sb.append(", consumePerPoint=").append(consumePerPoint);
sb.append(", lowOrderAmount=").append(lowOrderAmount);
sb.append(", maxPointPerOrder=").append(maxPointPerOrder);
sb.append(", type=").append(type);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberRuleSetting.java | 1 |
请完成以下Java代码 | public class SetBenchMark {
@State(Scope.Thread)
public static class MyState {
//Set<Employee> employeeSet = new HashSet<>();
LinkedHashSet<Employee> employeeSet = new LinkedHashSet<>();
//ConcurrentSkipListSet<Employee> employeeSet = new ConcurrentSkipListSet <>();
// TreeSet
long iterations = 1000;
Employee employee = new Employee(100L, "Harry");
@Setup(Level.Trial)
public void setUp() {
for (long i = 0; i < iterations; i++) {
employeeSet.add(new Employee(i, "John"));
}
//employeeSet.add(employee);
}
}
@Benchmark
public boolean testAdd(MyState state) {
return state.employeeSet.add(state.employee);
}
@Benchmark
public Boolean testContains(MyState state) {
return state.employeeSet.contains(state.employee);
} | @Benchmark
public boolean testRemove(MyState state) {
return state.employeeSet.remove(state.employee);
}
public static void main(String[] args) throws Exception {
Options options = new OptionsBuilder()
.include(SetBenchMark.class.getSimpleName()).threads(1)
.forks(1).shouldFailOnError(true)
.shouldDoGC(true)
.jvmArgs("-server").build();
new Runner(options).run();
}
} | repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\performance\SetBenchMark.java | 1 |
请完成以下Java代码 | public class CompensateEventDefinitionImpl extends EventDefinitionImpl implements CompensateEventDefinition {
protected static Attribute<Boolean> waitForCompletionAttribute;
protected static AttributeReference<Activity> activityRefAttribute;
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CompensateEventDefinition.class, BPMN_ELEMENT_COMPENSATE_EVENT_DEFINITION)
.namespaceUri(BPMN20_NS)
.extendsType(EventDefinition.class)
.instanceProvider(new ModelTypeInstanceProvider<CompensateEventDefinition>() {
public CompensateEventDefinition newInstance(ModelTypeInstanceContext instanceContext) {
return new CompensateEventDefinitionImpl(instanceContext);
}
});
waitForCompletionAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_WAIT_FOR_COMPLETION)
.build();
activityRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ACTIVITY_REF)
.qNameAttributeReference(Activity.class)
.build();
typeBuilder.build();
} | public CompensateEventDefinitionImpl(ModelTypeInstanceContext context) {
super(context);
}
public boolean isWaitForCompletion() {
return waitForCompletionAttribute.getValue(this);
}
public void setWaitForCompletion(boolean isWaitForCompletion) {
waitForCompletionAttribute.setValue(this, isWaitForCompletion);
}
public Activity getActivity() {
return activityRefAttribute.getReferenceTargetElement(this);
}
public void setActivity(Activity activity) {
activityRefAttribute.setReferenceTargetElement(this, activity);
}
} | repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\CompensateEventDefinitionImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private WFProcess processWFActivity(
@NonNull final UserId invokerId,
@NonNull final WFProcessId wfProcessId,
@NonNull final WFActivityId wfActivityId,
@NonNull final BiFunction<WFProcess, WFActivity, WFProcess> processor)
{
return changeWFProcessById(
wfProcessId,
wfProcess -> {
wfProcess.assertHasAccess(invokerId);
final WFActivity wfActivity = wfProcess.getActivityById(wfActivityId);
WFProcess wfProcessChanged = processor.apply(wfProcess, wfActivity);
if (!Objects.equals(wfProcess, wfProcessChanged))
{
wfProcessChanged = withUpdatedActivityStatuses(wfProcessChanged);
}
return wfProcessChanged;
});
}
private WFProcess withUpdatedActivityStatuses(@NonNull final WFProcess wfProcess) | {
WFProcess wfProcessChanged = wfProcess;
for (final WFActivity wfActivity : wfProcess.getActivities())
{
final WFActivityStatus newActivityStatus = wfActivityHandlersRegistry
.getHandler(wfActivity.getWfActivityType())
.computeActivityState(wfProcessChanged, wfActivity);
wfProcessChanged = wfProcessChanged.withChangedActivityStatus(wfActivity.getId(), newActivityStatus);
}
return wfProcessChanged;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\service\WorkflowRestAPIService.java | 2 |
请完成以下Java代码 | public void init(IInfoSimple parent, I_AD_InfoColumn infoColumn, String searchText)
{
this.parent = parent;
this.infoColumn = infoColumn;
}
@Override
public I_AD_InfoColumn getAD_InfoColumn()
{
return infoColumn;
}
@Override
public String getLabel(int index)
{
return Msg.translate(Env.getCtx(), "SponsorNo");
}
@Override
public int getParameterCount()
{
return 1;
}
@Override
public Object getParameterToComponent(int index)
{
return null;
}
@Override
public Object getParameterValue(int index, boolean returnValueTo)
{
if (index == 0)
return getText();
else
return null;
}
@Override
public String[] getWhereClauses(List<Object> params)
{
final SponsorNoObject sno = getSponsorNoObject(); | final String searchText = getText();
if (sno == null && !Check.isEmpty(searchText, true))
return new String[]{"1=2"};
if (sno == null)
return null;
final Timestamp date = TimeUtil.trunc(Env.getContextAsDate(Env.getCtx(), "#Date"), TimeUtil.TRUNC_DAY);
//
final String whereClause = "EXISTS (SELECT 1 FROM C_Sponsor_Salesrep ssr"
+ " JOIN C_Sponsor sp ON (ssr.C_Sponsor_ID = sp.C_Sponsor_ID)"
+ " WHERE " + bpartnerTableAlias + ".C_BPartner_ID = sp.C_BPartner_ID"
+ " AND ssr.C_Sponsor_Parent_ID = ?"
+ ")"
+ " AND ? BETWEEN ssr.Validfrom AND Validto"
+ " AND ssr.C_BPartner_ID > 0";
params.add(sno.getSponsorID());
params.add(date);
return new String[]{whereClause};
}
public IInfoSimple getParent()
{
return parent;
}
protected abstract SponsorNoObject getSponsorNoObject();
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\apps\search\InfoQueryCriteriaBPSonsorAbstract.java | 1 |
请完成以下Java代码 | public void addActionListener(final ActionListener listener)
{
} // addActionListener
@Override
public void actionPerformed(final ActionEvent e)
{
try
{
if (e.getSource() == m_button)
{
actionButton();
}
}
catch (final Exception ex)
{
Services.get(IClientUI.class).error(attributeContext.getWindowNo(), ex);
}
} // actionPerformed
private void actionButton()
{
if (!m_button.isEnabled())
{
return;
}
throw new UnsupportedOperationException();
}
@Override
public void propertyChange(final PropertyChangeEvent evt)
{
final String propertyName = evt.getPropertyName();
if (propertyName.equals(org.compiere.model.GridField.PROPERTY))
{
setValue(evt.getNewValue());
}
else if (propertyName.equals(org.compiere.model.GridField.REQUEST_FOCUS)) | {
requestFocus();
}
}
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public void addMouseListener(final MouseListener l)
{
m_text.addMouseListener(l);
}
} // VPAttribute | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VPAttribute.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper("memoizing")
.addValue(delegate)
.add("keyFunction", keyFunction)
.toString();
}
@Override
public R apply(final T input)
{
return values.computeIfAbsent(keyFunction.apply(input), k -> delegate.apply(input));
}
@Override
public R peek(final T input)
{
return values.get(keyFunction.apply(input));
}
@Override
public void forget()
{
values.clear();
}
}
private static class MemoizingLastCallFunction<T, R, K> implements MemoizingFunction<T, R>
{
private final Function<T, R> delegate;
private final Function<T, K> keyFunction;
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private transient volatile K lastKey;
private transient R lastValue;
private MemoizingLastCallFunction(final Function<T, R> delegate, final Function<T, K> keyFunction)
{
Check.assumeNotNull(delegate, "Parameter function is not null");
Check.assumeNotNull(keyFunction, "Parameter keyFunction is not null");
this.delegate = delegate;
this.keyFunction = keyFunction;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper("memoizing-last-call")
.addValue(delegate)
.toString();
}
@Override
public R apply(final T input)
{
final K key = keyFunction.apply(input);
lock.readLock().lock();
boolean readLockAcquired = true;
boolean writeLockAcquired = false;
try
{
if (Objects.equals(lastKey, key))
{
return lastValue;
}
// Upgrade to write lock
lock.readLock().unlock(); // must release read lock before acquiring write lock
readLockAcquired = false;
lock.writeLock().lock();
writeLockAcquired = true;
try
{
lastValue = delegate.apply(input);
lastKey = key;
return lastValue;
} | finally
{
// Downgrade to read lock
lock.readLock().lock(); // acquire read lock before releasing write lock
readLockAcquired = true;
lock.writeLock().unlock(); // unlock write, still hold read
writeLockAcquired = false;
}
}
finally
{
if (writeLockAcquired)
{
lock.writeLock().unlock();
}
if (readLockAcquired)
{
lock.readLock().unlock();
}
}
}
@Override
public R peek(final T input)
{
final ReadLock readLock = lock.readLock();
readLock.lock();
try
{
return lastValue;
}
finally
{
readLock.unlock();
}
}
@Override
public void forget()
{
final WriteLock writeLock = lock.writeLock();
writeLock.lock();
try
{
lastKey = null;
lastValue = null;
}
finally
{
writeLock.unlock();
}
}
}
private static final class SimpleMemoizingFunction<T, R> extends MemoizingFunctionWithKeyExtractor<T, R, T>
{
private SimpleMemoizingFunction(final Function<T, R> delegate)
{
super(delegate, input -> input);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Functions.java | 1 |
请完成以下Java代码 | public String prepareTable(ColumnInfo[] layout, String from, String where, boolean multiSelection, String tableName)
{
for (int i = 0; i < layout.length; i++)
{
if (layout[i].getColClass() == IDColumn.class)
{
idColumnIndex = i;
break;
}
}
sql = super.prepareTable(layout, from, where, multiSelection, tableName);
return sql;
}
public String getSQL()
{
return sql;
}
public void prepareTable(Class<?> cl, String[] columnNames, String sqlWhere, String sqlOrderBy)
{
ColumnInfo[] layout = MiniTableUtil.createColumnInfo(cl, columnNames);
String tableName = MiniTableUtil.getTableName(cl);
String from = tableName;
final boolean multiSelection = false;
prepareTable(layout, from, sqlWhere, multiSelection, tableName);
if (!Check.isEmpty(sqlOrderBy, true))
{
sql += " ORDER BY " + sqlOrderBy;
}
}
public void loadData(Object... sqlParams)
{
if (sql == null)
throw new IllegalStateException("Table not initialized. Please use prepareTable method first");
int selectedId = getSelectedId();
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{
pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
DB.setParameters(pstmt, sqlParams);
rs = pstmt.executeQuery();
this.loadTable(rs);
}
catch (Exception e)
{
log.error(sql, e);
}
finally
{
DB.close(rs, pstmt);
rs = null;
pstmt = null;
}
selectById(selectedId);
}
public int getSelectedId()
{
if (idColumnIndex < 0)
return -1;
int row = getSelectedRow();
if (row != -1)
{
Object data = getModel().getValueAt(row, 0);
if (data != null)
{
Integer id = ((IDColumn)data).getRecord_ID();
return id == null ? -1 : id.intValue();
}
}
return -1;
} | public void selectById(int id)
{
selectById(id, true);
}
public void selectById(int id, boolean fireEvent)
{
if (idColumnIndex < 0)
return;
boolean fireSelectionEventOld = fireSelectionEvent;
try
{
fireSelectionEvent = fireEvent;
if (id < 0)
{
this.getSelectionModel().removeSelectionInterval(0, this.getRowCount());
return;
}
for (int i = 0; i < this.getRowCount(); i++)
{
IDColumn key = (IDColumn)this.getModel().getValueAt(i, idColumnIndex);
if (key != null && id > 0 && key.getRecord_ID() == id)
{
this.getSelectionModel().setSelectionInterval(i, i);
break;
}
}
}
finally
{
fireSelectionEvent = fireSelectionEventOld;
}
}
private boolean fireSelectionEvent = true;
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\adempiere\ui\swing\MiniTable2.java | 1 |
请完成以下Java代码 | public String DropShipPartner(final ICalloutField calloutField)
{
if (calloutField.isRecordCopyingMode())
{
// 05291: In case current record is on dataNew phase with Copy option set
// then just don't update the DropShip fields, take them as they were copied
return NO_ERROR;
}
final I_C_Order order = calloutField.getModel(I_C_Order.class);
if (order.isSOTrx())
{
if (order.isDropShip())
{
OrderDocumentLocationAdapterFactory
.deliveryLocationAdapter(order)
.setFrom(OrderDocumentLocationAdapterFactory
.locationAdapter(order)
.toDocumentLocation());
}
else
{
OrderDocumentLocationAdapterFactory
.deliveryLocationAdapter(order)
.setFrom(DocumentLocation.EMPTY);
}
}
else
{
if (!order.isDropShip())
{
final I_AD_Org org = Services.get(IOrgDAO.class).getById(order.getAD_Org_ID());
final I_C_BPartner linkedBPartner = Services.get(IBPartnerOrgBL.class).retrieveLinkedBPartner(org);
if (null != linkedBPartner)
{
order.setDropShip_BPartner_ID(linkedBPartner.getC_BPartner_ID());
}
final WarehouseId warehouseId = WarehouseId.ofRepoIdOrNull(order.getM_Warehouse_ID());
if (warehouseId != null)
{
final I_M_Warehouse warehouse = Services.get(IWarehouseDAO.class).getById(warehouseId);
final BPartnerId warehouseBPartnerId = BPartnerId.ofRepoIdOrNull(warehouse.getC_BPartner_ID());
OrderDocumentLocationAdapterFactory
.deliveryLocationAdapter(order)
.setFrom(DocumentLocation.builder()
.bpartnerId(warehouseBPartnerId)
.bpartnerLocationId(BPartnerLocationId.ofRepoIdOrNull(warehouseBPartnerId, warehouse.getC_BPartner_Location_ID()))
.locationId(LocationId.ofRepoIdOrNull(warehouse.getC_Location_ID())) | .build());
}
order.setDropShip_User_ID(-1);
}
}
return NO_ERROR;
}
private static boolean isEnforcePriceLimit(final I_C_OrderLine orderLine, final boolean isSOTrx)
{
// We enforce PriceLimit only for sales orders
if (!isSOTrx)
{
return false;
}
return orderLine.isEnforcePriceLimit();
}
public String attributeSetInstance(final ICalloutField calloutField)
{
// 05118 : Also update the prices
final I_C_OrderLine orderLine = calloutField.getModel(I_C_OrderLine.class);
Services.get(IOrderLineBL.class).updatePrices(orderLine);
return NO_ERROR;
}
} // CalloutOrder | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\CalloutOrder.java | 1 |
请完成以下Java代码 | public static ContextPath root(@NonNull final DocumentEntityDescriptor entityDescriptor)
{
return new ContextPath(ImmutableList.of(ContextPathElement.ofNameAndId(
extractName(entityDescriptor),
entityDescriptor.getWindowId().toInt())
));
}
static String extractName(final @NonNull DocumentEntityDescriptor entityDescriptor)
{
final String tableName = entityDescriptor.getTableNameOrNull();
return tableName != null ? tableName : entityDescriptor.getInternalName();
}
@Override
public String toString() {return toJson();}
@JsonValue
public String toJson()
{
String json = this._json;
if (json == null)
{
json = this._json = computeJson();
}
return json;
}
private String computeJson()
{
return elements.stream()
.map(ContextPathElement::toJson)
.collect(Collectors.joining("."));
}
public ContextPath newChild(@NonNull final String name)
{
return newChild(ContextPathElement.ofName(name));
}
public ContextPath newChild(@NonNull final DocumentEntityDescriptor entityDescriptor)
{
return newChild(ContextPathElement.ofNameAndId(
extractName(entityDescriptor),
AdTabId.toRepoId(entityDescriptor.getAdTabIdOrNull())
));
}
private ContextPath newChild(@NonNull final ContextPathElement element)
{
return new ContextPath(ImmutableList.<ContextPathElement>builder()
.addAll(elements)
.add(element)
.build());
}
public AdWindowId getAdWindowId()
{
return AdWindowId.ofRepoId(elements.get(0).getId());
}
@Override
public int compareTo(@NonNull final ContextPath other)
{
return toJson().compareTo(other.toJson());
}
}
@Value | class ContextPathElement
{
@NonNull String name;
int id;
@JsonCreator
public static ContextPathElement ofJson(@NonNull final String json)
{
try
{
final int idx = json.indexOf("/");
if (idx > 0)
{
String name = json.substring(0, idx);
int id = Integer.parseInt(json.substring(idx + 1));
return new ContextPathElement(name, id);
}
else
{
return new ContextPathElement(json, -1);
}
}
catch (final Exception ex)
{
throw new AdempiereException("Failed parsing: " + json, ex);
}
}
public static ContextPathElement ofName(@NonNull final String name) {return new ContextPathElement(name, -1);}
public static ContextPathElement ofNameAndId(@NonNull final String name, final int id) {return new ContextPathElement(name, id > 0 ? id : -1);}
@Override
public String toString() {return toJson();}
@JsonValue
public String toJson() {return id > 0 ? name + "/" + id : name;}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextPath.java | 1 |
请完成以下Java代码 | public Object call() throws Exception
{
try
{
final Object result = proceed();
return result == null ? NullResult : result;
}
catch (Exception e)
{
throw e;
}
catch (Throwable e)
{
Throwables.propagateIfPossible(e);
throw Throwables.propagate(e);
}
}
@Override | public Object getTarget()
{
return target;
}
@Override
public Object[] getParameters()
{
return methodArgs;
}
@Override
public Method getMethod()
{
return method;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\proxy\impl\InvocationContext.java | 1 |
请完成以下Java代码 | public boolean equals(Object obj) {
if (obj instanceof Bindings) {
Bindings other = (Bindings) obj;
return (
Arrays.equals(functions, other.functions) &&
Arrays.equals(variables, other.variables) &&
converter.equals(other.converter)
);
}
return false;
}
@Override
public int hashCode() {
return (Arrays.hashCode(functions) ^ Arrays.hashCode(variables) ^ converter.hashCode());
}
private void writeObject(ObjectOutputStream out) throws IOException, ClassNotFoundException {
out.defaultWriteObject();
MethodWrapper[] wrappers = new MethodWrapper[functions.length]; | for (int i = 0; i < wrappers.length; i++) {
wrappers[i] = new MethodWrapper(functions[i]);
}
out.writeObject(wrappers);
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.defaultReadObject();
MethodWrapper[] wrappers = (MethodWrapper[]) in.readObject();
if (wrappers.length == 0) {
functions = NO_FUNCTIONS;
} else {
functions = new Method[wrappers.length];
for (int i = 0; i < functions.length; i++) {
functions[i] = wrappers[i].method;
}
}
}
} | repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\Bindings.java | 1 |
请完成以下Java代码 | private void load0(String trxName) throws ParserConfigurationException, SAXException, IOException
{
this.objects = new ArrayList<Object>();
final IXMLHandlerFactory factory = Services.get(IXMLHandlerFactory.class);
final DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setIgnoringElementContentWhitespace(true);
final DocumentBuilder builder = dbf.newDocumentBuilder();
final InputSource source = getInputSource();
final Document doc = builder.parse(source);
final NodeList nodes = doc.getDocumentElement().getChildNodes();
for (int i = 0; i < nodes.getLength(); i++)
{
if (!(nodes.item(i) instanceof Element))
{
continue;
}
final Element element = (Element)nodes.item(i);
final String name = element.getLocalName();
final Class<Object> beanClass = factory.getBeanClassByNodeName(name);
if (beanClass == null)
{
addLog("Error: node is not handled: " + name);
continue;
}
final IXMLHandler<Object> converter = factory.getHandler(beanClass);
final Object bean = InterfaceWrapperHelper.create(ctx, beanClass, trxName);
if (converter.fromXmlNode(bean, element))
{
InterfaceWrapperHelper.save(bean); // make sure is saved
objects.add(bean);
}
} | }
private InputSource getInputSource()
{
if (fileName != null)
{
return new InputSource(fileName);
}
else if (inputStream != null)
{
return new InputSource(inputStream);
}
else
{
throw new AdempiereException("Cannot identify source");
}
}
private void addLog(String msg)
{
logger.info(msg);
}
public List<Object> getObjects()
{
if (objects == null)
{
return new ArrayList<Object>();
}
return new ArrayList<Object>(this.objects);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\xml\XMLLoader.java | 1 |
请完成以下Java代码 | public PlanItemTransition getStandardEvent() {
PlanItemTransitionStandardEvent child = standardEventChild.getChild(this);
return child.getValue();
}
public void setStandardEvent(PlanItemTransition standardEvent) {
PlanItemTransitionStandardEvent child = standardEventChild.getChild(this);
child.setValue(standardEvent);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItemStartTrigger.class, CMMN_ELEMENT_PLAN_ITEM_START_TRIGGER)
.extendsType(StartTrigger.class)
.namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<PlanItemStartTrigger>() {
public PlanItemStartTrigger newInstance(ModelTypeInstanceContext instanceContext) { | return new PlanItemStartTriggerImpl(instanceContext);
}
});
sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF)
.idAttributeReference(PlanItem.class)
.build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
standardEventChild = sequenceBuilder.element(PlanItemTransitionStandardEvent.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemStartTriggerImpl.java | 1 |
请完成以下Java代码 | public class FunctionalJavaIOMain {
public static IO<Unit> printLetters(final String s) {
return () -> {
for (int i = 0; i < s.length(); i++) {
System.out.println(s.charAt(i));
}
return Unit.unit();
};
}
public static void main(String[] args) {
F<String, IO<Unit>> printLetters = i -> printLetters(i);
IO<Unit> lowerCase = IOFunctions.stdoutPrintln("What's your first Name ?");
IO<Unit> input = IOFunctions.stdoutPrint("First Name: ");
IO<Unit> userInput = IOFunctions.append(lowerCase, input); | IO<String> readInput = IOFunctions.stdinReadLine();
F<String, String> toUpperCase = i -> i.toUpperCase();
F<String, IO<Unit>> transformInput = F1Functions.<String, IO<Unit>, String> o(printLetters).f(toUpperCase);
IO<Unit> readAndPrintResult = IOFunctions.bind(readInput, transformInput);
IO<Unit> program = IOFunctions.bind(userInput, nothing -> readAndPrintResult);
IOFunctions.toSafe(program).run();
}
} | repos\tutorials-master\libraries-6\src\main\java\com\baeldung\fj\FunctionalJavaIOMain.java | 1 |
请完成以下Java代码 | public HistoricProcessInstanceQueryDto getHistoricProcessInstanceQuery() {
return historicProcessInstanceQuery;
}
public void setHistoricProcessInstanceQuery(HistoricProcessInstanceQueryDto historicProcessInstanceQuery) {
this.historicProcessInstanceQuery = historicProcessInstanceQuery;
}
public boolean isHierarchical() {
return hierarchical;
}
public void setHierarchical(boolean hierarchical) {
this.hierarchical = hierarchical;
}
public boolean isUpdateInChunks() { | return updateInChunks;
}
public void setUpdateInChunks(boolean updateInChunks) {
this.updateInChunks = updateInChunks;
}
public Integer getUpdateChunkSize() {
return updateChunkSize;
}
public void setUpdateChunkSize(Integer updateChunkSize) {
this.updateChunkSize = updateChunkSize;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\batch\removaltime\SetRemovalTimeToHistoricProcessInstancesDto.java | 1 |
请完成以下Java代码 | public static DelegateExecution getMultiInstanceRootExecution(ExecutionEntity execution) {
ExecutionEntity multiInstanceRootExecution = null;
ExecutionEntity currentExecution = execution;
while (currentExecution != null && multiInstanceRootExecution == null && currentExecution.getParentId() != null) {
if (currentExecution.isMultiInstanceRoot()) {
multiInstanceRootExecution = currentExecution;
} else {
currentExecution = currentExecution.getParent();
}
}
return multiInstanceRootExecution;
}
public static DelegateExecution getParentInstanceExecutionInMultiInstance(ExecutionEntity execution) {
ExecutionEntity instanceExecution = null;
ExecutionEntity currentExecution = execution;
while (currentExecution != null && instanceExecution == null && currentExecution.getParentId() != null) {
if (currentExecution.getParent().isMultiInstanceRoot()) {
instanceExecution = currentExecution;
} else {
currentExecution = currentExecution.getParent();
}
}
return instanceExecution;
}
/**
* Returns the list of boundary event activity ids that are in the the process model,
* associated with the current activity of the passed execution.
* Note that no check if made here whether this an active child execution for those boundary events.
*/
public static List<String> getBoundaryEventActivityIds(DelegateExecution execution) {
Process process = ProcessDefinitionUtil.getProcess(execution.getProcessDefinitionId());
String activityId = execution.getCurrentActivityId();
if (StringUtils.isNotEmpty(activityId)) { | List<String> boundaryEventActivityIds = new ArrayList<>();
List<BoundaryEvent> boundaryEvents = process.findFlowElementsOfType(BoundaryEvent.class, true);
for (BoundaryEvent boundaryEvent : boundaryEvents) {
if (activityId.equals(boundaryEvent.getAttachedToRefId())) {
boundaryEventActivityIds.add(boundaryEvent.getId());
}
}
return boundaryEventActivityIds;
} else {
return Collections.emptyList();
}
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\ExecutionGraphUtil.java | 1 |
请完成以下Java代码 | private Action createPackAllAction()
{
//TODO: localization
BoundAction action = new BoundAction("Size All Column", PACK_ALL_COMMAND);
action.setLongDescription("Size all column to fit content");
action.registerCallback(this, "packAll");
return action;
}
/**
* Size all column to fit content.
*
* @see #PACK_ALL_COMMAND
*/
public void packAll()
{
autoSize(true);
}
/** Logger */
private static final transient Logger log = LogManager.getLogger(VTable.class);
/**
* Property Change Listener for CurrentRow.
* - Selects the current row if not already selected
* - Required when navigating via Buttons
* @param evt event
*/
@Override
public void propertyChange(PropertyChangeEvent evt)
{
if (evt.getPropertyName().equals(GridTab.PROPERTY))
{
final int row = ((Integer)evt.getNewValue()).intValue();
final int selRow = getSelectedRow();
if (row == selRow)
return;
setRowSelectionInterval(row,row);
setColumnSelectionInterval(0, 0);
Rectangle cellRect = getCellRect(row, 0, false);
if (cellRect != null)
scrollRectToVisible(cellRect);
}
} // propertyChange
@Override
protected CTableModelRowSorter createModelRowSorter()
{
return new CTableModelRowSorter(this)
{
@Override
protected void sort (final int modelColumnIndex)
{
final int rows = getRowCount();
if (rows <= 0)
return;
//
final TableModel model = getModel();
if (!(model instanceof GridTable))
{
super.sort(modelColumnIndex);
return;
}
final GridTable gridTable = (GridTable)model; | sorting = true;
try
{
// other sort columns
final boolean sortAscending = addToSortColumnsAndRemoveOtherColumns(modelColumnIndex);
gridTable.sort(modelColumnIndex, sortAscending);
}
finally
{
sorting = false;
}
// table model fires "Sorted" DataStatus event which causes MTab to position to row 0
} // sort
};
}
/**
* Transfer focus explicitly to editor due to editors with multiple components
*
* @param row row
* @param column column
* @param e event
* @return true if cell is editing
*/
@Override
public boolean editCellAt (int row, int column, java.util.EventObject e)
{
if (!super.editCellAt(row, column, e))
return false;
// log.debug( "VTable.editCellAt", "r=" + row + ", c=" + column);
Object ed = getCellEditor();
if (ed instanceof VEditor)
((Component)ed).requestFocus();
else if (ed instanceof VCellEditor)
{
ed = ((VCellEditor)ed).getEditor();
((Component)ed).requestFocus();
}
return true;
} // editCellAt
/**
* toString
* @return String representation
*/
@Override
public String toString()
{
return new StringBuilder("VTable[")
.append(getModel()).append("]").toString();
} // toString
} // VTable | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\VTable.java | 1 |
请完成以下Java代码 | public int getGL_BudgetControl_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_BudgetControl_ID);
if (ii == null)
return 0;
return ii.intValue();
}
public I_GL_Budget getGL_Budget() throws RuntimeException
{
return (I_GL_Budget)MTable.get(getCtx(), I_GL_Budget.Table_Name)
.getPO(getGL_Budget_ID(), get_TrxName()); }
/** Set Budget.
@param GL_Budget_ID
General Ledger Budget
*/
public void setGL_Budget_ID (int GL_Budget_ID)
{
if (GL_Budget_ID < 1)
set_Value (COLUMNNAME_GL_Budget_ID, null);
else
set_Value (COLUMNNAME_GL_Budget_ID, Integer.valueOf(GL_Budget_ID));
}
/** Get Budget.
@return General Ledger Budget
*/
public int getGL_Budget_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_Budget_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Comment/Help.
@param Help
Comment or Hint
*/
public void setHelp (String Help)
{
set_Value (COLUMNNAME_Help, Help);
}
/** Get Comment/Help.
@return Comment or Hint
*/
public String getHelp ()
{
return (String)get_Value(COLUMNNAME_Help);
}
/** Set Before Approval. | @param IsBeforeApproval
The Check is before the (manual) approval
*/
public void setIsBeforeApproval (boolean IsBeforeApproval)
{
set_Value (COLUMNNAME_IsBeforeApproval, Boolean.valueOf(IsBeforeApproval));
}
/** Get Before Approval.
@return The Check is before the (manual) approval
*/
public boolean isBeforeApproval ()
{
Object oo = get_Value(COLUMNNAME_IsBeforeApproval);
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_GL_BudgetControl.java | 1 |
请完成以下Java代码 | public abstract class EntitiesExportCtx<R extends VersionCreateRequest> {
protected final User user;
protected final CommitGitRequest commit;
protected final R request;
private final List<ListenableFuture<Void>> futures;
private final Map<EntityId, EntityId> externalIdMap;
public EntitiesExportCtx(User user, CommitGitRequest commit, R request) {
this.user = user;
this.commit = commit;
this.request = request;
this.futures = new ArrayList<>();
this.externalIdMap = new HashMap<>();
}
protected <T extends R> EntitiesExportCtx(EntitiesExportCtx<T> other) {
this.user = other.getUser();
this.commit = other.getCommit();
this.request = other.getRequest();
this.futures = other.getFutures();
this.externalIdMap = other.getExternalIdMap();
}
public void add(ListenableFuture<Void> future) {
futures.add(future);
}
public TenantId getTenantId() {
return user.getTenantId();
}
protected static EntityExportSettings buildExportSettings(VersionCreateConfig config) {
return EntityExportSettings.builder()
.exportRelations(config.isSaveRelations())
.exportAttributes(config.isSaveAttributes())
.exportCredentials(config.isSaveCredentials())
.exportCalculatedFields(config.isSaveCalculatedFields())
.build(); | }
public abstract EntityExportSettings getSettings();
@SuppressWarnings("unchecked")
public <ID extends EntityId> ID getExternalId(ID internalId) {
var result = externalIdMap.get(internalId);
log.debug("[{}][{}] Local cache {} for id", internalId.getEntityType(), internalId.getId(), result != null ? "hit" : "miss");
return (ID) result;
}
public void putExternalId(EntityId internalId, EntityId externalId) {
log.debug("[{}][{}] Local cache put: {}", internalId.getEntityType(), internalId.getId(), externalId);
externalIdMap.put(internalId, externalId != null ? externalId : internalId);
}
} | repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\sync\vc\data\EntitiesExportCtx.java | 1 |
请完成以下Java代码 | private static Chain initChain(ExecutionGraphQlService service, List<RSocketGraphQlInterceptor> interceptors) {
Chain endOfChain = (request) -> service.execute(request).map(RSocketGraphQlResponse::new);
return interceptors.isEmpty() ? endOfChain :
interceptors.stream()
.reduce(RSocketGraphQlInterceptor::andThen)
.map((interceptor) -> interceptor.apply(endOfChain))
.orElse(endOfChain);
}
/**
* Handle a {@code Request-Response} interaction. For queries and mutations.
* @param payload the decoded GraphQL request payload
*/
public Mono<Map<String, Object>> handle(Map<String, Object> payload) {
return handleInternal(payload).map(ExecutionGraphQlResponse::toMap);
}
/**
* Handle a {@code Request-Stream} interaction. For subscriptions.
* @param payload the decoded GraphQL request payload
*/
public Flux<Map<String, Object>> handleSubscription(Map<String, Object> payload) {
return handleInternal(payload)
.flatMapMany((response) -> {
if (response.getData() instanceof Publisher) {
Publisher<ExecutionResult> publisher = response.getData();
return Flux.from(publisher).map(ExecutionResult::toSpecification);
}
else if (response.isValid()) {
return Flux.error(new InvalidException(
"Expected a Publisher for a subscription operation. " +
"This is either a server error or the operation is not a subscription"));
}
String errorData = encodeErrors(response).toString(StandardCharsets.UTF_8); | return Flux.error(new RejectedException(errorData));
});
}
private Mono<RSocketGraphQlResponse> handleInternal(Map<String, Object> payload) {
String requestId = this.idGenerator.generateId().toString();
return this.executionChain.next(new RSocketGraphQlRequest(payload, requestId, null));
}
@SuppressWarnings("unchecked")
private DataBuffer encodeErrors(RSocketGraphQlResponse response) {
return ((Encoder<List<GraphQLError>>) this.jsonEncoder).encodeValue(
response.getExecutionResult().getErrors(),
DefaultDataBufferFactory.sharedInstance, LIST_TYPE, MimeTypeUtils.APPLICATION_JSON, null);
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\GraphQlRSocketHandler.java | 1 |
请完成以下Java代码 | public abstract class BasePageDataIterable<T> implements Iterable<T>, Iterator<T> {
private final int fetchSize;
private List<T> currentItems;
private int currentIdx;
private boolean hasNextPack;
private PageLink nextPackLink;
private boolean initialized;
public BasePageDataIterable(int fetchSize) {
super();
this.fetchSize = fetchSize;
}
@Override
public Iterator<T> iterator() {
return this;
}
@Override
public boolean hasNext() {
if (!initialized) {
fetch(new PageLink(fetchSize));
initialized = true;
}
if (currentIdx == currentItems.size()) { | if (hasNextPack) {
fetch(nextPackLink);
}
}
return currentIdx < currentItems.size();
}
@Override
public T next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
return currentItems.get(currentIdx++);
}
private void fetch(PageLink link) {
PageData<T> pageData = fetchPageData(link);
currentIdx = 0;
currentItems = pageData != null ? pageData.getData() : new ArrayList<>();
hasNextPack = pageData != null && pageData.hasNext();
nextPackLink = link.nextPageLink();
}
abstract PageData<T> fetchPageData(PageLink link);
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\page\BasePageDataIterable.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class IncidentRestService extends AbstractPluginResource {
public final static String PATH = "/incident";
public IncidentRestService(String engineName) {
super(engineName);
}
@GET
@Produces(MediaType.APPLICATION_JSON)
public List<IncidentDto> getIncidents(@Context UriInfo uriInfo,
@QueryParam("firstResult") Integer firstResult,
@QueryParam("maxResults") Integer maxResults) {
IncidentQueryDto queryParameter = new IncidentQueryDto(uriInfo.getQueryParameters());
return queryIncidents(queryParameter, firstResult, maxResults);
}
@POST
@Produces(MediaType.APPLICATION_JSON)
@Consumes(MediaType.APPLICATION_JSON)
public List<IncidentDto> queryIncidents(IncidentQueryDto queryParameter,
@QueryParam("firstResult") Integer firstResult,
@QueryParam("maxResults") Integer maxResults) {
paginateQueryParameters(queryParameter, firstResult, maxResults);
configureExecutionQuery(queryParameter);
List<IncidentDto> matchingIncidents = getQueryService().executeQuery("selectIncidentWithCauseAndRootCauseIncidents", queryParameter);
return matchingIncidents;
}
private void paginateQueryParameters(IncidentQueryDto queryParameter, Integer firstResult, Integer maxResults) {
if (firstResult == null) {
firstResult = 0;
}
if (maxResults == null) {
maxResults = Integer.MAX_VALUE;
}
queryParameter.setFirstResult(firstResult);
queryParameter.setMaxResults(maxResults);
}
@GET
@Path("/count")
@Produces(MediaType.APPLICATION_JSON)
public CountResultDto getIncidentsCount(@Context UriInfo uriInfo) {
IncidentQueryDto queryParameter = new IncidentQueryDto(uriInfo.getQueryParameters()); | return queryIncidentsCount(queryParameter);
}
@POST
@Path("/count")
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.APPLICATION_JSON)
public CountResultDto queryIncidentsCount(IncidentQueryDto queryParameter) {
CountResultDto result = new CountResultDto();
configureExecutionQuery(queryParameter);
long count = getQueryService().executeQueryRowCount("selectIncidentWithCauseAndRootCauseIncidentsCount", queryParameter);
result.setCount(count);
return result;
}
protected void configureExecutionQuery(IncidentQueryDto query) {
configureAuthorizationCheck(query);
configureTenantCheck(query);
addPermissionCheck(query, PROCESS_INSTANCE, "RES.PROC_INST_ID_", READ);
addPermissionCheck(query, PROCESS_DEFINITION, "PROCDEF.KEY_", READ_INSTANCE);
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\resources\IncidentRestService.java | 2 |
请完成以下Java代码 | public abstract class AclFormattingUtils {
public static String demergePatterns(String original, String removeBits) {
Assert.notNull(original, "Original string required");
Assert.notNull(removeBits, "Bits To Remove string required");
Assert.isTrue(original.length() == removeBits.length(),
"Original and Bits To Remove strings must be identical length");
char[] replacement = new char[original.length()];
for (int i = 0; i < original.length(); i++) {
if (removeBits.charAt(i) == Permission.RESERVED_OFF) {
replacement[i] = original.charAt(i);
}
else {
replacement[i] = Permission.RESERVED_OFF;
}
}
return new String(replacement);
}
public static String mergePatterns(String original, String extraBits) {
Assert.notNull(original, "Original string required");
Assert.notNull(extraBits, "Extra Bits string required");
Assert.isTrue(original.length() == extraBits.length(),
"Original and Extra Bits strings must be identical length");
char[] replacement = new char[extraBits.length()];
for (int i = 0; i < extraBits.length(); i++) {
if (extraBits.charAt(i) == Permission.RESERVED_OFF) {
replacement[i] = original.charAt(i);
}
else {
replacement[i] = extraBits.charAt(i);
}
}
return new String(replacement);
}
/**
* Returns a representation of the active bits in the presented mask, with each active
* bit being denoted by character '*'.
* <p>
* Inactive bits will be denoted by character {@link Permission#RESERVED_OFF}.
* @param i the integer bit mask to print the active bits for
* @return a 32-character representation of the bit mask
*/
public static String printBinary(int i) {
return printBinary(i, '*', Permission.RESERVED_OFF);
} | /**
* Returns a representation of the active bits in the presented mask, with each active
* bit being denoted by the passed character.
* <p>
* Inactive bits will be denoted by character {@link Permission#RESERVED_OFF}.
* @param mask the integer bit mask to print the active bits for
* @param code the character to print when an active bit is detected
* @return a 32-character representation of the bit mask
*/
public static String printBinary(int mask, char code) {
Assert.doesNotContain(Character.toString(code), Character.toString(Permission.RESERVED_ON),
() -> Permission.RESERVED_ON + " is a reserved character code");
Assert.doesNotContain(Character.toString(code), Character.toString(Permission.RESERVED_OFF),
() -> Permission.RESERVED_OFF + " is a reserved character code");
return printBinary(mask, Permission.RESERVED_ON, Permission.RESERVED_OFF).replace(Permission.RESERVED_ON, code);
}
private static String printBinary(int i, char on, char off) {
String s = Integer.toBinaryString(i);
String pattern = Permission.THIRTY_TWO_RESERVED_OFF;
String temp2 = pattern.substring(0, pattern.length() - s.length()) + s;
return temp2.replace('0', off).replace('1', on);
}
} | repos\spring-security-main\acl\src\main\java\org\springframework\security\acls\domain\AclFormattingUtils.java | 1 |
请完成以下Java代码 | public ActivityInstanceDto[] getChildActivityInstances() {
return childActivityInstances;
}
public TransitionInstanceDto[] getChildTransitionInstances() {
return childTransitionInstances;
}
/** the list of executions that are currently waiting in this activity instance */
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 |
请完成以下Java代码 | public List<String> shortcutFieldOrder() {
return Collections.singletonList("host");
}
@Override
public GatewayFilter apply(Config config) {
return new GatewayFilter() {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
String value = ServerWebExchangeUtils.expand(exchange, config.getHost());
ServerHttpRequest request = exchange.getRequest().mutate().headers(httpHeaders -> {
httpHeaders.remove("Host");
httpHeaders.add("Host", value);
}).build();
// Make sure the header we just set is preserved
exchange.getAttributes().put(PRESERVE_HOST_HEADER_ATTRIBUTE, true);
return chain.filter(exchange.mutate().request(request).build());
}
@Override
public String toString() {
String host = config.getHost();
return filterToStringCreator(SetRequestHostHeaderGatewayFilterFactory.this)
.append(host != null ? host : "") | .toString();
}
};
}
public static class Config {
private @Nullable String host;
public @Nullable String getHost() {
return host;
}
public void setHost(String host) {
this.host = host;
}
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\SetRequestHostHeaderGatewayFilterFactory.java | 1 |
请完成以下Java代码 | public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Time based.
@param IsTimeBased
Time based Revenue Recognition rather than Service Level based
*/
public void setIsTimeBased (boolean IsTimeBased)
{
set_Value (COLUMNNAME_IsTimeBased, Boolean.valueOf(IsTimeBased));
}
/** Get Time based.
@return Time based Revenue Recognition rather than Service Level based
*/
public boolean isTimeBased ()
{
Object oo = get_Value(COLUMNNAME_IsTimeBased);
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()); | }
/** Set Number of Months.
@param NoMonths Number of Months */
public void setNoMonths (int NoMonths)
{
set_Value (COLUMNNAME_NoMonths, Integer.valueOf(NoMonths));
}
/** Get Number of Months.
@return Number of Months */
public int getNoMonths ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_NoMonths);
if (ii == null)
return 0;
return ii.intValue();
}
/** RecognitionFrequency AD_Reference_ID=196 */
public static final int RECOGNITIONFREQUENCY_AD_Reference_ID=196;
/** Month = M */
public static final String RECOGNITIONFREQUENCY_Month = "M";
/** Quarter = Q */
public static final String RECOGNITIONFREQUENCY_Quarter = "Q";
/** Year = Y */
public static final String RECOGNITIONFREQUENCY_Year = "Y";
/** Set Recognition frequency.
@param RecognitionFrequency Recognition frequency */
public void setRecognitionFrequency (String RecognitionFrequency)
{
set_Value (COLUMNNAME_RecognitionFrequency, RecognitionFrequency);
}
/** Get Recognition frequency.
@return Recognition frequency */
public String getRecognitionFrequency ()
{
return (String)get_Value(COLUMNNAME_RecognitionFrequency);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_RevenueRecognition.java | 1 |
请完成以下Java代码 | private static String getLocationFieldNameForBPartnerField(final String bpartnerFieldName)
{
switch (bpartnerFieldName)
{
case I_C_Order.COLUMNNAME_C_BPartner_ID:
return I_C_Order.COLUMNNAME_C_BPartner_Location_ID;
case I_C_Order.COLUMNNAME_Bill_BPartner_ID:
return I_C_Order.COLUMNNAME_Bill_Location_ID;
case I_C_Order.COLUMNNAME_DropShip_BPartner_ID:
return I_C_Order.COLUMNNAME_DropShip_Location_ID;
case I_C_Order.COLUMNNAME_Pay_BPartner_ID:
return I_C_Order.COLUMNNAME_Pay_Location_ID;
default:
return null;
}
} | @Nullable
private static String getUserIdFieldNameForBPartnerField(final String bpartnerFieldName)
{
switch (bpartnerFieldName)
{
case I_C_Order.COLUMNNAME_C_BPartner_ID:
return I_C_Order.COLUMNNAME_AD_User_ID;
case I_C_Order.COLUMNNAME_Bill_BPartner_ID:
return I_C_Order.COLUMNNAME_Bill_User_ID;
case I_C_Order.COLUMNNAME_DropShip_BPartner_ID:
return I_C_Order.COLUMNNAME_DropShip_User_ID;
default:
return null;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\AdvancedSearchBPartnerProcessor.java | 1 |
请完成以下Java代码 | public void addEmptyHUListener(@NonNull final EmptyHUListener emptyHUListener)
{
emptyHUListeners.add(emptyHUListener);
}
@Override
public List<EmptyHUListener> getEmptyHUListeners()
{
return ImmutableList.copyOf(emptyHUListeners);
}
@Override
public void flush()
{
final IAttributeStorageFactory attributesStorageFactory = _attributesStorageFactory;
if(attributesStorageFactory != null)
{
attributesStorageFactory.flush();
}
}
@Override
public IAutoCloseable temporarilyDontDestroyHU(@NonNull final HuId huId)
{
huIdsToNotDestroy.add(huId);
return () -> huIdsToNotDestroy.remove(huId); | }
@Override
public boolean isDontDestroyHu(@NonNull final HuId huId)
{
return huIdsToNotDestroy.contains(huId);
}
@Override
public boolean isPropertyTrue(@NonNull final String propertyName)
{
final Boolean isPropertyTrue = getProperty(propertyName);
return isPropertyTrue != null && isPropertyTrue;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\MutableHUContext.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public List<HistoricIdentityLinkEntity> findHistoricIdentityLinksByScopeIdAndScopeType(String scopeId, String scopeType) {
return dataManager.findHistoricIdentityLinksByScopeIdAndScopeType(scopeId, scopeType);
}
@Override
public List<HistoricIdentityLinkEntity> findHistoricIdentityLinksBySubScopeIdAndScopeType(String subScopeId, String scopeType) {
return dataManager.findHistoricIdentityLinksBySubScopeIdAndScopeType(subScopeId, scopeType);
}
@Override
public void deleteHistoricIdentityLinksByTaskId(String taskId) {
List<HistoricIdentityLinkEntity> identityLinks = findHistoricIdentityLinksByTaskId(taskId);
for (HistoricIdentityLinkEntity identityLink : identityLinks) {
delete(identityLink);
}
}
@Override
public void deleteHistoricIdentityLinksByProcInstance(String processInstanceId) {
List<HistoricIdentityLinkEntity> identityLinks = dataManager
.findHistoricIdentityLinksByProcessInstanceId(processInstanceId);
for (HistoricIdentityLinkEntity identityLink : identityLinks) {
delete(identityLink);
}
}
@Override
public void deleteHistoricIdentityLinksByScopeIdAndScopeType(String scopeId, String scopeType) {
dataManager.deleteHistoricIdentityLinksByScopeIdAndType(scopeId, scopeType);
}
@Override
public void deleteHistoricIdentityLinksByScopeDefinitionIdAndScopeType(String scopeDefinitionId, String scopeType) {
dataManager.deleteHistoricIdentityLinksByScopeDefinitionIdAndType(scopeDefinitionId, scopeType);
}
@Override
public void bulkDeleteHistoricIdentityLinksForProcessInstanceIds(Collection<String> processInstanceIds) {
dataManager.bulkDeleteHistoricIdentityLinksForProcessInstanceIds(processInstanceIds);
} | @Override
public void bulkDeleteHistoricIdentityLinksForTaskIds(Collection<String> taskIds) {
dataManager.bulkDeleteHistoricIdentityLinksForTaskIds(taskIds);
}
@Override
public void bulkDeleteHistoricIdentityLinksForScopeIdsAndScopeType(Collection<String> scopeIds, String scopeType) {
dataManager.bulkDeleteHistoricIdentityLinksForScopeIdsAndScopeType(scopeIds, scopeType);
}
@Override
public void deleteHistoricProcessIdentityLinksForNonExistingInstances() {
dataManager.deleteHistoricProcessIdentityLinksForNonExistingInstances();
}
@Override
public void deleteHistoricCaseIdentityLinksForNonExistingInstances() {
dataManager.deleteHistoricCaseIdentityLinksForNonExistingInstances();
}
@Override
public void deleteHistoricTaskIdentityLinksForNonExistingInstances() {
dataManager.deleteHistoricTaskIdentityLinksForNonExistingInstances();
}
} | repos\flowable-engine-main\modules\flowable-identitylink-service\src\main\java\org\flowable\identitylink\service\impl\persistence\entity\HistoricIdentityLinkEntityManagerImpl.java | 2 |
请完成以下Java代码 | public static void inOperator() {
Bson filter = in("userName", "Jack", "Lisa");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void notInOperator() {
Bson filter = nin("userName", "Jack", "Lisa");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void andOperator() {
Bson filter = and(gt("age", 25), eq("role", "Admin"));
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void orOperator() {
Bson filter = or(gt("age", 30), eq("role", "Admin"));
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void existsOperator() {
Bson filter = exists("type");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
public static void regexOperator() {
Bson filter = regex("userName", "a");
FindIterable<Document> documents = collection.find(filter);
printResult(documents);
}
private static void printResult(FindIterable<Document> documents) {
MongoCursor<Document> cursor = documents.iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} | public static void main(String args[]) {
setUp();
equalsOperator();
notEqualOperator();
greaterThanOperator();
lessThanOperator();
inOperator();
notInOperator();
andOperator();
orOperator();
existsOperator();
regexOperator();
}
} | repos\tutorials-master\persistence-modules\java-mongodb\src\main\java\com\baeldung\mongo\filter\FilterOperation.java | 1 |
请完成以下Java代码 | public class Author {
@Id
private final Long id;
private final String name;
private final Set<Book> books;
public Author(Long id, String name, Set<Book> books) {
this.id = id;
this.name = name;
this.books = books;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public Set<Book> getBooks() {
return books;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} | if (o == null || getClass() != o.getClass()) {
return false;
}
Author author = (Author) o;
return Objects.equals(id, author.id) && Objects.equals(name, author.name)
&& Objects.equals(books, author.books);
}
@Override
public int hashCode() {
return Objects.hash(id, name, books);
}
@Override
public String toString() {
return "Author{" + "name='" + name + '\'' + '}';
}
} | repos\spring-data-examples-main\jdbc\graalvm-native\src\main\java\example\springdata\jdbc\graalvmnative\model\Author.java | 1 |
请完成以下Java代码 | public void setDateDoc (Timestamp DateDoc)
{
set_Value (COLUMNNAME_DateDoc, DateDoc);
}
/** Get Document Date.
@return Date of the Document
*/
public Timestamp getDateDoc ()
{
return (Timestamp)get_Value(COLUMNNAME_DateDoc);
}
public I_GL_JournalBatch getGL_JournalBatch() throws RuntimeException
{
return (I_GL_JournalBatch)MTable.get(getCtx(), I_GL_JournalBatch.Table_Name)
.getPO(getGL_JournalBatch_ID(), get_TrxName()); }
/** Set Journal Batch.
@param GL_JournalBatch_ID | General Ledger Journal Batch
*/
public void setGL_JournalBatch_ID (int GL_JournalBatch_ID)
{
if (GL_JournalBatch_ID < 1)
set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, null);
else
set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, Integer.valueOf(GL_JournalBatch_ID));
}
/** Get Journal Batch.
@return General Ledger Journal Batch
*/
public int getGL_JournalBatch_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_GL_JournalBatch_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Recurring_Run.java | 1 |
请完成以下Java代码 | private Mono<?> postFilter(EvaluationContext ctx, Object result, ExpressionAttribute attribute) {
return ReactiveExpressionUtils.evaluateAsBoolean(attribute.getExpression(), ctx)
.flatMap((granted) -> granted ? Mono.just(result) : Mono.empty());
}
@Override
public Pointcut getPointcut() {
return this.pointcut;
}
@Override
public Advice getAdvice() {
return this;
} | @Override
public boolean isPerInstance() {
return true;
}
@Override
public int getOrder() {
return this.order;
}
public void setOrder(int order) {
this.order = order;
}
} | repos\spring-security-main\core\src\main\java\org\springframework\security\authorization\method\PostFilterAuthorizationReactiveMethodInterceptor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setCollectDate(Date collectDate) {
this.collectDate = collectDate;
}
/**
* 汇总类型(参考枚举:SettDailyCollectTypeEnum)
*
* @return
*/
public String getCollectType() {
return collectType;
}
/**
* 汇总类型(参考枚举:SettDailyCollectTypeEnum)
*
* @param collectType
*/
public void setCollectType(String collectType) {
this.collectType = collectType;
}
/**
* 结算批次号(结算之后再回写过来)
*
* @return
*/
public String getBatchNo() {
return batchNo;
}
/**
* 结算批次号(结算之后再回写过来)
*
* @param batchNo
*/
public void setBatchNo(String batchNo) {
this.batchNo = batchNo == null ? null : batchNo.trim();
}
/**
* 交易总金额
*
* @return
*/
public BigDecimal getTotalAmount() {
return totalAmount;
}
/**
* 交易总金额
*
* @param totalAmount
*/
public void setTotalAmount(BigDecimal totalAmount) {
this.totalAmount = totalAmount;
} | /**
* 交易总笔数
*
* @return
*/
public Integer getTotalCount() {
return totalCount;
}
/**
* 交易总笔数
*
* @param totalCount
*/
public void setTotalCount(Integer totalCount) {
this.totalCount = totalCount;
}
/**
* 结算状态(参考枚举:SettDailyCollectStatusEnum)
*
* @return
*/
public String getSettStatus() {
return settStatus;
}
/**
* 结算状态(参考枚举:SettDailyCollectStatusEnum)
*
* @param settStatus
*/
public void setSettStatus(String settStatus) {
this.settStatus = settStatus;
}
/**
* 风险预存期
*/
public Integer getRiskDay() {
return riskDay;
}
/**
* 风险预存期
*/
public void setRiskDay(Integer riskDay) {
this.riskDay = riskDay;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\account\entity\RpSettDailyCollect.java | 2 |
请完成以下Java代码 | protected final Context context() {
return this.context;
}
/**
* Attaches the authentication context before the actual call.
*
* <p>
* This method is called after the grpc context is attached.
* </p>
*/
protected abstract void attachAuthenticationContext();
/**
* Detaches the authentication context after the actual call.
*
* <p>
* This method is called before the grpc context is detached.
* </p>
*/
protected abstract void detachAuthenticationContext();
@Override
public void onMessage(final ReqT message) {
final Context previous = this.context.attach();
try {
attachAuthenticationContext();
log.debug("onMessage - Authentication set");
super.onMessage(message);
} finally {
detachAuthenticationContext();
this.context.detach(previous);
log.debug("onMessage - Authentication cleared");
}
}
@Override
public void onHalfClose() {
final Context previous = this.context.attach();
try {
attachAuthenticationContext();
log.debug("onHalfClose - Authentication set");
super.onHalfClose();
} finally {
detachAuthenticationContext();
this.context.detach(previous);
log.debug("onHalfClose - Authentication cleared");
}
}
@Override
public void onCancel() {
final Context previous = this.context.attach();
try {
attachAuthenticationContext();
log.debug("onCancel - Authentication set");
super.onCancel(); | } finally {
detachAuthenticationContext();
log.debug("onCancel - Authentication cleared");
this.context.detach(previous);
}
}
@Override
public void onComplete() {
final Context previous = this.context.attach();
try {
attachAuthenticationContext();
log.debug("onComplete - Authentication set");
super.onComplete();
} finally {
detachAuthenticationContext();
log.debug("onComplete - Authentication cleared");
this.context.detach(previous);
}
}
@Override
public void onReady() {
final Context previous = this.context.attach();
try {
attachAuthenticationContext();
log.debug("onReady - Authentication set");
super.onReady();
} finally {
detachAuthenticationContext();
log.debug("onReady - Authentication cleared");
this.context.detach(previous);
}
}
} | repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\interceptors\AbstractAuthenticatingServerCallListener.java | 1 |
请完成以下Java代码 | public Integer getPriviledgeMemberPrice() {
return priviledgeMemberPrice;
}
public void setPriviledgeMemberPrice(Integer priviledgeMemberPrice) {
this.priviledgeMemberPrice = priviledgeMemberPrice;
}
public Integer getPriviledgeBirthday() {
return priviledgeBirthday;
}
public void setPriviledgeBirthday(Integer priviledgeBirthday) {
this.priviledgeBirthday = priviledgeBirthday;
}
public String getNote() {
return note;
}
public void setNote(String note) {
this.note = note;
}
@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(", name=").append(name);
sb.append(", growthPoint=").append(growthPoint); | sb.append(", defaultStatus=").append(defaultStatus);
sb.append(", freeFreightPoint=").append(freeFreightPoint);
sb.append(", commentGrowthPoint=").append(commentGrowthPoint);
sb.append(", priviledgeFreeFreight=").append(priviledgeFreeFreight);
sb.append(", priviledgeSignIn=").append(priviledgeSignIn);
sb.append(", priviledgeComment=").append(priviledgeComment);
sb.append(", priviledgePromotion=").append(priviledgePromotion);
sb.append(", priviledgeMemberPrice=").append(priviledgeMemberPrice);
sb.append(", priviledgeBirthday=").append(priviledgeBirthday);
sb.append(", note=").append(note);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberLevel.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public int create(UmsResource umsResource) {
umsResource.setCreateTime(new Date());
return resourceMapper.insert(umsResource);
}
@Override
public int update(Long id, UmsResource umsResource) {
umsResource.setId(id);
int count = resourceMapper.updateByPrimaryKeySelective(umsResource);
adminCacheService.delResourceListByResource(id);
return count;
}
@Override
public UmsResource getItem(Long id) {
return resourceMapper.selectByPrimaryKey(id);
}
@Override
public int delete(Long id) {
int count = resourceMapper.deleteByPrimaryKey(id);
adminCacheService.delResourceListByResource(id);
return count; | }
@Override
public List<UmsResource> list(Long categoryId, String nameKeyword, String urlKeyword, Integer pageSize, Integer pageNum) {
PageHelper.startPage(pageNum,pageSize);
UmsResourceExample example = new UmsResourceExample();
UmsResourceExample.Criteria criteria = example.createCriteria();
if(categoryId!=null){
criteria.andCategoryIdEqualTo(categoryId);
}
if(StrUtil.isNotEmpty(nameKeyword)){
criteria.andNameLike('%'+nameKeyword+'%');
}
if(StrUtil.isNotEmpty(urlKeyword)){
criteria.andUrlLike('%'+urlKeyword+'%');
}
return resourceMapper.selectByExample(example);
}
@Override
public List<UmsResource> listAll() {
return resourceMapper.selectByExample(new UmsResourceExample());
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\UmsResourceServiceImpl.java | 2 |
请完成以下Java代码 | public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) {
return Optional.ofNullable(findAssetProfileById(tenantId, new AssetProfileId(entityId.getId())));
}
@Override
public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) {
return FluentFuture.from(assetProfileDao.findByIdAsync(tenantId, entityId.getId()))
.transform(Optional::ofNullable, directExecutor());
}
@Override
public EntityType getEntityType() {
return EntityType.ASSET_PROFILE;
}
@Override
public List<EntityInfo> findAssetProfileNamesByTenantId(TenantId tenantId, boolean activeOnly) {
log.trace("Executing findAssetProfileNamesByTenantId, tenantId [{}]", tenantId);
validateId(tenantId, id -> INCORRECT_TENANT_ID + id);
return assetProfileDao.findTenantAssetProfileNames(tenantId.getId(), activeOnly)
.stream().sorted(Comparator.comparing(EntityInfo::getName))
.collect(Collectors.toList());
}
@Override
public List<AssetProfileInfo> findAssetProfilesByIds(TenantId tenantId, List<AssetProfileId> assetProfileIds) {
log.trace("Executing findAssetProfilesByIds, tenantId [{}], assetProfileIds [{}]", tenantId, assetProfileIds);
return assetProfileDao.findAssetProfilesByTenantIdAndIds(tenantId.getId(), toUUIDs(assetProfileIds));
}
private final PaginatedRemover<TenantId, AssetProfile> tenantAssetProfilesRemover = | new PaginatedRemover<>() {
@Override
protected PageData<AssetProfile> findEntities(TenantId tenantId, TenantId id, PageLink pageLink) {
return assetProfileDao.findAssetProfiles(id, pageLink);
}
@Override
protected void removeEntity(TenantId tenantId, AssetProfile entity) {
removeAssetProfile(tenantId, entity);
}
};
private AssetProfileInfo toAssetProfileInfo(AssetProfile profile) {
return profile == null ? null : new AssetProfileInfo(profile.getId(), profile.getTenantId(), profile.getName(), profile.getImage(),
profile.getDefaultDashboardId());
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\asset\AssetProfileServiceImpl.java | 1 |
请完成以下Java代码 | protected void addPartitions(QueueKey queueKey, Set<TopicPartitionInfo> partitions, RestoreCallback callback) {
Map<String, Long> eventsStartOffsets = eventsStartOffsetsProvider != null ? eventsStartOffsetsProvider.get() : null; // remembering the offsets before subscribing to states
Set<TopicPartitionInfo> statePartitions = withTopic(partitions, stateConsumer.getTopic());
partitionsInProgress.addAll(statePartitions);
stateConsumer.addPartitions(statePartitions, statePartition -> {
var readLock = partitionsLock.readLock();
readLock.lock();
try {
partitionsInProgress.remove(statePartition);
log.info("Finished partition {} (still in progress: {})", statePartition, partitionsInProgress);
if (callback != null) {
callback.onPartitionRestored(statePartition);
}
if (partitionsInProgress.isEmpty()) {
log.info("All partitions processed");
if (callback != null) {
callback.onAllPartitionsRestored();
}
}
TopicPartitionInfo eventPartition = statePartition.withTopic(eventConsumer.getTopic());
if (this.partitions.get(queueKey).contains(eventPartition)) {
eventConsumer.addPartitions(Set.of(eventPartition), null, eventsStartOffsets != null ? eventsStartOffsets::get : null);
for (PartitionedQueueConsumerManager<?> consumer : otherConsumers) {
consumer.addPartitions(Set.of(statePartition.withTopic(consumer.getTopic())));
}
}
} finally {
readLock.unlock();
} | }, null);
}
@Override
protected void removePartitions(QueueKey queueKey, Set<TopicPartitionInfo> partitions) {
super.removePartitions(queueKey, partitions);
stateConsumer.removePartitions(withTopic(partitions, stateConsumer.getTopic()));
}
@Override
protected void deletePartitions(Set<TopicPartitionInfo> partitions) {
super.deletePartitions(partitions);
stateConsumer.delete(withTopic(partitions, stateConsumer.getTopic()));
}
@Override
public void stop() {
super.stop();
stateConsumer.stop();
stateConsumer.awaitStop();
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\state\KafkaQueueStateService.java | 1 |
请完成以下Java代码 | public boolean isSelfService ()
{
Object oo = get_Value(COLUMNNAME_IsSelfService);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** 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);
}
/** Set Preis.
@param Price
Price
*/
@Override
public void setPrice (java.math.BigDecimal Price)
{
set_Value (COLUMNNAME_Price, Price);
}
/** Get Preis.
@return Price
*/
@Override
public java.math.BigDecimal getPrice ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Price);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Verarbeitet.
@param Processed
Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public void setProcessed (boolean Processed)
{
set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed));
}
/** Get Verarbeitet.
@return Checkbox sagt aus, ob der Beleg verarbeitet wurde.
*/
@Override
public boolean isProcessed ()
{
Object oo = get_Value(COLUMNNAME_Processed);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo); | }
return false;
}
/** Set Verarbeiten.
@param Processing Verarbeiten */
@Override
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Verarbeiten.
@return Verarbeiten */
@Override
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Ranking.
@param Ranking
Relative Rank Number
*/
@Override
public void setRanking (int Ranking)
{
set_Value (COLUMNNAME_Ranking, Integer.valueOf(Ranking));
}
/** Get Ranking.
@return Relative Rank Number
*/
@Override
public int getRanking ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Ranking);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.rfq\src\main\java-gen\de\metas\rfq\model\X_C_RfQResponse.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setPort(int port) {
this.port = port;
}
/**
* Optional root suffix for the embedded LDAP server. Default is
* "dc=springframework,dc=org".
* @param root root suffix for the embedded LDAP server
*/
public void setRoot(String root) {
this.root = root;
}
/**
* Username (DN) of the "manager" user identity (i.e. "uid=admin,ou=system") which
* will be used to authenticate to an LDAP server. If omitted, anonymous access will
* be used.
* @param managerDn the username (DN) of the "manager" user identity used to
* authenticate to a LDAP server.
*/
public void setManagerDn(String managerDn) {
this.managerDn = managerDn;
}
/**
* The password for the manager DN. This is required if the
* {@link #setManagerDn(String)} is specified.
* @param managerPassword password for the manager DN
*/
public void setManagerPassword(String managerPassword) {
this.managerPassword = managerPassword;
}
@Override
public DefaultSpringSecurityContextSource getObject() throws Exception {
if (!unboundIdPresent) {
throw new IllegalStateException("Embedded LDAP server is not provided");
}
this.container = getContainer();
this.port = this.container.getPort();
DefaultSpringSecurityContextSource contextSourceFromProviderUrl = new DefaultSpringSecurityContextSource(
"ldap://127.0.0.1:" + this.port + "/" + this.root);
if (this.managerDn != null) {
contextSourceFromProviderUrl.setUserDn(this.managerDn);
if (this.managerPassword == null) {
throw new IllegalStateException("managerPassword is required if managerDn is supplied");
}
contextSourceFromProviderUrl.setPassword(this.managerPassword);
} | contextSourceFromProviderUrl.afterPropertiesSet();
return contextSourceFromProviderUrl;
}
@Override
public Class<?> getObjectType() {
return DefaultSpringSecurityContextSource.class;
}
@Override
public void destroy() {
if (this.container instanceof Lifecycle) {
((Lifecycle) this.container).stop();
}
}
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
private EmbeddedLdapServerContainer getContainer() {
if (!unboundIdPresent) {
throw new IllegalStateException("Embedded LDAP server is not provided");
}
UnboundIdContainer unboundIdContainer = new UnboundIdContainer(this.root, this.ldif);
unboundIdContainer.setApplicationContext(this.context);
unboundIdContainer.setPort(getEmbeddedServerPort());
unboundIdContainer.afterPropertiesSet();
return unboundIdContainer;
}
private int getEmbeddedServerPort() {
if (this.port == null) {
this.port = getDefaultEmbeddedServerPort();
}
return this.port;
}
private int getDefaultEmbeddedServerPort() {
try (ServerSocket serverSocket = new ServerSocket(DEFAULT_PORT)) {
return serverSocket.getLocalPort();
}
catch (IOException ex) {
return RANDOM_PORT;
}
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\EmbeddedLdapServerContextSourceFactoryBean.java | 2 |
请完成以下Java代码 | public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the issr property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getIssr() {
return issr;
}
/**
* Sets the value of the issr property.
*
* @param value | * allowed object is
* {@link String }
*
*/
public void setIssr(String value) {
this.issr = value;
}
/**
* Gets the value of the schmeNm property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getSchmeNm() {
return schmeNm;
}
/**
* Sets the value of the schmeNm property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setSchmeNm(String value) {
this.schmeNm = 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_04\GenericIdentification20.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getProvince() {
return province;
}
/** 银行卡开户所在省 **/
public void setProvince(String province) {
this.province = province;
}
/** 银行卡开户所在城市 **/
public String getCity() {
return city;
}
/** 银行卡开户所在城市 **/
public void setCity(String city) {
this.city = city;
}
/** 银行卡开户所在区 **/
public String getAreas() {
return areas;
}
/** 银行卡开户所在区 **/
public void setAreas(String areas) {
this.areas = areas;
}
/** 银行卡开户具体地址 **/
public String getStreet() {
return street;
}
/** 银行卡开户具体地址 **/
public void setStreet(String street) {
this.street = street;
}
/** 银行卡开户名eg:张三 **/
public String getBankAccountName() {
return bankAccountName;
}
/** 银行卡开户名eg:张三 **/
public void setBankAccountName(String bankAccountName) {
this.bankAccountName = bankAccountName;
}
/** 银行卡卡号 **/
public String getBankAccountNo() {
return bankAccountNo;
}
/** 银行卡卡号 **/
public void setBankAccountNo(String bankAccountNo) {
this.bankAccountNo = bankAccountNo;
}
/** 银行编号eg:ICBC **/
public String getBankCode() {
return bankCode;
}
/** 银行编号eg:ICBC **/
public void setBankCode(String bankCode) {
this.bankCode = bankCode;
}
/** 银行卡类型 **/
public String getBankAccountType() {
return bankAccountType;
}
/** 银行卡类型 **/
public void setBankAccountType(String bankAccountType) {
this.bankAccountType = bankAccountType;
}
/** 证件类型 **/
public String getCardType() {
return cardType;
} | /** 证件类型 **/
public void setCardType(String cardType) {
this.cardType = cardType;
}
/** 证件号码 **/
public String getCardNo() {
return cardNo;
}
/** 证件号码 **/
public void setCardNo(String cardNo) {
this.cardNo = cardNo;
}
/** 手机号码 **/
public String getMobileNo() {
return mobileNo;
}
/** 手机号码 **/
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
/** 银行名称 **/
public String getBankName() {
return bankName;
}
/** 银行名称 **/
public void setBankName(String bankName) {
this.bankName = bankName;
}
/** 用户编号 **/
public String getUserNo() {
return userNo;
}
/** 用户编号 **/
public void setUserNo(String userNo) {
this.userNo = userNo;
}
/** 是否默认 **/
public String getIsDefault() {
return isDefault;
}
/** 是否默认 **/
public void setIsDefault(String isDefault) {
this.isDefault = isDefault;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\user\entity\RpUserBankAccount.java | 2 |
请完成以下Java代码 | private AdempiereServer[] getInActive()
{
final List<AdempiereServer> list = new ArrayList<>();
for (int i = 0; i < m_servers.size(); i++)
{
final AdempiereServer server = m_servers.get(i);
if (server != null && (!server.isAlive() || !server.isInterrupted()))
{
list.add(server);
}
}
AdempiereServer[] retValue = new AdempiereServer[list.size()];
list.toArray(retValue);
return retValue;
} // getInActive
/**
* Get all Servers
*
* @return array of servers
*/
public AdempiereServer[] getAll()
{
AdempiereServer[] retValue = new AdempiereServer[m_servers.size()];
m_servers.toArray(retValue);
return retValue;
} // getAll
/**
* Get Server with ID
*
* @param serverID server id
* @return server or null
*/
public AdempiereServer getServer(String serverID)
{
if (serverID == null)
return null;
for (int i = 0; i < m_servers.size(); i++)
{
AdempiereServer server = m_servers.get(i);
if (serverID.equals(server.getServerID()))
return server;
}
return null;
} // getServer
/**
* Remove Server with ID
*
* @param serverID server id
*/
public void removeServerWithId(@NonNull final String serverID)
{
int matchedIndex = -1;
for (int i = 0; i < m_servers.size(); i++)
{
final AdempiereServer server = m_servers.get(i);
if (serverID.equals(server.getServerID()))
{
matchedIndex = i;
break;
}
}
if (matchedIndex > -1)
{
m_servers.remove(matchedIndex);
}
}
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder("AdempiereServerMgr[");
sb.append("Servers=").append(m_servers.size())
.append(",ContextSize=").append(_ctx.size())
.append(",Started=").append(m_start)
.append("]");
return sb.toString();
} // toString | /**
* Get Description
*
* @return description
*/
public String getDescription()
{
return "1.4";
} // getDescription
/**
* Get Number Servers
*
* @return no of servers
*/
public String getServerCount()
{
int noRunning = 0;
int noStopped = 0;
for (int i = 0; i < m_servers.size(); i++)
{
AdempiereServer server = m_servers.get(i);
if (server.isAlive())
noRunning++;
else
noStopped++;
}
String info = String.valueOf(m_servers.size())
+ " - Running=" + noRunning
+ " - Stopped=" + noStopped;
return info;
} // getServerCount
/**
* Get start date
*
* @return start date
*/
public Timestamp getStartTime()
{
return new Timestamp(m_start.getTime());
} // getStartTime
} // AdempiereServerMgr | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java-legacy\org\compiere\server\AdempiereServerMgr.java | 1 |
请完成以下Java代码 | public Builder setParameters(@NonNull final Map<String, Object> parameters)
{
parameters.forEach(this::setParameter);
return this;
}
private ImmutableMap<String, Object> getParameters()
{
return parameters != null ? ImmutableMap.copyOf(parameters) : ImmutableMap.of();
}
public Builder applySecurityRestrictions(final boolean applySecurityRestrictions)
{
this.applySecurityRestrictions = applySecurityRestrictions;
return this;
}
private boolean isApplySecurityRestrictions()
{
return applySecurityRestrictions;
}
}
//
//
//
//
//
@ToString
private static final class WrappedDocumentFilterList
{
public static WrappedDocumentFilterList ofFilters(final DocumentFilterList filters)
{
if (filters == null || filters.isEmpty())
{
return EMPTY;
}
final ImmutableList<JSONDocumentFilter> jsonFiltersEffective = null;
return new WrappedDocumentFilterList(jsonFiltersEffective, filters);
}
public static WrappedDocumentFilterList ofJSONFilters(final List<JSONDocumentFilter> jsonFilters)
{
if (jsonFilters == null || jsonFilters.isEmpty())
{
return EMPTY;
}
final ImmutableList<JSONDocumentFilter> jsonFiltersEffective = ImmutableList.copyOf(jsonFilters);
final DocumentFilterList filtersEffective = null;
return new WrappedDocumentFilterList(jsonFiltersEffective, filtersEffective);
}
public static final WrappedDocumentFilterList EMPTY = new WrappedDocumentFilterList();
private final ImmutableList<JSONDocumentFilter> jsonFilters;
private final DocumentFilterList filters;
private WrappedDocumentFilterList(@Nullable final ImmutableList<JSONDocumentFilter> jsonFilters, @Nullable final DocumentFilterList filters)
{ | this.jsonFilters = jsonFilters;
this.filters = filters;
}
/**
* empty constructor
*/
private WrappedDocumentFilterList()
{
filters = DocumentFilterList.EMPTY;
jsonFilters = null;
}
public DocumentFilterList unwrap(final DocumentFilterDescriptorsProvider descriptors)
{
if (filters != null)
{
return filters;
}
if (jsonFilters == null || jsonFilters.isEmpty())
{
return DocumentFilterList.EMPTY;
}
return JSONDocumentFilter.unwrapList(jsonFilters, descriptors);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\CreateViewRequest.java | 1 |
请完成以下Java代码 | public JsonResolveLocatorResponse resolveLocator(@RequestBody @NonNull final JsonResolveLocatorRequest request)
{
assertApplicationAccess();
final LocatorScannedCodeResolverResult result = jobService.resolveLocator(
request.getScannedCode(),
request.getWfProcessId(),
request.getLineId(),
Env.getLoggedUserId()
);
return JsonResolveLocatorResponse.of(result);
}
@PostMapping("/resolveHU")
public JsonResolveHUResponse resolveHU(@RequestBody @NonNull final JsonResolveHURequest request)
{
assertApplicationAccess();
final ResolveHUResponse response = jobService.resolveHU(
ResolveHURequest.builder()
.scannedCode(request.getScannedCode())
.callerId(Env.getLoggedUserId())
.wfProcessId(request.getWfProcessId())
.lineId(request.getLineId())
.locatorId(request.getLocatorQRCode().getLocatorId())
.build()
);
return mappers.newJsonResolveHUResponse(newJsonOpts()).toJson(response);
}
@PostMapping("/count")
public JsonWFProcess reportCounting(@RequestBody @NonNull final JsonCountRequest request)
{
assertApplicationAccess();
final Inventory inventory = jobService.reportCounting(request, Env.getLoggedUserId());
return toJsonWFProcess(inventory);
}
private JsonWFProcess toJsonWFProcess(final Inventory inventory)
{ | return workflowRestController.toJson(WFProcessMapper.toWFProcess(inventory));
}
@GetMapping("/lineHU")
public JsonInventoryLineHU getLineHU(
@RequestParam("wfProcessId") @NonNull String wfProcessIdStr,
@RequestParam("lineId") @NonNull String lineIdStr,
@RequestParam("lineHUId") @NonNull String lineHUIdStr)
{
assertApplicationAccess();
final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr);
final InventoryLineId lineId = InventoryLineId.ofObject(lineIdStr);
final InventoryLineHUId lineHUId = InventoryLineHUId.ofObject(lineHUIdStr);
final InventoryLine line = jobService.getById(wfProcessId, Env.getLoggedUserId()).getLineById(lineId);
return mappers.newJsonInventoryJobMapper(newJsonOpts())
.loadAllDetails(true)
.toJson(line, lineHUId);
}
@GetMapping("/lineHUs")
public JsonGetLineHUsResponse getLineHUs(
@RequestParam("wfProcessId") @NonNull String wfProcessIdStr,
@RequestParam("lineId") @NonNull String lineIdStr)
{
assertApplicationAccess();
final WFProcessId wfProcessId = WFProcessId.ofString(wfProcessIdStr);
final InventoryLineId lineId = InventoryLineId.ofObject(lineIdStr);
final InventoryLine line = jobService.getById(wfProcessId, Env.getLoggedUserId()).getLineById(lineId);
return JsonGetLineHUsResponse.builder()
.wfProcessId(wfProcessId)
.lineId(lineId)
.lineHUs(mappers.newJsonInventoryJobMapper(newJsonOpts()).toJsonInventoryLineHUs(line))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\rest_api\InventoryRestController.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getVersionTag() {
return versionTag;
}
public Integer getHistoryTimeToLive() {
return historyTimeToLive;
}
public boolean isStartableInTasklist() {
return isStartableInTasklist;
}
public static ProcessDefinitionDto fromProcessDefinition(ProcessDefinition definition) {
ProcessDefinitionDto dto = new ProcessDefinitionDto();
dto.id = definition.getId();
dto.key = definition.getKey();
dto.category = definition.getCategory(); | dto.description = definition.getDescription();
dto.name = definition.getName();
dto.version = definition.getVersion();
dto.resource = definition.getResourceName();
dto.deploymentId = definition.getDeploymentId();
dto.diagram = definition.getDiagramResourceName();
dto.suspended = definition.isSuspended();
dto.tenantId = definition.getTenantId();
dto.versionTag = definition.getVersionTag();
dto.historyTimeToLive = definition.getHistoryTimeToLive();
dto.isStartableInTasklist = definition.isStartableInTasklist();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\repository\ProcessDefinitionDto.java | 2 |
请完成以下Java代码 | public String getNormalName() {
return "Entity View";
}
},
WIDGETS_BUNDLE(16),
WIDGET_TYPE(17),
TENANT_PROFILE(20),
DEVICE_PROFILE(21),
ASSET_PROFILE(22),
API_USAGE_STATE(23),
TB_RESOURCE(24, "resource"),
OTA_PACKAGE(25),
EDGE(26),
RPC(27),
QUEUE(28),
NOTIFICATION_TARGET(29),
NOTIFICATION_TEMPLATE(30),
NOTIFICATION_REQUEST(31),
NOTIFICATION(32),
NOTIFICATION_RULE(33),
QUEUE_STATS(34),
OAUTH2_CLIENT(35),
DOMAIN(36),
MOBILE_APP(37),
MOBILE_APP_BUNDLE(38),
CALCULATED_FIELD(39),
// CALCULATED_FIELD_LINK(40), - was removed in 4.3
JOB(41),
ADMIN_SETTINGS(42),
AI_MODEL(43, "ai_model") {
@Override
public String getNormalName() {
return "AI model";
}
},
API_KEY(44);
@Getter
private final int protoNumber; // Corresponds to EntityTypeProto
@Getter
private final String tableName;
@Getter
private final String normalName = StringUtils.capitalize(Strings.CS.removeStart(name(), "TB_")
.toLowerCase().replaceAll("_", " "));
public static final List<String> NORMAL_NAMES = EnumSet.allOf(EntityType.class).stream()
.map(EntityType::getNormalName).toList();
private static final EntityType[] BY_PROTO;
static {
BY_PROTO = new EntityType[Arrays.stream(values()).mapToInt(EntityType::getProtoNumber).max().orElse(0) + 1];
for (EntityType entityType : values()) {
BY_PROTO[entityType.getProtoNumber()] = entityType;
}
}
EntityType(int protoNumber) {
this.protoNumber = protoNumber; | this.tableName = name().toLowerCase();
}
EntityType(int protoNumber, String tableName) {
this.protoNumber = protoNumber;
this.tableName = tableName;
}
public boolean isOneOf(EntityType... types) {
if (types == null) {
return false;
}
for (EntityType type : types) {
if (this == type) {
return true;
}
}
return false;
}
public static EntityType forProtoNumber(int protoNumber) {
if (protoNumber < 0 || protoNumber >= BY_PROTO.length) {
throw new IllegalArgumentException("Invalid EntityType proto number " + protoNumber);
}
return BY_PROTO[protoNumber];
}
} | repos\thingsboard-master\common\data\src\main\java\org\thingsboard\server\common\data\EntityType.java | 1 |
请在Spring Boot框架中完成以下Java代码 | private Optional<I_S_PostgREST_Config> getOptionalConfigRecordFor(@NonNull final OrgId orgId)
{
return cache.getOrLoad(orgId, this::retrieveConfigFor);
}
@NonNull
private Optional<I_S_PostgREST_Config> retrieveConfigFor(@NonNull final OrgId orgId)
{
return queryBL
.createQueryBuilder(I_S_PostgREST_Config.class)
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_S_PostgREST_Config.COLUMNNAME_AD_Org_ID, orgId, OrgId.ANY)
.orderBy(I_S_PostgREST_Config.COLUMNNAME_AD_Org_ID)
.create()
.firstOptional(I_S_PostgREST_Config.class);
}
public void save(@NonNull final PostgRESTConfig postgRESTConfig)
{
final I_S_PostgREST_Config configRecord = InterfaceWrapperHelper.loadOrNew(postgRESTConfig.getId(), I_S_PostgREST_Config.class);
configRecord.setAD_Org_ID(postgRESTConfig.getOrgId().getRepoId());
configRecord.setBase_url(postgRESTConfig.getBaseURL()); | if (postgRESTConfig.getConnectionTimeout() == null)
{
configRecord.setConnection_timeout(0);
}
else
{
final long millis = postgRESTConfig.getConnectionTimeout().toMillis();
configRecord.setConnection_timeout((int)millis);
}
if (postgRESTConfig.getReadTimeout() == null)
{
configRecord.setRead_timeout(0);
}
else
{
final long millis = postgRESTConfig.getReadTimeout().toMillis();
configRecord.setRead_timeout((int)millis);
}
configRecord.setPostgREST_ResultDirectory(postgRESTConfig.getResultDirectory());
InterfaceWrapperHelper.saveRecord(configRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\postgrest\config\PostgRESTConfigRepository.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private static RootBeanDefinition getMapper(String userDetailsClass) {
if (OPT_PERSON.equals(userDetailsClass)) {
return new RootBeanDefinition(PERSON_MAPPER_CLASS, null, null);
}
if (OPT_INETORGPERSON.equals(userDetailsClass)) {
return new RootBeanDefinition(INET_ORG_PERSON_MAPPER_CLASS, null, null);
}
return new RootBeanDefinition(LDAP_USER_MAPPER_CLASS, null, null);
}
static RootBeanDefinition parseAuthoritiesPopulator(Element elt, ParserContext parserContext) {
String groupSearchFilter = elt.getAttribute(ATT_GROUP_SEARCH_FILTER);
String groupSearchBase = elt.getAttribute(ATT_GROUP_SEARCH_BASE);
String groupRoleAttribute = elt.getAttribute(ATT_GROUP_ROLE_ATTRIBUTE);
String rolePrefix = elt.getAttribute(ATT_ROLE_PREFIX);
if (!StringUtils.hasText(groupSearchFilter)) {
groupSearchFilter = DEF_GROUP_SEARCH_FILTER;
}
if (!StringUtils.hasText(groupSearchBase)) {
groupSearchBase = DEF_GROUP_SEARCH_BASE;
}
BeanDefinitionBuilder populator = BeanDefinitionBuilder.rootBeanDefinition(LDAP_AUTHORITIES_POPULATOR_CLASS);
populator.getRawBeanDefinition().setSource(parserContext.extractSource(elt)); | populator.addConstructorArgValue(parseServerReference(elt, parserContext));
populator.addConstructorArgValue(groupSearchBase);
populator.addPropertyValue("groupSearchFilter", groupSearchFilter);
populator.addPropertyValue("searchSubtree", Boolean.TRUE);
if (StringUtils.hasText(rolePrefix)) {
if ("none".equals(rolePrefix)) {
rolePrefix = "";
}
populator.addPropertyValue("rolePrefix", rolePrefix);
}
if (StringUtils.hasLength(groupRoleAttribute)) {
populator.addPropertyValue("groupRoleAttribute", groupRoleAttribute);
}
return (RootBeanDefinition) populator.getBeanDefinition();
}
} | repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\LdapUserServiceBeanDefinitionParser.java | 2 |
请完成以下Java代码 | void logToSystemErr(String message, Object... args) {
if (isSystemErrLoggingEnabled()) {
message = message.trim().endsWith("%n") ? message : message.concat("%n");
System.err.printf(message, args);
System.err.flush();
}
}
private boolean isSystemErrLoggingEnabled() {
return Optional.ofNullable(threadLocalEnvironmentReference.get())
.map(environment -> environment.getProperty(SYSTEM_ERR_ENABLED_PROPERTY, Boolean.class, false))
.orElseGet(() -> Boolean.getBoolean(SYSTEM_ERR_ENABLED_PROPERTY));
}
protected abstract class AbstractPropertySourceLoggingFunction
implements Function<PropertySource<?>, PropertySource<?>> {
protected void logProperties(@NonNull Iterable<String> propertyNames,
@NonNull Function<String, Object> propertyValueFunction) {
log("Properties [");
for (String propertyName : CollectionUtils.nullSafeIterable(propertyNames)) {
log("\t%1$s = %2$s", propertyName, propertyValueFunction.apply(propertyName));
}
log("]");
}
}
protected class EnumerablePropertySourceLoggingFunction extends AbstractPropertySourceLoggingFunction {
@Override
public @Nullable PropertySource<?> apply(@Nullable PropertySource<?> propertySource) {
if (propertySource instanceof EnumerablePropertySource) {
EnumerablePropertySource<?> enumerablePropertySource =
(EnumerablePropertySource<?>) propertySource;
String[] propertyNames = enumerablePropertySource.getPropertyNames();
Arrays.sort(propertyNames); | logProperties(Arrays.asList(propertyNames), enumerablePropertySource::getProperty);
}
return propertySource;
}
}
// The PropertySource may not be enumerable but may use a Map as its source.
protected class MapPropertySourceLoggingFunction extends AbstractPropertySourceLoggingFunction {
@Override
@SuppressWarnings("unchecked")
public @Nullable PropertySource<?> apply(@Nullable PropertySource<?> propertySource) {
if (!(propertySource instanceof EnumerablePropertySource)) {
Object source = propertySource != null
? propertySource.getSource()
: null;
if (source instanceof Map) {
Map<String, Object> map = new TreeMap<>((Map<String, Object>) source);
logProperties(map.keySet(), map::get);
}
}
return propertySource;
}
}
} | repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\context\logging\EnvironmentLoggingApplicationListener.java | 1 |
请完成以下Java代码 | public static QuickInputLayoutDescriptor build(@NonNull final DocumentEntityDescriptor entityDescriptor, @NonNull final String[][] fieldNames) {return onlyFields(entityDescriptor, fieldNames);}
public static QuickInputLayoutDescriptor onlyFields(
@NonNull final DocumentEntityDescriptor entityDescriptor,
@NonNull final List<String> fieldNames)
{
Check.assumeNotEmpty(fieldNames, "fieldNames is not empty");
final Builder layoutBuilder = builder();
for (final String fieldName : fieldNames)
{
if (Check.isBlank(fieldName))
{
continue;
}
DocumentLayoutElementDescriptor
.builderOrEmpty(entityDescriptor, fieldName)
.ifPresent(layoutBuilder::element);
}
return layoutBuilder.build();
}
@SuppressWarnings("unused")
public static QuickInputLayoutDescriptor allFields(@NonNull final DocumentEntityDescriptor entityDescriptor)
{
final Builder layoutBuilder = builder();
for (final DocumentFieldDescriptor field : entityDescriptor.getFields())
{
final DocumentLayoutElementDescriptor.Builder element = DocumentLayoutElementDescriptor.builder(field);
layoutBuilder.element(element);
}
return layoutBuilder.build();
}
private final List<DocumentLayoutElementDescriptor> elements;
private QuickInputLayoutDescriptor(final List<DocumentLayoutElementDescriptor> elements)
{
this.elements = ImmutableList.copyOf(elements); | }
@Override
public String toString()
{
return MoreObjects.toStringHelper(this)
.omitNullValues()
.add("elements", elements.isEmpty() ? null : elements)
.toString();
}
public List<DocumentLayoutElementDescriptor> getElements()
{
return elements;
}
public static final class Builder
{
private final List<DocumentLayoutElementDescriptor> elements = new ArrayList<>();
private Builder()
{
}
public QuickInputLayoutDescriptor build()
{
return new QuickInputLayoutDescriptor(elements);
}
public Builder element(@NonNull final DocumentLayoutElementDescriptor.Builder elementBuilder)
{
elements.add(elementBuilder.build());
return this;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\quickinput\QuickInputLayoutDescriptor.java | 1 |
请完成以下Java代码 | public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getProcessDefinitionName() {
return processDefinitionName;
}
public void setProcessDefinitionName(String processDefinitionName) {
this.processDefinitionName = processDefinitionName;
}
public int getXmlLineNumber() {
return xmlLineNumber;
}
public void setXmlLineNumber(int xmlLineNumber) {
this.xmlLineNumber = xmlLineNumber;
}
public int getXmlColumnNumber() {
return xmlColumnNumber;
}
public void setXmlColumnNumber(int xmlColumnNumber) {
this.xmlColumnNumber = xmlColumnNumber;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
}
public String getActivityName() {
return activityName;
}
public void setActivityName(String activityName) {
this.activityName = activityName;
}
public boolean isWarning() {
return isWarning;
}
public void setWarning(boolean isWarning) {
this.isWarning = isWarning;
}
@Override
public String toString() {
StringBuilder strb = new StringBuilder();
strb.append("[Validation set: '").append(validatorSetName).append("' | Problem: '").append(problem).append("'] : ");
strb.append(defaultDescription);
strb.append(" - [Extra info : ");
boolean extraInfoAlreadyPresent = false;
if (processDefinitionId != null) {
strb.append("processDefinitionId = ").append(processDefinitionId); | extraInfoAlreadyPresent = true;
}
if (processDefinitionName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("processDefinitionName = ").append(processDefinitionName).append(" | ");
extraInfoAlreadyPresent = true;
}
if (activityId != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("id = ").append(activityId).append(" | ");
extraInfoAlreadyPresent = true;
}
if (activityName != null) {
if (extraInfoAlreadyPresent) {
strb.append(" | ");
}
strb.append("activityName = ").append(activityName).append(" | ");
extraInfoAlreadyPresent = true;
}
strb.append("]");
if (xmlLineNumber > 0 && xmlColumnNumber > 0) {
strb.append(" ( line: ").append(xmlLineNumber).append(", column: ").append(xmlColumnNumber).append(")");
}
return strb.toString();
}
} | repos\flowable-engine-main\modules\flowable-process-validation\src\main\java\org\flowable\validation\ValidationError.java | 1 |
请完成以下Java代码 | private void runSimulation(int numWorkers, int numberOfPartialResults) {
NUM_PARTIAL_RESULTS = numberOfPartialResults;
NUM_WORKERS = numWorkers;
cyclicBarrier = new CyclicBarrier(NUM_WORKERS, new AggregatorThread());
System.out.println("Spawning " + NUM_WORKERS + " worker threads to compute " + NUM_PARTIAL_RESULTS + " partial results each");
for (int i = 0; i < NUM_WORKERS; i++) {
Thread worker = new Thread(new NumberCruncherThread());
worker.setName("Thread " + i);
worker.start();
}
}
class NumberCruncherThread implements Runnable {
@Override
public void run() {
String thisThreadName = Thread.currentThread().getName();
List<Integer> partialResult = new ArrayList<>();
for (int i = 0; i < NUM_PARTIAL_RESULTS; i++) {
Integer num = random.nextInt(10);
System.out.println(thisThreadName + ": Crunching some numbers! Final result - " + num);
partialResult.add(num);
}
partialResults.add(partialResult);
try {
System.out.println(thisThreadName + " waiting for others to reach barrier.");
cyclicBarrier.await();
} catch (InterruptedException | BrokenBarrierException e) {
e.printStackTrace();
}
}
}
class AggregatorThread implements Runnable {
@Override
public void run() {
String thisThreadName = Thread.currentThread().getName();
System.out.println(thisThreadName + ": Computing final sum of " + NUM_WORKERS + " workers, having " + NUM_PARTIAL_RESULTS + " results each.");
int sum = 0;
for (List<Integer> threadResult : partialResults) { | System.out.print("Adding ");
for (Integer partialResult : threadResult) {
System.out.print(partialResult + " ");
sum += partialResult;
}
System.out.println();
}
System.out.println(Thread.currentThread().getName() + ": Final result = " + sum);
}
}
public static void main(String[] args) {
CyclicBarrierDemo play = new CyclicBarrierDemo();
play.runSimulation(5, 3);
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-7\src\main\java\com\baeldung\cyclicbarrier\CyclicBarrierDemo.java | 1 |
请完成以下Java代码 | public static QtyToDeliverMap ofMap(final Map<ShipmentScheduleId, StockQtyAndUOMQty> map)
{
return map.isEmpty() ? EMPTY : new QtyToDeliverMap(ImmutableMap.copyOf(map));
}
public static QtyToDeliverMap of(@NonNull final ShipmentScheduleId shipmentScheduleId, @NonNull StockQtyAndUOMQty qtyToDeliver)
{
return ofMap(ImmutableMap.of(shipmentScheduleId, qtyToDeliver));
}
@NonNull
public static QtyToDeliverMap fromJson(@Nullable final String json)
{
if (json == null || Check.isBlank(json))
{
return QtyToDeliverMap.EMPTY;
}
try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().readValue(json, QtyToDeliverMap.class);
}
catch (JsonProcessingException e)
{
throw new AdempiereException("Failed deserializing " + QtyToDeliverMap.class.getSimpleName() + " from json: " + json, e);
}
}
public String toJsonString()
{ | try
{
return JsonObjectMapperHolder.sharedJsonObjectMapper().writeValueAsString(this);
}
catch (JsonProcessingException e)
{
throw new AdempiereException("Failed serializing " + this, e);
}
}
public boolean isEmpty() {return map.isEmpty();}
public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIds() {return ImmutableSet.copyOf(map.keySet());}
@Nullable
public StockQtyAndUOMQty getQtyToDeliver(@NonNull final ShipmentScheduleId shipmentScheduleId)
{
return map.get(shipmentScheduleId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\QtyToDeliverMap.java | 1 |
请完成以下Java代码 | protected int get_AccessLevel()
{
return accessLevel.intValue();
}
/** Load Meta Data */
protected POInfo initPO (Properties ctx)
{
POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName());
return poi;
}
public String toString()
{
StringBuffer sb = new StringBuffer ("X_C_BankStatementMatcher[")
.append(get_ID()).append("]");
return sb.toString();
}
/** Set Bank Statement Matcher.
@param C_BankStatementMatcher_ID
Algorithm to match Bank Statement Info to Business Partners, Invoices and Payments
*/
public void setC_BankStatementMatcher_ID (int C_BankStatementMatcher_ID)
{
if (C_BankStatementMatcher_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_BankStatementMatcher_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_BankStatementMatcher_ID, Integer.valueOf(C_BankStatementMatcher_ID));
}
/** Get Bank Statement Matcher.
@return Algorithm to match Bank Statement Info to Business Partners, Invoices and Payments
*/
public int getC_BankStatementMatcher_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_BankStatementMatcher_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Classname.
@param Classname
Java Classname
*/
public void setClassname (String Classname)
{
set_Value (COLUMNNAME_Classname, Classname);
}
/** Get Classname.
@return Java Classname
*/
public String getClassname ()
{
return (String)get_Value(COLUMNNAME_Classname);
}
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
/** Set Name.
@param Name
Alphanumeric identifier of the entity | */
public void setName (String Name)
{
set_Value (COLUMNNAME_Name, Name);
}
/** Get Name.
@return Alphanumeric identifier of the entity
*/
public String getName ()
{
return (String)get_Value(COLUMNNAME_Name);
}
/** Get Record ID/ColumnName
@return ID/ColumnName pair
*/
public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (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.banking\de.metas.banking.base\src\main\java-gen\org\compiere\model\X_C_BankStatementMatcher.java | 1 |
请完成以下Java代码 | public class Product {
@Id
private String id;
private String name;
private String category;
private double price;
private boolean available;
public Product() {
}
public Product(String name, double price, String category, boolean available) {
this.name = name;
this.category = category;
this.price = price;
this.available = available;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) { | this.name = name;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public double getPrice() {
return price;
}
public void setPrice(double price) {
this.price = price;
}
public boolean isAvailable() {
return available;
}
public void setAvailable(boolean available) {
this.available = available;
}
} | repos\tutorials-master\persistence-modules\spring-data-mongodb-2\src\main\java\com\baeldung\multicriteria\Product.java | 1 |
请完成以下Java代码 | public void setIsInternal (boolean IsInternal)
{
set_Value (COLUMNNAME_IsInternal, Boolean.valueOf(IsInternal));
}
/** Get Internal.
@return Internal Organization
*/
public boolean isInternal ()
{
Object oo = get_Value(COLUMNNAME_IsInternal);
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());
}
/** 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\compiere\model\X_B_Seller.java | 1 |
请完成以下Java代码 | public String getComentTmp() {
return comentTmp;
}
public void setComentTmp(String comentTmp) {
this.comentTmp = comentTmp;
}
public List<String> getComment() {
return comment;
}
public void setComment(List<String> comment) {
this.comment = comment;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
} | public String getUrlMd5() {
return urlMd5;
}
public void setUrlMd5(String urlMd5) {
this.urlMd5 = urlMd5;
}
@Override
public String toString() {
return "Blog{" + "title='" + title + '\'' + ", publishDate=" + publishDate + ", readCountStr='" + readCountStr
+ '\'' + ", readCount=" + readCount + ", content='" + content + '\'' + ", likeCount=" + likeCount
+ ", comentTmp='" + comentTmp + '\'' + ", url='" + url + '\'' + ", comment=" + comment + '}';
}
} | repos\spring-boot-quick-master\quick-vw-crawler\src\main\java\com\crawler\vw\entity\Blog.java | 1 |
请完成以下Java代码 | public Q patch() {
return method(HttpPatch.METHOD_NAME);
}
public Q head() {
return method(HttpHead.METHOD_NAME);
}
public Q options() {
return method(HttpOptions.METHOD_NAME);
}
public Q trace() {
return method(HttpTrace.METHOD_NAME);
}
public Map<String, Object> getConfigOptions() {
return getRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG);
}
public Object getConfigOption(String field) {
Map<String, Object> config = getConfigOptions();
if (config != null) {
return config.get(field);
} | return null;
}
@SuppressWarnings("unchecked")
public Q configOption(String field, Object value) {
if (field == null || field.isEmpty() || value == null) {
LOG.ignoreConfig(field, value);
} else {
Map<String, Object> config = getConfigOptions();
if (config == null) {
config = new HashMap<>();
setRequestParameter(HttpBaseRequest.PARAM_NAME_REQUEST_CONFIG, config);
}
config.put(field, value);
}
return (Q) this;
}
} | repos\camunda-bpm-platform-master\connect\http-client\src\main\java\org\camunda\connect\httpclient\impl\AbstractHttpRequest.java | 1 |
请完成以下Java代码 | private void validateOneIdentificationMethod(@NonNull final JsonCreateReceiptInfo createReceiptInfo)
{
if (createReceiptInfo.countIdentificationMethods() != 1)
{
throw new AdempiereException(ERR_RECEIPT_SCHEDULE_INVALID_IDENTIFICATION_METHOD)
.appendParametersToMessage()
.setParameter("jsonCreateReceiptInfo", createReceiptInfo);
}
}
@NonNull
private ExternalSystemIdWithExternalIds getExternalSystemIdWithExternalIds(@NonNull final JsonCreateReceiptInfo receiptInfo)
{
return ExternalSystemIdWithExternalIds.builder()
.externalSystemId(externalSystemRepository.getIdByType(ExternalSystemType.ofValue(receiptInfo.getExternalSystemCode())))
.externalHeaderIdWithExternalLineIds(ExternalHeaderIdWithExternalLineIds.builder()
.externalHeaderId(ExternalId.of(receiptInfo.getExternalHeaderId()))
.externalLineId(ExternalId.of(receiptInfo.getExternalLineId()))
.build())
.build();
}
//
//
//utility class
private static class ReceiptScheduleCache
{
private final IReceiptScheduleDAO receiptScheduleDAO;
private final HashMap<ReceiptScheduleId, I_M_ReceiptSchedule> receiptScheduleHashMap = new HashMap<>();
private ReceiptScheduleCache(@NonNull final IReceiptScheduleDAO receiptScheduleDAO)
{
this.receiptScheduleDAO = receiptScheduleDAO;
}
void refreshCacheForIds(@NonNull final ImmutableSet<ReceiptScheduleId> receiptScheduleIds)
{
this.receiptScheduleHashMap.putAll(receiptScheduleDAO.getByIds(receiptScheduleIds)); | }
private I_M_ReceiptSchedule getById(@NonNull final ReceiptScheduleId receiptScheduleId)
{
return this.receiptScheduleHashMap.computeIfAbsent(receiptScheduleId, receiptScheduleDAO::getById);
}
private List<I_M_ReceiptSchedule> getByIds(@NonNull final ImmutableSet<ReceiptScheduleId> receiptScheduleIds)
{
return receiptScheduleIds.stream()
.map(this::getById)
.collect(ImmutableList.toImmutableList());
}
private OrgId getOrgId(@NonNull final ReceiptScheduleId receiptScheduleId)
{
final I_M_ReceiptSchedule receiptSchedule = getById(receiptScheduleId);
return OrgId.ofRepoId(receiptSchedule.getAD_Org_ID());
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\receipt\ReceiptService.java | 1 |
请完成以下Spring Boot application配置 | spring:
application:
name: user-service # 服务名
# Zipkin 配置项,对应 ZipkinProperties 类
zipkin:
base-url: http://127.0.0.1:9411 # Zipkin 服务的地址
# Spring Cloud Sleuth 配置项
sleuth:
# Spring Cloud Sleuth 针对 Web 组件的配置项,例如说 SpringMVC
web:
enabled: true # 是否开启,默认为 true
data:
# MongoDB 配置项,对应 MongoProperties 类
mon | godb:
host: 127.0.0.1
port: 27017
database: yourdatabase
username: test01
password: password01
# 上述属性,也可以只配置 uri | repos\SpringBoot-Labs-master\labx-13\labx-13-sc-sleuth-db-mongodb\src\main\resources\application.yml | 2 |
请完成以下Java代码 | class AnnotatedColumnControlButton extends ColumnControlButton
{
private static final long serialVersionUID = 1L;
public static final String PROPERTY_DisableColumnControl = AnnotatedColumnControlButton.class.getName() + ".DisableColumnControl";
public AnnotatedColumnControlButton(JXTable table)
{
super(table);
}
@Override
protected ColumnVisibilityAction createColumnVisibilityAction(final TableColumn column)
{
ColumnVisibilityAction action = super.createColumnVisibilityAction(column);
if (action != null && !canControlColumn(column))
{
// NOTE: instead of just disabling it, better hide it at all
//action.setEnabled(false);
action = null;
}
return action;
} | private static final boolean canControlColumn(TableColumn column)
{
if (!(column instanceof TableColumnExt))
{
return false;
}
final TableColumnExt columnExt = (TableColumnExt)column;
final Object disableColumnControlObj = columnExt.getClientProperty(PROPERTY_DisableColumnControl);
if (DisplayType.toBooleanNonNull(disableColumnControlObj, false))
{
return false;
}
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedColumnControlButton.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
public I_AD_User getSalesRep() throws RuntimeException
{
return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name)
.getPO(getSalesRep_ID(), get_TrxName()); }
/** Set Sales Representative.
@param SalesRep_ID
Sales Representative or Company Agent
*/
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Sales Representative.
@return Sales Representative or Company Agent
*/
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0; | return ii.intValue();
}
/** Set Search Key.
@param Value
Search key for the record in the format required - must be unique
*/
public void setValue (String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Search Key.
@return Search key for the record in the format required - must be unique
*/
public String getValue ()
{
return (String)get_Value(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_SalesRegion.java | 1 |
请完成以下Java代码 | public final class ImmutablePair<LT, RT> implements IPair<LT, RT>
{
/**
* Creates an immutable pair
*/
public static <L, R> ImmutablePair<L, R> of(
@Nullable final L left,
@Nullable final R right)
{
return new ImmutablePair<L, R>(left, right);
}
private final LT left;
private final RT right;
private ImmutablePair(@Nullable final LT left, @Nullable final RT right)
{
this.left = left;
this.right = right;
}
@Override
public String toString()
{
return "ImmutablePair [left=" + left + ", right=" + right + "]";
}
@Override
public int hashCode()
{
final int prime = 31;
int result = 1;
result = prime * result + ((left == null) ? 0 : left.hashCode());
result = prime * result + ((right == null) ? 0 : right.hashCode());
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 ImmutablePair<?, ?> other = (ImmutablePair<?, ?>)obj;
if (left == null) | {
if (other.left != null)
return false;
}
else if (!left.equals(other.left))
return false;
if (right == null)
{
if (other.right != null)
return false;
}
else if (!right.equals(other.right))
return false;
return true;
}
@Override
public LT getLeft()
{
return left;
}
@Override
public RT getRight()
{
return right;
}
} | repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\pair\ImmutablePair.java | 1 |
请完成以下Java代码 | public class LocalDateTimeType implements VariableType {
public String getTypeName() {
return "localDateTime";
}
public boolean isCachable() {
return true;
}
public boolean isAbleToStore(Object value) {
if (value == null) {
return true;
}
return LocalDateTime.class.isAssignableFrom(value.getClass());
} | public Object getValue(ValueFields valueFields) {
Long longValue = valueFields.getLongValue();
if (longValue != null) {
return LocalDateTime.ofEpochSecond(longValue, 0, ZoneOffset.UTC);
}
return null;
}
public void setValue(Object value, ValueFields valueFields) {
if (value != null) {
valueFields.setLongValue(((LocalDateTime) value).toEpochSecond(ZoneOffset.UTC));
} else {
valueFields.setLongValue(null);
}
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\variable\LocalDateTimeType.java | 1 |
请完成以下Java代码 | public Criteria andBigPicNotIn(List<String> values) {
addCriterion("big_pic not in", values, "bigPic");
return (Criteria) this;
}
public Criteria andBigPicBetween(String value1, String value2) {
addCriterion("big_pic between", value1, value2, "bigPic");
return (Criteria) this;
}
public Criteria andBigPicNotBetween(String value1, String value2) {
addCriterion("big_pic not between", value1, value2, "bigPic");
return (Criteria) this;
}
}
public static class Criteria extends GeneratedCriteria {
protected Criteria() {
super();
}
}
public static class Criterion {
private String condition;
private Object value;
private Object secondValue;
private boolean noValue;
private boolean singleValue;
private boolean betweenValue;
private boolean listValue;
private String typeHandler;
public String getCondition() {
return condition;
}
public Object getValue() {
return value;
}
public Object getSecondValue() {
return secondValue;
}
public boolean isNoValue() {
return noValue;
}
public boolean isSingleValue() {
return singleValue;
}
public boolean isBetweenValue() {
return betweenValue;
}
public boolean isListValue() {
return listValue;
}
public String getTypeHandler() {
return typeHandler;
} | protected Criterion(String condition) {
super();
this.condition = condition;
this.typeHandler = null;
this.noValue = true;
}
protected Criterion(String condition, Object value, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.typeHandler = typeHandler;
if (value instanceof List<?>) {
this.listValue = true;
} else {
this.singleValue = true;
}
}
protected Criterion(String condition, Object value) {
this(condition, value, null);
}
protected Criterion(String condition, Object value, Object secondValue, String typeHandler) {
super();
this.condition = condition;
this.value = value;
this.secondValue = secondValue;
this.typeHandler = typeHandler;
this.betweenValue = true;
}
protected Criterion(String condition, Object value, Object secondValue) {
this(condition, value, secondValue, null);
}
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsBrandExample.java | 1 |
请完成以下Java代码 | public void sendWebsocketViewChangedNotification(
@RequestParam("viewId") final String viewIdStr,
@RequestParam("changedIds") final String changedIdsStr)
{
assertLoggedIn();
final ViewId viewId = ViewId.ofViewIdString(viewIdStr);
final DocumentIdsSelection changedRowIds = DocumentIdsSelection.ofCommaSeparatedString(changedIdsStr);
sendWebsocketViewChangedNotification(viewId, changedRowIds);
}
void sendWebsocketViewChangedNotification(
final ViewId viewId,
final DocumentIdsSelection changedRowIds)
{
final ViewChanges viewChanges = new ViewChanges(viewId);
viewChanges.addChangedRowIds(changedRowIds);
JSONViewChanges jsonViewChanges = JSONViewChanges.of(viewChanges);
final WebsocketTopicName endpoint = WebsocketTopicNames.buildViewNotificationsTopicName(jsonViewChanges.getViewId());
try
{
websocketSender.convertAndSend(endpoint, jsonViewChanges);
}
catch (final Exception ex)
{
throw AdempiereException.wrapIfNeeded(ex)
.appendParametersToMessage()
.setParameter("json", jsonViewChanges);
}
}
@GetMapping("/logging/config")
public void setWebsocketLoggingConfig(
@RequestParam("enabled") final boolean enabled,
@RequestParam(value = "maxLoggedEvents", defaultValue = "500") final int maxLoggedEvents)
{
userSession.assertLoggedIn();
websocketSender.setLogEventsEnabled(enabled);
websocketSender.setLogEventsMaxSize(maxLoggedEvents);
}
@GetMapping("/logging/events") | public List<WebsocketEventLogRecord> getWebsocketLoggedEvents(
@RequestParam(value = "destinationFilter", required = false) final String destinationFilter)
{
userSession.assertLoggedIn();
return websocketSender.getLoggedEvents(destinationFilter);
}
@GetMapping("/activeSubscriptions")
public Map<String, ?> getActiveSubscriptions()
{
userSession.assertLoggedIn();
final ImmutableMap<WebsocketTopicName, Collection<WebsocketSubscriptionId>> map = websocketActiveSubscriptionsIndex.getSubscriptionIdsByTopicName().asMap();
final ImmutableMap<String, ImmutableList<String>> stringsMap = map.entrySet()
.stream()
.map(entry -> GuavaCollectors.entry(
entry.getKey().getAsString(), // topic
entry.getValue().stream()
.map(WebsocketSubscriptionId::getAsString)
.collect(ImmutableList.toImmutableList())))
.collect(GuavaCollectors.toImmutableMap());
return stringsMap;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\debug\DebugWebsocketRestController.java | 1 |
请完成以下Java代码 | protected ExecutionEntity getProcessInstanceEntity(CommandContext commandContext, String processInstanceId) {
ExecutionEntity processInstance = CommandContextUtil.getExecutionEntityManager(commandContext).findById(processInstanceId);
if (processInstance == null) {
throw new FlowableIllegalArgumentException(
"The process instance with id '" + processInstanceId + "' could not be found as an active process instance.");
}
return processInstance;
}
/**
* This will remove ALL identity links with the given type, no mather whether they are user or group based.
*
* @param commandContext the command context within which to remove the identity links
* @param processInstanceId the id of the process instance to remove the identity links for
* @param identityType the identity link type (e.g. assignee or owner, etc) to be removed
*/
protected void removeIdentityLinkType(CommandContext commandContext, String processInstanceId, String identityType) {
ExecutionEntity processInstanceEntity = getProcessInstanceEntity(commandContext, processInstanceId);
// this will remove ALL identity links with the given identity type (for users AND groups)
IdentityLinkUtil.deleteProcessInstanceIdentityLinks(processInstanceEntity, null, null, identityType);
}
/**
* Creates a new identity link entry for the given process instance, which can either be a user or group based one, but not both the same time.
* If both the user and group ids are null, no new identity link is created.
*
* @param commandContext the command context within which to perform the identity link creation
* @param processInstanceId the id of the process instance to create an identity link for
* @param userId the user id if this is a user based identity link, otherwise null
* @param groupId the group id if this is a group based identity link, otherwise null | * @param identityType the type of identity link (e.g. owner or assignee, etc)
*/
protected void createIdentityLinkType(CommandContext commandContext, String processInstanceId, String userId, String groupId, String identityType) {
// if both user and group ids are null, don't create an identity link
if (userId == null && groupId == null) {
return;
}
// if both are set the same time, throw an exception as this is not allowed
if (userId != null && groupId != null) {
throw new FlowableIllegalArgumentException("Either set the user id or the group id for an identity link, but not both the same time.");
}
ExecutionEntity processInstanceEntity = getProcessInstanceEntity(commandContext, processInstanceId);
IdentityLinkUtil.createProcessInstanceIdentityLink(processInstanceEntity, userId, groupId, identityType);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\AbstractProcessInstanceIdentityLinkCmd.java | 1 |
请完成以下Java代码 | public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getKey() {
return key;
}
public void setKey(String key) {
this.key = key;
}
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public byte[] getPasswordBytes() {
return passwordBytes;
}
public void setPasswordBytes(byte[] passwordBytes) {
this.passwordBytes = passwordBytes;
}
public String getPassword() {
return password;
} | public void setPassword(String password) {
this.password = password;
}
public String getName() {
return key;
}
public String getUsername() {
return value;
}
public String getParentId() {
return parentId;
}
public void setParentId(String parentId) {
this.parentId = parentId;
}
public Map<String, String> getDetails() {
return details;
}
public void setDetails(Map<String, String> details) {
this.details = details;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", revision=" + revision
+ ", type=" + type
+ ", userId=" + userId
+ ", key=" + key
+ ", value=" + value
+ ", password=" + password
+ ", parentId=" + parentId
+ ", details=" + details
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\IdentityInfoEntity.java | 1 |
请完成以下Java代码 | public static StringDictionary load(String path, String separator)
{
StringDictionary dictionary = new StringDictionary(separator);
if (dictionary.load(path)) return dictionary;
return null;
}
/**
* 加载词典
* @param path
* @return
*/
public static StringDictionary load(String path)
{
return load(path, "=");
}
/**
* 合并词典,第一个为主词典
* @param args
* @return
*/
public static StringDictionary combine(StringDictionary... args)
{
StringDictionary[] dictionaries = args.clone();
StringDictionary mainDictionary = dictionaries[0];
for (int i = 1; i < dictionaries.length; ++i)
{
mainDictionary.combine(dictionaries[i]);
} | return mainDictionary;
}
public static StringDictionary combine(String... args)
{
String[] pathArray = args.clone();
List<StringDictionary> dictionaryList = new LinkedList<StringDictionary>();
for (String path : pathArray)
{
StringDictionary dictionary = load(path);
if (dictionary == null) continue;
dictionaryList.add(dictionary);
}
return combine(dictionaryList.toArray(new StringDictionary[0]));
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\StringDictionaryMaker.java | 1 |
请完成以下Java代码 | public void setRedo (java.lang.String Redo)
{
set_Value (COLUMNNAME_Redo, Redo);
}
/** Get Redo.
@return Redo */
@Override
public java.lang.String getRedo ()
{
return (java.lang.String)get_Value(COLUMNNAME_Redo);
}
/** Set Transaktion.
@param TrxName
Name of the transaction
*/
@Override
public void setTrxName (java.lang.String TrxName)
{
set_ValueNoCheck (COLUMNNAME_TrxName, TrxName);
}
/** Get Transaktion.
@return Name of the transaction
*/ | @Override
public java.lang.String getTrxName ()
{
return (java.lang.String)get_Value(COLUMNNAME_TrxName);
}
/** Set Undo.
@param Undo Undo */
@Override
public void setUndo (java.lang.String Undo)
{
set_Value (COLUMNNAME_Undo, Undo);
}
/** Get Undo.
@return Undo */
@Override
public java.lang.String getUndo ()
{
return (java.lang.String)get_Value(COLUMNNAME_Undo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ChangeLog.java | 1 |
请完成以下Java代码 | public class OnlyOneOpenInvoiceCandProcessor implements IShipmentSchedulesAfterFirstPassUpdater
{
public static final String MSG_OPEN_INVOICE_1P = "ShipmentSchedule_OpenInvoice_1P";
public static final String MSG_WITH_NEXT_SUBSCRIPTION = "ShipmentSchedule_WithNextSubscription";
private static final Logger logger = LogManager.getLogger(OnlyOneOpenInvoiceCandProcessor.class);
@Override
public void doUpdateAfterFirstPass(
final Properties ctx,
final IShipmentSchedulesDuringUpdate candidates)
{
for (final DeliveryGroupCandidate groupCandidate : candidates.getCandidates())
{
for (final DeliveryLineCandidate lineCandidate : groupCandidate.getLines())
{
if (lineCandidate.isDiscarded())
{
// this line won't be delivered anyways. Nothing to do
continue;
}
handleOnlyOneOpenInv(ctx, candidates, lineCandidate);
}
}
}
private void handleOnlyOneOpenInv(final Properties ctx,
final IShipmentSchedulesDuringUpdate candidates,
final DeliveryLineCandidate lineCandidate)
{
try (final MDCCloseable mdcClosable = ShipmentSchedulesMDC.putShipmentScheduleId(lineCandidate.getShipmentScheduleId())) | {
final BPartnerStats stats = Services.get(IBPartnerStatsDAO.class).getCreateBPartnerStats(lineCandidate.getBillBPartnerId());
final String creditStatus = I_C_BPartner.SO_CREDITSTATUS_ONE_OPEN_INVOICE;
if (creditStatus.equals(stats.getSOCreditStatus()))
{
final BigDecimal soCreditUsed = stats.getSOCreditUsed();
if (soCreditUsed.signum() > 0)
{
logger.debug("Discard lineCandidate because of an existing open invoice");
candidates.addStatusInfo(lineCandidate, Services.get(IMsgBL.class).getMsg(ctx, MSG_OPEN_INVOICE_1P, new Object[] { soCreditUsed }));
lineCandidate.setDiscarded();
}
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\spi\impl\OnlyOneOpenInvoiceCandProcessor.java | 1 |
请完成以下Java代码 | public CorporateAction1 getCorpActn() {
return corpActn;
}
/**
* Sets the value of the corpActn property.
*
* @param value
* allowed object is
* {@link CorporateAction1 }
*
*/
public void setCorpActn(CorporateAction1 value) {
this.corpActn = value;
}
/**
* Gets the value of the sfkpgAcct property.
*
* @return
* possible object is
* {@link CashAccount16 }
*
*/
public CashAccount16 getSfkpgAcct() {
return sfkpgAcct;
}
/**
* Sets the value of the sfkpgAcct property.
*
* @param value | * allowed object is
* {@link CashAccount16 }
*
*/
public void setSfkpgAcct(CashAccount16 value) {
this.sfkpgAcct = value;
}
/**
* Gets the value of the addtlTxInf property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getAddtlTxInf() {
return addtlTxInf;
}
/**
* Sets the value of the addtlTxInf property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setAddtlTxInf(String value) {
this.addtlTxInf = 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\EntryTransaction2.java | 1 |
请完成以下Java代码 | public class MessageThrowingEventListener extends BaseDelegateEventListener {
protected String messageName;
protected Class<?> entityClass;
@Override
public void onEvent(FlowableEvent event) {
if (isValidEvent(event) && event instanceof FlowableEngineEvent) {
FlowableEngineEvent engineEvent = (FlowableEngineEvent) event;
if (engineEvent.getProcessInstanceId() == null) {
throw new ActivitiIllegalArgumentException(
"Cannot throw process-instance scoped message, since the dispatched event is not part of an ongoing process instance");
}
CommandContext commandContext = Context.getCommandContext();
List<EventSubscriptionEntity> subscriptionEntities = commandContext.getEventSubscriptionEntityManager()
.findEventSubscriptionsByNameAndExecution(MessageEventHandler.EVENT_HANDLER_TYPE, messageName, engineEvent.getExecutionId());
// Revert to messaging the process instance
if (subscriptionEntities.isEmpty() && engineEvent.getProcessInstanceId() != null &&
!engineEvent.getExecutionId().equals(engineEvent.getProcessInstanceId())) {
subscriptionEntities = commandContext.getEventSubscriptionEntityManager()
.findEventSubscriptionsByNameAndExecution(MessageEventHandler.EVENT_HANDLER_TYPE, messageName, engineEvent.getProcessInstanceId()); | }
for (EventSubscriptionEntity signalEventSubscriptionEntity : subscriptionEntities) {
signalEventSubscriptionEntity.eventReceived(null, false);
}
}
}
public void setMessageName(String messageName) {
this.messageName = messageName;
}
@Override
public boolean isFailOnException() {
return true;
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\helper\MessageThrowingEventListener.java | 1 |
请完成以下Java代码 | public JSONDocumentField setDisplayed(final boolean displayed)
{
setDisplayed(displayed, null);
return this;
}
/* package */ void setLookupValuesStale(final boolean lookupValuesStale, @Nullable final String reason)
{
this.lookupValuesStale = lookupValuesStale;
lookupValuesStaleReason = reason;
}
/* package */ JSONDocumentField setValidStatus(final JSONDocumentValidStatus validStatus)
{
this.validStatus = validStatus;
return this;
}
@Nullable
public Object getValue()
{
return value;
}
@JsonAnyGetter
public Map<String, Object> getOtherProperties()
{
return otherProperties;
}
@JsonAnySetter
public void putOtherProperty(final String name, final Object jsonValue)
{
otherProperties.put(name, jsonValue);
}
public JSONDocumentField putDebugProperty(final String name, final Object jsonValue)
{
otherProperties.put("debug-" + name, jsonValue);
return this;
}
public void putDebugProperties(final Map<String, Object> debugProperties)
{
if (debugProperties == null || debugProperties.isEmpty())
{
return;
}
for (final Map.Entry<String, Object> e : debugProperties.entrySet()) | {
putDebugProperty(e.getKey(), e.getValue());
}
}
public JSONDocumentField setViewEditorRenderMode(final ViewEditorRenderMode viewEditorRenderMode)
{
this.viewEditorRenderMode = viewEditorRenderMode != null ? viewEditorRenderMode.toJson() : null;
return this;
}
public void setFieldWarning(@Nullable final JSONDocumentFieldWarning fieldWarning)
{
this.fieldWarning = fieldWarning;
}
public JSONDocumentField setDevices(@Nullable final List<JSONDeviceDescriptor> devices)
{
this.devices = devices;
return this;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONDocumentField.java | 1 |
请完成以下Java代码 | public void reset() {
this.delegate.reset();
}
@Override
public void restore(Object previousValue) {
restoreInternal(previousValue);
}
@SuppressWarnings("unchecked")
public <V> void restoreInternal(Object previousValue) {
((ThreadLocalAccessor<V>) this.delegate).restore((V) previousValue);
}
@Override
public void restore() {
this.delegate.restore();
}
private static final class DelegateAccessor implements ThreadLocalAccessor<Object> {
@Override
public Object key() {
return SecurityContext.class.getName();
}
@Override
public Object getValue() {
return SecurityContextHolder.getContext();
}
@Override
public void setValue(Object value) {
SecurityContextHolder.setContext((SecurityContext) value);
}
@Override
public void setValue() {
SecurityContextHolder.clearContext();
}
@Override
public void restore(Object previousValue) {
SecurityContextHolder.setContext((SecurityContext) previousValue);
}
@Override
public void restore() {
SecurityContextHolder.clearContext();
}
@Override
@Deprecated(since = "1.3.0", forRemoval = true)
public void reset() {
SecurityContextHolder.clearContext();
} | }
private static final class NoOpAccessor implements ThreadLocalAccessor<Object> {
@Override
public Object key() {
return getClass().getName();
}
@Override
public @Nullable Object getValue() {
return null;
}
@Override
public void setValue(Object value) {
}
@Override
public void setValue() {
}
@Override
public void restore(Object previousValue) {
}
@Override
public void restore() {
}
@Override
@Deprecated(since = "1.3.0", forRemoval = true)
public void reset() {
}
}
} | repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\execution\SecurityContextThreadLocalAccessor.java | 1 |
请完成以下Java代码 | public String toString()
{
return ObjectUtils.toString(this);
}
@Override
public I_C_Invoice_Candidate getC_Invoice_Candidate()
{
return invoiceCandidate;
}
@Override
public I_C_InvoiceCandidate_InOutLine getC_InvoiceCandidate_InOutLine()
{
return iciol;
}
@Override
public List<Object> getLineAggregationKeyElements()
{
return aggregationKeyElements;
}
@Override
public Set<IInvoiceLineAttribute> getAttributesFromInoutLines()
{
return attributesFromInoutLines;
}
@Override
public boolean isAllocateRemainingQty()
{
return this.allocateRemainingQty;
}
/**
* {@link InvoiceLineAggregationRequest} builder.
*/
public static class Builder
{
private I_C_Invoice_Candidate invoiceCandidate;
private I_C_InvoiceCandidate_InOutLine iciol;
private final List<Object> aggregationKeyElements = new ArrayList<>();
private final Set<IInvoiceLineAttribute> attributesFromInoutLines = new LinkedHashSet<>();
@Setter
private boolean allocateRemainingQty = false;
/* package */ InvoiceLineAggregationRequest build()
{
return new InvoiceLineAggregationRequest(this);
}
private Builder()
{
}
@Override | public String toString()
{
return ObjectUtils.toString(this);
}
public Builder setC_Invoice_Candidate(final I_C_Invoice_Candidate invoiceCandidate)
{
this.invoiceCandidate = invoiceCandidate;
return this;
}
public Builder setC_InvoiceCandidate_InOutLine(final I_C_InvoiceCandidate_InOutLine iciol)
{
this.iciol = iciol;
return this;
}
/**
* Adds an additional element to be considered part of the line aggregation key.
* <p>
* NOTE: basically this shall be always empty because everything which is related to line aggregation
* shall be configured from aggregation definition,
* but we are also leaving this door open in case we need to implement some quick/hot fixes.
*
* @deprecated This method will be removed because we shall go entirely with standard aggregation definition.
*/
@Deprecated
public Builder addLineAggregationKeyElement(@NonNull final Object aggregationKeyElement)
{
aggregationKeyElements.add(aggregationKeyElement);
return this;
}
public void addInvoiceLineAttributes(@NonNull final Collection<IInvoiceLineAttribute> invoiceLineAttributes)
{
this.attributesFromInoutLines.addAll(invoiceLineAttributes);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoiceLineAggregationRequest.java | 1 |
请完成以下Java代码 | private ImpDataCell createDateCell(final ImpFormatColumn column, final List<String> cellRawValues)
{
try
{
final String rawValue = extractRawValue(column, cellRawValues);
final Object value = column.parseCellValue(rawValue);
return ImpDataCell.value(value);
}
catch (final Exception ex)
{
return ImpDataCell.error(ErrorMessage.of(ex));
}
}
private static String extractRawValue(final ImpFormatColumn column, final List<String> cellRawValues)
{
if (column.isConstant())
{
return column.getConstantValue();
}
// NOTE: startNo is ONE based, so we have to convert it to 0-based index.
final int cellIndex = column.getStartNo() - 1;
if (cellIndex < 0)
{
throw new AdempiereException("Invalid StartNo for column + " + column.getName());
}
if (cellIndex >= cellRawValues.size())
{
return null;
}
return cellRawValues.get(cellIndex);
}
private static List<String> splitLineByDelimiter(
final String line,
final char cellQuote,
final char cellDelimiter)
{
if (line == null || line.isEmpty())
{
return ImmutableList.of();
}
final List<String> result = new ArrayList<>();
StringBuilder currentValue = new StringBuilder();
boolean inQuotes = false;
boolean startCollectChar = false;
boolean doubleQuotesInColumn = false;
final char[] chars = line.toCharArray();
for (final char ch : chars)
{
if (inQuotes)
{
startCollectChar = true;
if (ch == cellQuote) | {
inQuotes = false;
doubleQuotesInColumn = false;
}
else
{
// Fixed : allow "" in custom quote enclosed
if (ch == '\"')
{
if (!doubleQuotesInColumn)
{
currentValue.append(ch);
doubleQuotesInColumn = true;
}
}
else
{
currentValue.append(ch);
}
}
}
else
{
if (ch == cellQuote)
{
inQuotes = true;
// double quotes in column will hit this!
if (startCollectChar)
{
currentValue.append('"');
}
}
else if (ch == cellDelimiter)
{
result.add(currentValue.toString());
currentValue = new StringBuilder();
startCollectChar = false;
}
else
{
currentValue.append(ch);
}
}
}
result.add(currentValue.toString());
return result;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\impexp\parser\FlexImpDataLineParser.java | 1 |
请完成以下Java代码 | protected void executeParse(BpmnParse bpmnParse, SubProcess subProcess) {
ActivityImpl activity = createActivityOnScope(bpmnParse, subProcess, BpmnXMLConstants.ELEMENT_SUBPROCESS, bpmnParse.getCurrentScope());
activity.setAsync(subProcess.isAsynchronous());
activity.setExclusive(!subProcess.isNotExclusive());
boolean triggeredByEvent = false;
if (subProcess instanceof EventSubProcess) {
triggeredByEvent = true;
}
activity.setProperty("triggeredByEvent", triggeredByEvent);
// event subprocesses are not scopes
activity.setScope(!triggeredByEvent);
activity.setActivityBehavior(bpmnParse.getActivityBehaviorFactory().createSubprocActivityBehavior(subProcess));
bpmnParse.setCurrentScope(activity);
bpmnParse.setCurrentSubProcess(subProcess); | bpmnParse.processFlowElements(subProcess.getFlowElements());
processArtifacts(bpmnParse, subProcess.getArtifacts(), activity);
// no data objects for event subprocesses
if (!(subProcess instanceof EventSubProcess)) {
// parse out any data objects from the template in order to set up the necessary process variables
Map<String, Object> variables = processDataObjects(bpmnParse, subProcess.getDataObjects(), activity);
activity.setVariables(variables);
}
bpmnParse.removeCurrentScope();
bpmnParse.removeCurrentSubProcess();
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\handler\SubProcessParseHandler.java | 1 |
请完成以下Java代码 | protected boolean beforeSave(boolean newRecord)
{
// Reset Stocked if not Item
// AZ Goodwill: Bug Fix isStocked always return false
// if (isStocked() && !PRODUCTTYPE_Item.equals(getProductType()))
if (!PRODUCTTYPE_Item.equals(getProductType()))
{
setIsStocked(false);
}
// UOM reset
if (m_precision != null && is_ValueChanged("C_UOM_ID"))
{
m_precision = null;
}
return true;
} // beforeSave
@Override
protected boolean afterSave(boolean newRecord, boolean success)
{
if (!success)
{
return success;
}
// Value/Name change in Account
if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name")))
{
MAccount.updateValueDescription(getCtx(), "M_Product_ID=" + getM_Product_ID(), get_TrxName());
}
// Name/Description Change in Asset MAsset.setValueNameDescription
if (!newRecord && (is_ValueChanged("Name") || is_ValueChanged("Description")))
{
String sql = DB.convertSqlToNative("UPDATE A_Asset a "
+ "SET (Name, Description)="
+ "(SELECT SUBSTR((SELECT bp.Name FROM C_BPartner bp WHERE bp.C_BPartner_ID=a.C_BPartner_ID) || ' - ' || p.Name,1,60), p.Description "
+ "FROM M_Product p "
+ "WHERE p.M_Product_ID=a.M_Product_ID) "
+ "WHERE IsActive='Y'"
// + " AND GuaranteeDate > now()"
+ " AND M_Product_ID=" + getM_Product_ID());
int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName());
log.debug("Asset Description updated #" + no);
}
// New - Acct, Tree, Old Costing
if (newRecord)
{
if(!this.isCopying()) | {
insert_Accounting(I_M_Product_Acct.Table_Name,
I_M_Product_Category_Acct.Table_Name,
"p.M_Product_Category_ID=" + getM_Product_Category_ID());
}
else
{
log.info("This M_Product is created via CopyRecordSupport; -> don't insert the default _acct records");
}
insert_Tree(X_AD_Tree.TREETYPE_Product);
}
// Product category changed, then update the accounts
if (!newRecord && is_ValueChanged(I_M_Product.COLUMNNAME_M_Product_Category_ID))
{
update_Accounting(I_M_Product_Acct.Table_Name,
I_M_Product_Category_Acct.Table_Name,
"p.M_Product_Category_ID=" + getM_Product_Category_ID());
}
return true;
} // afterSave
@Override
protected boolean beforeDelete()
{
if (PRODUCTTYPE_Resource.equals(getProductType()) && getS_Resource_ID() > 0)
{
throw new AdempiereException("@S_Resource_ID@<>0");
}
//
return delete_Accounting("M_Product_Acct");
} // beforeDelete
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProduct.java | 1 |
请完成以下Java代码 | public java.lang.String getProductDescription()
{
return get_ValueAsString(COLUMNNAME_ProductDescription);
}
@Override
public void setProductName (final @Nullable java.lang.String ProductName)
{
set_Value (COLUMNNAME_ProductName, ProductName);
}
@Override
public java.lang.String getProductName()
{
return get_ValueAsString(COLUMNNAME_ProductName);
}
@Override
public void setProductNo (final @Nullable java.lang.String ProductNo)
{
set_Value (COLUMNNAME_ProductNo, ProductNo);
}
@Override
public java.lang.String getProductNo()
{
return get_ValueAsString(COLUMNNAME_ProductNo);
}
@Override
public void setQualityRating (final @Nullable BigDecimal QualityRating)
{
set_Value (COLUMNNAME_QualityRating, QualityRating);
}
@Override
public BigDecimal getQualityRating()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QualityRating);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setShelfLifeMinDays (final int ShelfLifeMinDays)
{
set_Value (COLUMNNAME_ShelfLifeMinDays, ShelfLifeMinDays);
}
@Override
public int getShelfLifeMinDays()
{
return get_ValueAsInt(COLUMNNAME_ShelfLifeMinDays);
}
@Override
public void setShelfLifeMinPct (final int ShelfLifeMinPct)
{
set_Value (COLUMNNAME_ShelfLifeMinPct, ShelfLifeMinPct);
}
@Override
public int getShelfLifeMinPct()
{
return get_ValueAsInt(COLUMNNAME_ShelfLifeMinPct);
}
@Override | public void setUPC (final @Nullable java.lang.String UPC)
{
set_Value (COLUMNNAME_UPC, UPC);
}
@Override
public java.lang.String getUPC()
{
return get_ValueAsString(COLUMNNAME_UPC);
}
@Override
public void setUsedForCustomer (final boolean UsedForCustomer)
{
set_Value (COLUMNNAME_UsedForCustomer, UsedForCustomer);
}
@Override
public boolean isUsedForCustomer()
{
return get_ValueAsBoolean(COLUMNNAME_UsedForCustomer);
}
@Override
public void setUsedForVendor (final boolean UsedForVendor)
{
set_Value (COLUMNNAME_UsedForVendor, UsedForVendor);
}
@Override
public boolean isUsedForVendor()
{
return get_ValueAsBoolean(COLUMNNAME_UsedForVendor);
}
@Override
public void setVendorCategory (final @Nullable java.lang.String VendorCategory)
{
set_Value (COLUMNNAME_VendorCategory, VendorCategory);
}
@Override
public java.lang.String getVendorCategory()
{
return get_ValueAsString(COLUMNNAME_VendorCategory);
}
@Override
public void setVendorProductNo (final @Nullable java.lang.String VendorProductNo)
{
set_Value (COLUMNNAME_VendorProductNo, VendorProductNo);
}
@Override
public java.lang.String getVendorProductNo()
{
return get_ValueAsString(COLUMNNAME_VendorProductNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Product.java | 1 |
请完成以下Java代码 | private void enqueueShipmentsForDesadv(
final @NonNull IWorkPackageQueue queue,
final @NonNull I_EDI_Desadv desadv)
{
final List<I_M_InOut> shipments = desadvDAO.retrieveShipmentsWithStatus(desadv, ImmutableSet.of(EDIExportStatus.Pending, EDIExportStatus.Error));
final String trxName = InterfaceWrapperHelper.getTrxName(desadv);
for (final I_M_InOut shipment : shipments)
{
queue.newWorkPackage()
.setAD_PInstance_ID(getPinstanceId())
.bindToTrxName(trxName)
.addElement(shipment)
.buildAndEnqueue();
shipment.setEDI_ExportStatus(I_M_InOut.EDI_EXPORTSTATUS_Enqueued);
InterfaceWrapperHelper.save(shipment);
addLog("Enqueued M_InOut_ID={} for EDI_Desadv_ID={}", shipment.getM_InOut_ID(), desadv.getEDI_Desadv_ID());
}
if(shipments.isEmpty())
{
addLog("Found no M_InOuts to enqueue for EDI_Desadv_ID={}", desadv.getEDI_Desadv_ID());
}
else
{
desadv.setEDI_ExportStatus(I_M_InOut.EDI_EXPORTSTATUS_Enqueued);
InterfaceWrapperHelper.save(desadv);
}
}
@NonNull | private Iterator<I_EDI_Desadv> createIterator()
{
final IQueryBuilder<I_EDI_Desadv> queryBuilder = queryBL.createQueryBuilder(I_EDI_Desadv.class, getCtx(), get_TrxName())
.addOnlyActiveRecordsFilter()
.filter(getProcessInfo().getQueryFilterOrElseFalse());
queryBuilder.orderBy()
.addColumn(I_EDI_Desadv.COLUMNNAME_POReference)
.addColumn(I_EDI_Desadv.COLUMNNAME_EDI_Desadv_ID);
final Iterator<I_EDI_Desadv> iterator = queryBuilder
.create()
.iterate(I_EDI_Desadv.class);
if(!iterator.hasNext())
{
addLog("Found no EDI_Desadvs to enqueue within the current selection");
}
return iterator;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\process\EDI_Desadv_InOut_EnqueueForExport.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.