instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private static ILogicExpression extractMandatoryLogic(@NonNull final GridFieldVO gridFieldVO)
{
if (gridFieldVO.isMandatoryLogicExpression())
{
return gridFieldVO.getMandatoryLogic();
}
else if (gridFieldVO.isMandatory())
{
// consider it mandatory only if is displayed
return gridFieldVO.getDisplayLogic();
}
else
{
return ConstantLogicExpression.FALSE;
}
}
private void collectSpecialField(final DocumentFieldDescriptor.Builder field)
{
if (_specialFieldsCollector == null)
{
return;
}
_specialFieldsCollector.collect(field);
}
private void collectSpecialFieldsDone()
{
if (_specialFieldsCollector == null)
{
return;
}
_specialFieldsCollector.collectFinish();
}
@Nullable
public DocumentFieldDescriptor.Builder getSpecialField_DocumentSummary()
{
return _specialFieldsCollector == null ? null : _specialFieldsCollector.getDocumentSummary();
} | @Nullable
public Map<Characteristic, DocumentFieldDescriptor.Builder> getSpecialField_DocSatusAndDocAction()
{
return _specialFieldsCollector == null ? null : _specialFieldsCollector.getDocStatusAndDocAction();
}
private WidgetTypeStandardNumberPrecision getStandardNumberPrecision()
{
WidgetTypeStandardNumberPrecision standardNumberPrecision = this._standardNumberPrecision;
if (standardNumberPrecision == null)
{
standardNumberPrecision = this._standardNumberPrecision = WidgetTypeStandardNumberPrecision.builder()
.quantityPrecision(getPrecisionFromSysConfigs(SYSCONFIG_QUANTITY_DEFAULT_PRECISION))
.build()
.fallbackTo(WidgetTypeStandardNumberPrecision.DEFAULT);
}
return standardNumberPrecision;
}
@SuppressWarnings("SameParameterValue")
private OptionalInt getPrecisionFromSysConfigs(@NonNull final String sysconfigName)
{
final int precision = sysConfigBL.getIntValue(sysconfigName, -1);
return precision > 0 ? OptionalInt.of(precision) : OptionalInt.empty();
}
private boolean isSkipField(@NonNull final String fieldName)
{
switch (fieldName)
{
case FIELDNAME_AD_Org_ID:
return !sysConfigBL.getBooleanValue(SYS_CONFIG_AD_ORG_ID_IS_DISPLAYED, true);
case FIELDNAME_AD_Client_ID:
return !sysConfigBL.getBooleanValue(SYS_CONFIG_AD_CLIENT_ID_IS_DISPLAYED, true);
default:
return false;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\factory\standard\GridTabVOBasedDocumentEntityDescriptorFactory.java | 1 |
请完成以下Java代码 | public boolean isAllowed(String contextPath, String uri, @Nullable String method,
@Nullable Authentication authentication) {
List<WebInvocationPrivilegeEvaluator> privilegeEvaluators = getDelegate(contextPath, uri, method);
if (privilegeEvaluators.isEmpty()) {
return true;
}
for (WebInvocationPrivilegeEvaluator evaluator : privilegeEvaluators) {
boolean isAllowed = evaluator.isAllowed(contextPath, uri, method, authentication);
if (!isAllowed) {
return false;
}
}
return true;
}
private List<WebInvocationPrivilegeEvaluator> getDelegate(@Nullable String contextPath, String uri,
@Nullable String method) { | FilterInvocation filterInvocation = new FilterInvocation(contextPath, uri, method, this.servletContext);
HttpServletRequest request = filterInvocation.getHttpRequest();
for (RequestMatcherEntry<List<WebInvocationPrivilegeEvaluator>> delegate : this.delegates) {
if (delegate.getRequestMatcher().matches(request)) {
return delegate.getEntry();
}
}
return Collections.emptyList();
}
@Override
public void setServletContext(ServletContext servletContext) {
this.servletContext = servletContext;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\access\RequestMatcherDelegatingWebInvocationPrivilegeEvaluator.java | 1 |
请完成以下Java代码 | public String getExecutionId() {
return executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getActivityId() {
return activityId;
}
public Date getCreatedDate() {
return createdDate;
}
public String getTenantId() {
return tenantId;
} | public static EventSubscriptionDto fromEventSubscription(EventSubscription eventSubscription) {
EventSubscriptionDto dto = new EventSubscriptionDto();
dto.id = eventSubscription.getId();
dto.eventType = eventSubscription.getEventType();
dto.eventName = eventSubscription.getEventName();
dto.executionId = eventSubscription.getExecutionId();
dto.processInstanceId = eventSubscription.getProcessInstanceId();
dto.activityId = eventSubscription.getActivityId();
dto.createdDate = eventSubscription.getCreated();
dto.tenantId = eventSubscription.getTenantId();
return dto;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\EventSubscriptionDto.java | 1 |
请完成以下Java代码 | public CmmnModel getCmmnModel() {
return cmmnModel;
}
public void setCmmnModel(CmmnModel cmmnModel) {
this.cmmnModel = cmmnModel;
}
public String getNewAssigneeId() {
return newAssigneeId;
}
public void setNewAssigneeId(String newAssigneeId) {
this.newAssigneeId = newAssigneeId;
}
public Map<String, PlanItemInstanceEntity> getContinueParentPlanItemInstanceMap() {
return continueParentPlanItemInstanceMap;
}
public void setContinueParentPlanItemInstanceMap(Map<String, PlanItemInstanceEntity> continueParentPlanItemInstanceMap) {
this.continueParentPlanItemInstanceMap = continueParentPlanItemInstanceMap;
}
public void addContinueParentPlanItemInstance(String planItemInstanceId, PlanItemInstanceEntity continueParentPlanItemInstance) {
continueParentPlanItemInstanceMap.put(planItemInstanceId, continueParentPlanItemInstance);
}
public PlanItemInstanceEntity getContinueParentPlanItemInstance(String planItemInstanceId) {
return continueParentPlanItemInstanceMap.get(planItemInstanceId);
}
public Map<String, PlanItemMoveEntry> getMoveToPlanItemMap() {
return moveToPlanItemMap;
} | public void setMoveToPlanItemMap(Map<String, PlanItemMoveEntry> moveToPlanItemMap) {
this.moveToPlanItemMap = moveToPlanItemMap;
}
public PlanItemMoveEntry getMoveToPlanItem(String planItemId) {
return moveToPlanItemMap.get(planItemId);
}
public List<PlanItemMoveEntry> getMoveToPlanItems() {
return new ArrayList<>(moveToPlanItemMap.values());
}
public static class PlanItemMoveEntry {
protected PlanItem originalPlanItem;
protected PlanItem newPlanItem;
public PlanItemMoveEntry(PlanItem originalPlanItem, PlanItem newPlanItem) {
this.originalPlanItem = originalPlanItem;
this.newPlanItem = newPlanItem;
}
public PlanItem getOriginalPlanItem() {
return originalPlanItem;
}
public PlanItem getNewPlanItem() {
return newPlanItem;
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\MovePlanItemInstanceEntityContainer.java | 1 |
请完成以下Java代码 | public String getSourceActivityType() {
return sourceActivityType;
}
public void setSourceActivityType(String sourceActivityType) {
this.sourceActivityType = sourceActivityType;
}
@Override
public String getTargetActivityElementId() {
return targetActivityElementId;
}
@Override
public String getTargetActivityName() {
return targetActivityName;
}
public void setTargetActivityName(String targetActivityName) {
this.targetActivityName = targetActivityName;
}
@Override
public String getTargetActivityType() {
return targetActivityType;
}
public void setTargetActivityType(String targetActivityType) {
this.targetActivityType = targetActivityType;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
BPMNSequenceFlowImpl that = (BPMNSequenceFlowImpl) o;
return (
Objects.equals(getElementId(), that.getElementId()) &&
Objects.equals(sourceActivityElementId, that.getSourceActivityElementId()) &&
Objects.equals(sourceActivityType, that.getSourceActivityType()) &&
Objects.equals(sourceActivityName, that.getSourceActivityName()) &&
Objects.equals(targetActivityElementId, that.getTargetActivityElementId()) && | Objects.equals(targetActivityType, that.getTargetActivityType()) &&
Objects.equals(targetActivityName, that.getTargetActivityName())
);
}
@Override
public int hashCode() {
return Objects.hash(getElementId(), sourceActivityElementId, targetActivityElementId);
}
@Override
public String toString() {
return (
"SequenceFlowImpl{" +
"sourceActivityElementId='" +
sourceActivityElementId +
'\'' +
", sourceActivityName='" +
sourceActivityName +
'\'' +
", sourceActivityType='" +
sourceActivityType +
'\'' +
", targetActivityElementId='" +
targetActivityElementId +
'\'' +
", targetActivityName='" +
targetActivityName +
'\'' +
", targetActivityType='" +
targetActivityType +
'\'' +
'}'
);
}
} | repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\BPMNSequenceFlowImpl.java | 1 |
请完成以下Java代码 | public class LDAPConnectionUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(LDAPConnectionUtil.class);
public static InitialDirContext creatDirectoryContext(LDAPConfiguration ldapConfigurator) {
return createDirectoryContext(ldapConfigurator, ldapConfigurator.getUser(), ldapConfigurator.getPassword());
}
public static InitialDirContext createDirectoryContext(LDAPConfiguration ldapConfigurator, String principal, String credentials) {
Properties properties = new Properties();
properties.put(Context.INITIAL_CONTEXT_FACTORY, ldapConfigurator.getInitialContextFactory());
properties.put(Context.PROVIDER_URL, ldapConfigurator.getServer() + ":" + ldapConfigurator.getPort());
properties.put(Context.SECURITY_AUTHENTICATION, ldapConfigurator.getSecurityAuthentication());
properties.put(Context.SECURITY_PRINCIPAL, principal);
properties.put(Context.SECURITY_CREDENTIALS, credentials);
if (ldapConfigurator.isConnectionPooling()) {
properties.put("com.sun.jndi.ldap.connect.pool", "true");
}
if (ldapConfigurator.getCustomConnectionParameters() != null) {
for (String customParameter : ldapConfigurator.getCustomConnectionParameters().keySet()) { | properties.put(customParameter, ldapConfigurator.getCustomConnectionParameters().get(customParameter));
}
}
InitialDirContext context;
try {
context = new InitialDirContext(properties);
} catch (NamingException e) {
LOGGER.warn("Could not create InitialDirContext for LDAP connection: {}", e.getMessage());
throw new FlowableException("Could not create InitialDirContext for LDAP connection: " + e.getMessage(), e);
}
return context;
}
public static void closeDirectoryContext(InitialDirContext initialDirContext) {
try {
initialDirContext.close();
} catch (NamingException e) {
LOGGER.warn("Could not close InitialDirContext correctly!", e);
}
}
} | repos\flowable-engine-main\modules\flowable-ldap\src\main\java\org\flowable\ldap\LDAPConnectionUtil.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public T findOne(final long id) {
return getDao().findById(id).orElse(null);
}
@Override
public List<T> findAll() {
return Lists.newArrayList(getDao().findAll());
}
@Override
public T create(final T entity) {
return getDao().save(entity);
}
@Override | public T update(final T entity) {
return getDao().save(entity);
}
@Override
public void delete(final T entity) {
getDao().delete(entity);
}
@Override
public void deleteById(final long entityId) {
getDao().deleteById(entityId);
}
protected abstract CrudRepository<T, Serializable> getDao();
} | repos\tutorials-master\persistence-modules\spring-data-jpa-enterprise\src\main\java\com\baeldung\boot\services\impl\AbstractSpringDataJpaService.java | 2 |
请完成以下Java代码 | 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 ResponseEntity<BufferedImage> zxingPDF417Barcode(@RequestBody String barcode) throws Exception {
return okResponse(ZxingBarcodeGenerator.generatePDF417BarcodeImage(barcode));
}
@PostMapping(value = "/zxing/qrcode", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<BufferedImage> zxingQRCode(@RequestBody String barcode) throws Exception {
return okResponse(ZxingBarcodeGenerator.generateQRCodeImage(barcode));
}
//QRGen
@PostMapping(value = "/qrgen/qrcode", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<BufferedImage> qrgenQRCode(@RequestBody String barcode) throws Exception {
return okResponse(QRGenBarcodeGenerator.generateQRCodeImage(barcode));
} | @GetMapping(value = "/okapi/2d/{barcode}", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<BufferedImage> okapiBarcode(@PathVariable("barcode") String barcode) throws Exception {
return okResponse(OkapiBarcodeGenerator.generateOkapiBarcode(barcode));
}
private ResponseEntity<BufferedImage> okResponse(BufferedImage image) {
return new ResponseEntity<>(image, HttpStatus.OK);
}
//QRCodegen
@PostMapping(value = "/qrcodegen/qrcode", produces = MediaType.IMAGE_PNG_VALUE)
public ResponseEntity<BufferedImage> qrcodegenQRCode(@RequestBody String barcode) throws Exception {
return okResponse(QRCodegenGenerator.generateQrcode(barcode));
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-libraries\src\main\java\com\baeldung\barcodes\BarcodesController.java | 1 |
请完成以下Java代码 | public String getConfiguration() {
return configuration;
}
public void setConfiguration(String configuration) {
this.configuration = configuration;
}
public String getActivityId() {
return activityId;
}
public void setActivityId(String activityId) {
this.activityId = activityId;
this.activity = null;
}
public Date getCreated() {
return created;
}
public void setCreated(Date created) {
this.created = created;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((id == null) ? 0 : id.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false; | if (getClass() != obj.getClass())
return false;
EventSubscriptionEntity other = (EventSubscriptionEntity) obj;
if (id == null) {
if (other.id != null)
return false;
} else if (!id.equals(other.id))
return false;
return true;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<String>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<String, Class>();
if (executionId != null) {
referenceIdAndClass.put(executionId, ExecutionEntity.class);
}
return referenceIdAndClass;
}
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", eventType=" + eventType
+ ", eventName=" + eventName
+ ", executionId=" + executionId
+ ", processInstanceId=" + processInstanceId
+ ", activityId=" + activityId
+ ", tenantId=" + tenantId
+ ", configuration=" + configuration
+ ", revision=" + revision
+ ", created=" + created
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\EventSubscriptionEntity.java | 1 |
请完成以下Java代码 | public Criteria andProvinceNotIn(List<String> values) {
addCriterion("province not in", values, "province");
return (Criteria) this;
}
public Criteria andProvinceBetween(String value1, String value2) {
addCriterion("province between", value1, value2, "province");
return (Criteria) this;
}
public Criteria andProvinceNotBetween(String value1, String value2) {
addCriterion("province not between", value1, value2, "province");
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\UmsMemberLoginLogExample.java | 1 |
请完成以下Java代码 | public Map<String, Object> getAttributes() {
return this.attributes;
}
}
public static void main(String[] args) {
String result = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>\r\n" +
" <cas:authenticationSuccess>\r\n" +
" <cas:user>admin</cas:user>\r\n" +
" <cas:attributes>\r\n" +
" <cas:credentialType>UsernamePasswordCredential</cas:credentialType>\r\n" +
" <cas:isFromNewLogin>true</cas:isFromNewLogin>\r\n" +
" <cas:authenticationDate>2019-08-01T19:33:21.527+08:00[Asia/Shanghai]</cas:authenticationDate>\r\n" +
" <cas:authenticationMethod>RestAuthenticationHandler</cas:authenticationMethod>\r\n" +
" <cas:successfulAuthenticationHandlers>RestAuthenticationHandler</cas:successfulAuthenticationHandlers>\r\n" +
" <cas:longTermAuthenticationRequestTokenUsed>false</cas:longTermAuthenticationRequestTokenUsed>\r\n" +
" </cas:attributes>\r\n" +
" </cas:authenticationSuccess>\r\n" + | "</cas:serviceResponse>";
String errorRes = "<cas:serviceResponse xmlns:cas='http://www.yale.edu/tp/cas'>\r\n" +
" <cas:authenticationFailure code=\"INVALID_TICKET\">未能够识别出目标 'ST-5-1g-9cNES6KXNRwq-GuRET103sm0-DESKTOP-VKLS8B3'票根</cas:authenticationFailure>\r\n" +
"</cas:serviceResponse>";
String error = XmlUtils.getTextForElement(errorRes, "authenticationFailure");
//System.out.println("------"+error);
String error2 = XmlUtils.getTextForElement(result, "authenticationFailure");
//System.out.println("------"+error2);
String principal = XmlUtils.getTextForElement(result, "user");
//System.out.println("---principal---"+principal);
Map<String, Object> attributes = XmlUtils.extractCustomAttributes(result);
System.out.println("---attributes---"+attributes);
}
} | repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\cas\util\XmlUtils.java | 1 |
请完成以下Java代码 | public QueryInsertExecutor<ToModelType, FromModelType> mapColumnToSql(final String toColumnName, final String fromSql)
{
final IQueryInsertFromColumn from = new SqlQueryInsertFromColumn(fromSql);
mapColumn(toColumnName, from);
return this;
}
@Override
public QueryInsertExecutor<ToModelType, FromModelType> mapPrimaryKey()
{
final String toColumnName = getToKeyColumnName();
final IQueryInsertFromColumn from = new PrimaryKeyQueryInsertFromColumn(getToTableName());
mapColumn(toColumnName, from);
return this;
}
@Override
public QueryInsertExecutor<ToModelType, FromModelType> creatingSelectionOfInsertedRows()
{
this.createSelectionOfInsertedRows = true;
return this;
}
/* package */ boolean isCreateSelectionOfInsertedRows()
{
return createSelectionOfInsertedRows;
}
/* package */String getToKeyColumnName()
{
return InterfaceWrapperHelper.getKeyColumnName(toModelClass);
}
/**
* @return "To ColumnName" to "From Column" map
*/
/* package */ Map<String, IQueryInsertFromColumn> getColumnMapping()
{ | return toColumn2fromColumnRO;
}
/* package */ boolean isEmpty()
{
return toColumn2fromColumn.isEmpty();
}
/* package */ String getToTableName()
{
return toTableName;
}
/* package */ Class<ToModelType> getToModelClass()
{
return toModelClass;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\QueryInsertExecutor.java | 1 |
请完成以下Java代码 | public class FlatrateTermImportProcess extends SimpleImportProcessTemplate<I_I_Flatrate_Term>
{
private final FlatrateTermImporter flatRateImporter;
public FlatrateTermImportProcess()
{
flatRateImporter = FlatrateTermImporter.newInstance(this);
}
@Override
public Class<I_I_Flatrate_Term> getImportModelClass()
{
return I_I_Flatrate_Term.class;
}
@Override
public String getImportTableName()
{
return I_I_Flatrate_Term.Table_Name;
}
@Override
protected String getTargetTableName()
{
return I_C_Flatrate_Term.Table_Name;
}
@Override
protected String getImportOrderBySql()
{
return I_I_Flatrate_Term.COLUMNNAME_I_Flatrate_Term_ID;
}
@Override
protected void updateAndValidateImportRecordsImpl()
{
final ImportRecordsSelection selection = getImportRecordsSelection();
final String sqlImportWhereClause = ImportTableDescriptor.COLUMNNAME_I_IsImported + "<>" + DB.TO_BOOLEAN(true)
+ "\n " + selection.toSqlWhereClause("i");
FlatrateTermImportTableSqlUpdater.updateFlatrateTermImportTable(sqlImportWhereClause); | }
@Override
public I_I_Flatrate_Term retrieveImportRecord(final Properties ctx, final ResultSet rs)
{
final PO po = TableModelLoader.instance.getPO(ctx, I_I_Flatrate_Term.Table_Name, rs, ITrx.TRXNAME_ThreadInherited);
return InterfaceWrapperHelper.create(po, I_I_Flatrate_Term.class);
}
@Override
protected ImportRecordResult importRecord(final @NonNull IMutable<Object> state,
final @NonNull I_I_Flatrate_Term importRecord,
final boolean isInsertOnly /* not used. This import always inserts*/)
{
flatRateImporter.importRecord(importRecord);
return ImportRecordResult.Inserted;
}
@Override
protected void markImported(final I_I_Flatrate_Term importRecord)
{
// NOTE: overriding the method from abstract class because in case of I_Flatrate_Term,
// * the I_IsImported is a List (as it should be) and not YesNo
// * there is no Processing column
importRecord.setI_IsImported(X_I_Flatrate_Term.I_ISIMPORTED_Imported);
importRecord.setProcessed(true);
InterfaceWrapperHelper.save(importRecord);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\impexp\FlatrateTermImportProcess.java | 1 |
请完成以下Java代码 | protected ProcessPreconditionsResolution checkPreconditionsApplicable()
{
if (!getSelectedRowIds().isSingleDocumentId())
{
final String internalReason = StringUtils.formatMessage("Select one line");
return ProcessPreconditionsResolution.rejectWithInternalReason(internalReason);
}
final PPOrderLineRow row = getSingleSelectedRow();
if (row.isSourceHU())
{
return ProcessPreconditionsResolution.rejectWithInternalReason("Not available for source HU line");
}
if (row.getPpOrderQtyId() == null)
{
final String internalReason = StringUtils.formatMessage("Not an issue/receipt line");
return ProcessPreconditionsResolution.rejectWithInternalReason(internalReason);
}
if (row.isProcessed() && !(BOMComponentIssueMethod.IssueOnlyForReceived.equals(row.getIssueMethod())))
{
final String internalReason = StringUtils.formatMessage("Only not processed");
return ProcessPreconditionsResolution.rejectWithInternalReason(internalReason);
}
return ProcessPreconditionsResolution.accept();
} | @Override
protected String doIt() throws Exception
{
final PPOrderQtyId ppOrderQtyId = getSingleSelectedRow().getPpOrderQtyId();
final I_PP_Order_Qty candidate = huPPOrderQtyDAO.retrieveById(ppOrderQtyId);
huPPOrderQtyBL.reverseDraftCandidate(candidate);
return MSG_OK;
}
@Override
protected void postProcess(final boolean success)
{
getView().invalidateAll();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\pporder\process\WEBUI_PP_Order_ReverseCandidate.java | 1 |
请完成以下Java代码 | private IInfoQueryCriteria getInfoQueryCriteria(final I_AD_InfoColumn infoColumn, final boolean getDefaultIfNotFound)
{
final int infoColumnId = infoColumn.getAD_InfoColumn_ID();
if (criteriasById.containsKey(infoColumnId))
{
return criteriasById.get(infoColumnId);
}
final IInfoQueryCriteria criteria;
final String classname = infoColumn.getClassname();
if (Check.isEmpty(classname, true))
{
if (getDefaultIfNotFound)
{
criteria = new InfoQueryCriteriaGeneral();
}
else
{
return null;
}
}
else
{
criteria = Util.getInstance(IInfoQueryCriteria.class, classname);
}
criteria.init(this, infoColumn, searchText);
criteriasById.put(infoColumnId, criteria);
return criteria;
}
private IInfoColumnController getInfoColumnControllerOrNull(final I_AD_InfoColumn infoColumn)
{
final IInfoQueryCriteria criteria = getInfoQueryCriteria(infoColumn, false); // don't retrieve the default
if (criteria == null)
{
return null;
}
if (criteria instanceof IInfoColumnController)
{
final IInfoColumnController columnController = (IInfoColumnController)criteria;
return columnController;
}
return null;
}
@Override
protected void prepareTable(final Info_Column[] layout, final String from, final String staticWhere, final String orderBy)
{
super.prepareTable(layout, from, staticWhere, orderBy);
setupInfoColumnControllerBindings();
}
private void setupInfoColumnControllerBindings()
{
for (int i = 0; i < p_layout.length; i++)
{
final int columnIndexModel = i;
final Info_Column infoColumn = p_layout[columnIndexModel];
final IInfoColumnController columnController = infoColumn.getColumnController(); | final List<Info_Column> dependentColumns = infoColumn.getDependentColumns();
if (columnController == null
&& (dependentColumns == null || dependentColumns.isEmpty()))
{
// if there is no controller on this column and there are no dependent columns
// then there is no point for adding a binder
continue;
}
final TableModel tableModel = getTableModel();
final InfoColumnControllerBinder binder = new InfoColumnControllerBinder(this, infoColumn, columnIndexModel);
tableModel.addTableModelListener(binder);
}
}
@Override
public void setValue(final Info_Column infoColumn, final int rowIndexModel, final Object value)
{
final int colIndexModel = getColumnIndex(infoColumn);
if (colIndexModel < 0)
{
return;
}
p_table.setValueAt(value, rowIndexModel, colIndexModel);
}
@Override
public void setValueByColumnName(final String columnName, final int rowIndexModel, final Object value)
{
final int colIndexModel = getColumnIndex(columnName);
if (colIndexModel < 0)
{
return;
}
p_table.setValueAt(value, rowIndexModel, colIndexModel);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\apps\search\InfoSimple.java | 1 |
请完成以下Java代码 | protected void initializeExpressionManager() {
if (processEngineConfiguration.getExpressionManager() == null && applicationContext != null) {
processEngineConfiguration.setExpressionManager(
new SpringExpressionManager(applicationContext, processEngineConfiguration.getBeans()));
}
}
protected void initializeTransactionExternallyManaged() {
if (processEngineConfiguration instanceof SpringProcessEngineConfiguration) { // remark: any config can be injected, so we cannot have SpringConfiguration as member
SpringProcessEngineConfiguration engineConfiguration = (SpringProcessEngineConfiguration) processEngineConfiguration;
if (engineConfiguration.getTransactionManager() != null) {
processEngineConfiguration.setTransactionsExternallyManaged(true);
}
}
}
public Class<ProcessEngine> getObjectType() {
return ProcessEngine.class; | }
public boolean isSingleton() {
return true;
}
// getters and setters //////////////////////////////////////////////////////
public ProcessEngineConfigurationImpl getProcessEngineConfiguration() {
return processEngineConfiguration;
}
public void setProcessEngineConfiguration(ProcessEngineConfigurationImpl processEngineConfiguration) {
this.processEngineConfiguration = processEngineConfiguration;
}
} | repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\ProcessEngineFactoryBean.java | 1 |
请完成以下Java代码 | public static void main(String[] args) throws Exception
{
if (args.length < 1)
{
return;
}
TaggerImpl tagger = new TaggerImpl(Mode.TEST);
InputStream stream = null;
try
{
stream = IOUtil.newInputStream(args[0]);
}
catch (IOException e)
{
System.err.printf("model not exits for %s", args[0]);
return;
}
if (stream != null && !tagger.open(stream, 2, 0, 1.0))
{
System.err.println("open error");
return;
}
System.out.println("Done reading model");
if (args.length >= 2)
{
InputStream fis = IOUtil.newInputStream(args[1]);
InputStreamReader isr = new InputStreamReader(fis, "UTF-8");
BufferedReader br = new BufferedReader(isr);
while (true)
{
ReadStatus status = tagger.read(br);
if (ReadStatus.ERROR == status) | {
System.err.println("read error");
return;
}
else if (ReadStatus.EOF == status)
{
break;
}
if (tagger.getX_().isEmpty())
{
break;
}
if (!tagger.parse())
{
System.err.println("parse error");
return;
}
System.out.print(tagger.toString());
}
br.close();
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\TaggerImpl.java | 1 |
请完成以下Java代码 | public String getMemberNickName() {
return memberNickName;
}
public void setMemberNickName(String memberNickName) {
this.memberNickName = memberNickName;
}
public String getMemberIcon() {
return memberIcon;
}
public void setMemberIcon(String memberIcon) {
this.memberIcon = memberIcon;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
} | @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(", subjectId=").append(subjectId);
sb.append(", memberNickName=").append(memberNickName);
sb.append(", memberIcon=").append(memberIcon);
sb.append(", content=").append(content);
sb.append(", createTime=").append(createTime);
sb.append(", showStatus=").append(showStatus);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsSubjectComment.java | 1 |
请完成以下Java代码 | public void setDateReval (Timestamp DateReval)
{
set_Value (COLUMNNAME_DateReval, DateReval);
}
/** Get Revaluation Date.
@return Date of Revaluation
*/
public Timestamp getDateReval ()
{
return (Timestamp)get_Value(COLUMNNAME_DateReval);
}
/** Set Accounting Fact.
@param Fact_Acct_ID Accounting Fact */
public void setFact_Acct_ID (int Fact_Acct_ID)
{
if (Fact_Acct_ID < 1)
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, null);
else
set_ValueNoCheck (COLUMNNAME_Fact_Acct_ID, Integer.valueOf(Fact_Acct_ID));
}
/** Get Accounting Fact.
@return Accounting Fact */
public int getFact_Acct_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Fact_Acct_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Grand Total.
@param GrandTotal
Total amount of document
*/
public void setGrandTotal (BigDecimal GrandTotal)
{
set_Value (COLUMNNAME_GrandTotal, GrandTotal);
}
/** Get Grand Total.
@return Total amount of document
*/
public BigDecimal getGrandTotal ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_GrandTotal);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Include All Currencies.
@param IsAllCurrencies
Report not just foreign currency Invoices
*/
public void setIsAllCurrencies (boolean IsAllCurrencies)
{
set_Value (COLUMNNAME_IsAllCurrencies, Boolean.valueOf(IsAllCurrencies));
}
/** Get Include All Currencies.
@return Report not just foreign currency Invoices
*/
public boolean isAllCurrencies ()
{
Object oo = get_Value(COLUMNNAME_IsAllCurrencies);
if (oo != null)
{
if (oo instanceof Boolean) | return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Open Amount.
@param OpenAmt
Open item amount
*/
public void setOpenAmt (BigDecimal OpenAmt)
{
set_Value (COLUMNNAME_OpenAmt, OpenAmt);
}
/** Get Open Amount.
@return Open item amount
*/
public BigDecimal getOpenAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OpenAmt);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Percent.
@param Percent
Percentage
*/
public void setPercent (BigDecimal Percent)
{
set_Value (COLUMNNAME_Percent, Percent);
}
/** Get Percent.
@return Percentage
*/
public BigDecimal getPercent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent);
if (bd == null)
return Env.ZERO;
return bd;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_T_InvoiceGL.java | 1 |
请完成以下Java代码 | public static DecisionEvaluationBuilder evaluateDecisionTableById(CommandExecutor commandExecutor, String decisionDefinitionId) {
DecisionTableEvaluationBuilderImpl builder = new DecisionTableEvaluationBuilderImpl(commandExecutor);
builder.decisionDefinitionId = decisionDefinitionId;
return builder;
}
// getters ////////////////////////////////////
public String getDecisionDefinitionKey() {
return decisionDefinitionKey;
}
public String getDecisionDefinitionId() {
return decisionDefinitionId;
}
public Integer getVersion() {
return version; | }
public Map<String, Object> getVariables() {
return variables;
}
public String getDecisionDefinitionTenantId() {
return decisionDefinitionTenantId;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\dmn\DecisionTableEvaluationBuilderImpl.java | 1 |
请完成以下Java代码 | public void launch() {
log.info("[{}] Launching consumer", name);
consumerTask = consumerExecutor.submit(() -> {
if (threadPrefix != null) {
ThingsBoardThreadFactory.addThreadNamePrefix(threadPrefix);
}
try {
consumerLoop(consumer);
} catch (Throwable e) {
log.error("Failure in consumer loop", e);
}
log.info("[{}] Consumer stopped", name);
});
}
private void consumerLoop(TbQueueConsumer<M> consumer) {
while (!stopped && !consumer.isStopped()) {
try {
List<M> msgs = consumer.poll(pollInterval);
if (msgs.isEmpty()) {
continue;
}
msgPackProcessor.process(msgs, consumer);
} catch (Exception e) {
if (!consumer.isStopped()) {
log.warn("Failed to process messages from queue", e);
try {
Thread.sleep(pollInterval);
} catch (InterruptedException interruptedException) {
log.trace("Failed to wait until the server has capacity to handle new requests", interruptedException); | }
}
}
}
}
public void stop() {
log.debug("[{}] Stopping consumer", name);
stopped = true;
consumer.unsubscribe();
try {
if (consumerTask != null) {
consumerTask.get(10, TimeUnit.SECONDS);
}
} catch (InterruptedException | ExecutionException | TimeoutException e) {
log.error("[{}] Failed to await consumer loop stop", name, e);
}
}
public interface MsgPackProcessor<M extends TbQueueMsg> {
void process(List<M> msgs, TbQueueConsumer<M> consumer) throws Exception;
}
} | repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\common\consumer\QueueConsumerManager.java | 1 |
请完成以下Java代码 | public void onConnect(SocketIOClient client) {
if (client != null) {
String username = client.getHandshakeData().getSingleUrlParam("username");
String password = client.getHandshakeData().getSingleUrlParam("password");
String sessionId = client.getSessionId().toString();
logger.info("连接成功, username=" + username + ", password=" + password + ", sessionId=" + sessionId);
} else {
logger.error("客户端为空");
}
}
//添加@OnDisconnect事件,客户端断开连接时调用,刷新客户端信息
@OnDisconnect
public void onDisconnect(SocketIOClient client) {
logger.info("客户端断开连接, sessionId=" + client.getSessionId().toString());
client.disconnect();
}
// 消息接收入口
@OnEvent(value = "chatevent")
public void onEvent(SocketIOClient client, AckRequest ackRequest, ChatMessage chat) {
logger.info("接收到客户端消息");
if (ackRequest.isAckRequested()) { | // send ack response with data to client
ackRequest.sendAckData("服务器回答chatevent, userName=" + chat.getUserName() + ",message=" + chat.getMessage());
}
}
// 登录接口
@OnEvent(value = "login")
public void onLogin(SocketIOClient client, AckRequest ackRequest, LoginRequest message) {
logger.info("接收到客户端登录消息");
if (ackRequest.isAckRequested()) {
// send ack response with data to client
ackRequest.sendAckData("服务器回答login", message.getCode(), message.getBody());
}
}
} | repos\SpringBootBucket-master\springboot-socketio\src\main\java\com\xncoding\jwt\handler\MessageEventHandler.java | 1 |
请完成以下Java代码 | public int getDoc_User_ID(@NonNull final DocumentTableFields docFields)
{
return extractQMAnalysisReport(docFields).getCreatedBy();
}
@Override
public LocalDate getDocumentDate(@NonNull final DocumentTableFields docFields)
{
return TimeUtil.asLocalDate(extractQMAnalysisReport(docFields).getDateDoc());
}
/**
* Sets the <code>Processed</code> flag of the given <code>dunningDoc</code> lines.
* <p>
* Assumes that the given doc is not yet processed.
*/
@Override
public String completeIt(@NonNull final DocumentTableFields docFields)
{
final I_QM_Analysis_Report analysisReport = extractQMAnalysisReport(docFields);
analysisReport.setDocAction(IDocument.ACTION_ReActivate);
if (analysisReport.isProcessed())
{
throw new AdempiereException("@Processed@=@Y@");
}
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNone(analysisReport.getM_AttributeSetInstance_ID());
final I_M_Material_Tracking materialTracking = materialTrackingAttributeBL.getMaterialTrackingOrNull(asiId);
if (materialTracking != null)
{
final I_M_Material_Tracking_Ref ref = materialTrackingDAO.createMaterialTrackingRefNoSave(materialTracking, analysisReport);
InterfaceWrapperHelper.save(ref);
}
analysisReport.setProcessed(true);
return IDocument.STATUS_Completed;
}
@Override
public void voidIt(final DocumentTableFields docFields) | {
final I_QM_Analysis_Report analysisReport = extractQMAnalysisReport(docFields);
analysisReport.setProcessed(true);
analysisReport.setDocAction(IDocument.ACTION_None);
}
@Override
public void reactivateIt(@NonNull final DocumentTableFields docFields)
{
final I_QM_Analysis_Report analysisReport = extractQMAnalysisReport(docFields);
analysisReport.setProcessed(false);
analysisReport.setDocAction(IDocument.ACTION_Complete);
}
private static I_QM_Analysis_Report extractQMAnalysisReport(@NonNull final DocumentTableFields docFields)
{
return InterfaceWrapperHelper.create(docFields, I_QM_Analysis_Report.class);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.qualitymgmt\src\main\java\de\metas\qualitymgmt\analysis\QMAnalysisReportDocumentHandler.java | 1 |
请完成以下Java代码 | public void println() {
String separator = System.lineSeparator();
try {
this.out.write(separator.toCharArray(), 0, separator.length());
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
this.prependIndent = true;
}
/**
* Increase the indentation level and execute the {@link Runnable}. Decrease the
* indentation level on completion.
* @param runnable the code to execute withing an extra indentation level
*/
public void indented(Runnable runnable) {
indent();
runnable.run();
outdent();
}
/**
* Increase the indentation level.
*/
private void indent() {
this.level++;
refreshIndent();
}
/**
* Decrease the indentation level.
*/
private void outdent() {
this.level--;
refreshIndent();
}
private void refreshIndent() {
this.indent = this.indentStrategy.apply(this.level);
}
@Override
public void write(char[] chars, int offset, int length) {
try {
if (this.prependIndent) { | this.out.write(this.indent.toCharArray(), 0, this.indent.length());
this.prependIndent = false;
}
this.out.write(chars, offset, length);
}
catch (IOException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public void flush() throws IOException {
this.out.flush();
}
@Override
public void close() throws IOException {
this.out.close();
}
} | repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\io\IndentingWriter.java | 1 |
请完成以下Java代码 | public List<JsonReference> getReferences(
@NonNull final String attributeType,
@NonNull final Function<String, String> valueProvider)
{
return getValuesByKeyAttributeKey(attributeType, valueProvider)
.asMap().entrySet().stream()
.map(entry -> JsonReference.builder()
.kind(Integer.parseInt(entry.getKey()))
.value(concatValues(entry.getValue()))
.build())
.collect(Collectors.toList());
}
private static String concatValues(@NonNull final Collection<String> values)
{
return String.join(" ", values);
}
@NonNull
public String getSingleValue(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider)
{
return concatValues(getValueList(attributeType, valueProvider));
}
@NonNull
private ImmutableList<String> getValueList(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider)
{
return streamEligibleConfigs(attributeType, valueProvider)
.map(config -> valueProvider.apply(config.getAttributeValue()))
.filter(Check::isNotBlank)
.collect(ImmutableList.toImmutableList());
}
public ImmutableList<String> getDetailGroupKeysForType(@NonNull final String attributeType, @NonNull final Function<String, String> valueProvider)
{
return streamEligibleConfigs(attributeType, valueProvider)
.map(JsonMappingConfig::getGroupKey)
.filter(Check::isNotBlank)
.distinct()
.collect(ImmutableList.toImmutableList());
}
public List<JsonDetail> getDetailsForGroupAndType(
@NonNull final String attributeGroupKey,
@NonNull final String attributeType, | @NonNull final Function<String, String> valueProvider)
{
final Map<Integer, String> detailsByKindId = streamEligibleConfigs(attributeType, valueProvider)
.filter(config -> attributeGroupKey.equals(config.getGroupKey()))
.filter(config -> Check.isNotBlank(config.getAttributeKey()))
.map(config -> new AbstractMap.SimpleImmutableEntry<>(
Integer.parseInt(config.getAttributeKey()),
valueProvider.apply(config.getAttributeValue())))
.filter(entry -> Check.isNotBlank(entry.getValue()))
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.joining(" "))));
return detailsByKindId.entrySet().stream()
.map(entry -> JsonDetail.builder()
.kindId(entry.getKey())
.value(entry.getValue())
.build())
.collect(Collectors.toList());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.client.nshift\src\main\java\de\metas\shipper\client\nshift\NShiftMappingConfigs.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class Vehicle {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String brand;
private String model;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getBrand() { | return brand;
}
public void setBrand(String brand) {
this.brand = brand;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
} | repos\tutorials-master\persistence-modules\spring-jpa-2\src\main\java\com\baeldung\inheritancevscomposition\inheritance\Vehicle.java | 2 |
请完成以下Java代码 | public static Collector<ShipmentScheduleAndJobSchedules, ?, ShipmentScheduleAndJobSchedulesCollection> collect()
{
return GuavaCollectors.collectUsingListAccumulator(ShipmentScheduleAndJobSchedulesCollection::ofList);
}
public boolean isEmpty() {return list.isEmpty();}
@Override
public @NotNull Iterator<ShipmentScheduleAndJobSchedules> iterator() {return list.iterator();}
public ImmutableSet<PickingJobScheduleId> getJobScheduleIds()
{
return list.stream()
.flatMap(schedule -> schedule.getJobScheduleIds().stream())
.collect(ImmutableSet.toImmutableSet());
}
public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIdsWithoutJobSchedules()
{ | return getShipmentScheduleIds(schedule -> !schedule.hasJobSchedules());
}
public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIdsWithJobSchedules()
{
return getShipmentScheduleIds(ShipmentScheduleAndJobSchedules::hasJobSchedules);
}
public ImmutableSet<ShipmentScheduleId> getShipmentScheduleIds(@NonNull final Predicate<ShipmentScheduleAndJobSchedules> filter)
{
return list.stream()
.filter(filter)
.map(ShipmentScheduleAndJobSchedules::getShipmentScheduleId)
.collect(ImmutableSet.toImmutableSet());
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentScheduleAndJobSchedulesCollection.java | 1 |
请完成以下Java代码 | public void registerCallout()
{
Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this);
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = {
I_C_Fiscal_Representation.COLUMNNAME_ValidFrom
})
public void addFiscalRepresentationValidFromTo(final I_C_Fiscal_Representation fiscalRep)
{
if (fiscalRep.getValidFrom() != null && fiscalRep.getValidTo() != null && !fiscalRepresentationBL.isValidFromDate(fiscalRep))
{
fiscalRepresentationBL.updateValidFrom(fiscalRep);
}
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = {
I_C_Fiscal_Representation.COLUMNNAME_ValidTo
})
public void addFiscalRepresentationValidTo(final I_C_Fiscal_Representation fiscalRep)
{
if (fiscalRep.getValidTo() != null && fiscalRep.getValidFrom() != null && !fiscalRepresentationBL.isValidToDate(fiscalRep))
{
fiscalRepresentationBL.updateValidTo(fiscalRep);
}
}
@ModelChange(timings = {
ModelValidator.TYPE_BEFORE_CHANGE
}, ifColumnsChanged = {
I_C_Fiscal_Representation.COLUMNNAME_C_BPartner_Location_ID
})
public void addFiscalRepresentationLocationId(final I_C_Fiscal_Representation fiscalRep)
{
fiscalRepresentationBL.updateCountryId(fiscalRep);
}
@CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_ValidFrom })
public void updateFiscalRepresentationValidFrom(final I_C_Fiscal_Representation fiscalRep)
{
if (fiscalRep.getValidTo() != null && fiscalRep.getValidFrom() != null && !fiscalRepresentationBL.isValidFromDate(fiscalRep)) | {
fiscalRepresentationBL.updateValidFrom(fiscalRep);
}
}
@CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_C_BPartner_Location_ID })
public void updateFiscalRepresentationLocationId(final I_C_Fiscal_Representation fiscalRep)
{
fiscalRepresentationBL.updateCountryId(fiscalRep);
}
@CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_ValidTo })
public void updateFiscalRepresentationValidTo(final I_C_Fiscal_Representation fiscalRep)
{
if (fiscalRep.getValidTo() != null && fiscalRep.getValidFrom() != null && !fiscalRepresentationBL.isValidToDate(fiscalRep))
{
fiscalRepresentationBL.updateValidTo(fiscalRep);
}
}
@CalloutMethod(columnNames = { I_C_Fiscal_Representation.COLUMNNAME_C_BPartner_Representative_ID })
public void updateFiscalRepresentationPartner(final I_C_Fiscal_Representation fiscalRep)
{
fiscalRep.setC_BPartner_Location_ID(-1);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\organization\interceptors\C_Fiscal_Representation.java | 1 |
请在Spring Boot框架中完成以下Java代码 | AnalysingService analysingService() {
return new AnalysingService();
}
public static class AnalysingService {
private final AtomicReference<String> stringAtomicReference = new AtomicReference<>();
public void dump(String projectId) {
this.stringAtomicReference.set(projectId);
}
public AtomicReference<String> getStringAtomicReference() {
return stringAtomicReference;
}
}
@Bean
IntegrationFlow inboundProcess(FlowableInboundGateway inboundGateway) {
return IntegrationFlow
.from(inboundGateway)
.handle(new GenericHandler<DelegateExecution>() {
@Override
public Object handle(DelegateExecution execution, MessageHeaders headers) {
return MessageBuilder.withPayload(execution)
.setHeader("projectId", "2143243")
.setHeader("orderId", "246") | .copyHeaders(headers).build();
}
})
.get();
}
@Bean
CommandLineRunner init(
final AnalysingService analysingService,
final RuntimeService runtimeService) {
return new CommandLineRunner() {
@Override
public void run(String... strings) throws Exception {
String integrationGatewayProcess = "integrationGatewayProcess";
runtimeService.startProcessInstanceByKey(
integrationGatewayProcess, Collections.singletonMap("customerId", (Object) 232L));
System.out.println("projectId=" + analysingService.getStringAtomicReference().get());
}
};
} // ...
} | repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-samples\flowable-spring-boot-sample-integration\src\main\java\flowable\Application.java | 2 |
请完成以下Java代码 | private List<ServiceNotReadyException> check(List<RunningService> runningServices) {
List<ServiceNotReadyException> exceptions = null;
for (RunningService service : runningServices) {
if (isDisabled(service)) {
continue;
}
logger.trace(LogMessage.format("Checking readiness of service '%s'", service));
try {
this.check.check(service);
logger.trace(LogMessage.format("Service '%s' is ready", service));
}
catch (ServiceNotReadyException ex) {
logger.trace(LogMessage.format("Service '%s' is not ready", service), ex);
exceptions = (exceptions != null) ? exceptions : new ArrayList<>();
exceptions.add(ex);
}
} | return (exceptions != null) ? exceptions : Collections.emptyList();
}
private boolean isDisabled(RunningService service) {
return service.labels().containsKey(DISABLE_LABEL);
}
private static void sleep(Duration duration) {
try {
Thread.sleep(duration.toMillis());
}
catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
} | repos\spring-boot-4.0.1\core\spring-boot-docker-compose\src\main\java\org\springframework\boot\docker\compose\lifecycle\ServiceReadinessChecks.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RemittanceAdviceId implements RepoIdAware
{
@JsonCreator
public static RemittanceAdviceId ofRepoId(final int repoId)
{
return new RemittanceAdviceId(repoId);
}
@Nullable
public static RemittanceAdviceId ofRepoIdOrNull(final int repoId)
{
return repoId > 0 ? new RemittanceAdviceId(repoId) : null;
}
public static int toRepoId(@Nullable final RemittanceAdviceId remittanceAdviceId)
{ | return remittanceAdviceId != null ? remittanceAdviceId.getRepoId() : -1;
}
int repoId;
private RemittanceAdviceId(final int repoId)
{
this.repoId = Check.assumeGreaterThanZero(repoId, "C_RemittanceAdvice_ID");
}
@Override
@JsonValue
public int getRepoId()
{
return repoId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\remittanceadvice\RemittanceAdviceId.java | 2 |
请完成以下Java代码 | public int getDefaultAsyncJobAcquireWaitTimeInMillis() {
return defaultAsyncJobAcquireWaitTimeInMillis;
}
public void setDefaultAsyncJobAcquireWaitTimeInMillis(int defaultAsyncJobAcquireWaitTimeInMillis) {
this.defaultAsyncJobAcquireWaitTimeInMillis = defaultAsyncJobAcquireWaitTimeInMillis;
}
public int getDefaultQueueSizeFullWaitTime() {
return defaultQueueSizeFullWaitTime;
}
public void setDefaultQueueSizeFullWaitTime(int defaultQueueSizeFullWaitTime) {
this.defaultQueueSizeFullWaitTime = defaultQueueSizeFullWaitTime;
}
public int getTimerLockTimeInMillis() {
return timerLockTimeInMillis;
}
public void setTimerLockTimeInMillis(int timerLockTimeInMillis) {
this.timerLockTimeInMillis = timerLockTimeInMillis;
}
public int getAsyncJobLockTimeInMillis() {
return asyncJobLockTimeInMillis;
}
public void setAsyncJobLockTimeInMillis(int asyncJobLockTimeInMillis) {
this.asyncJobLockTimeInMillis = asyncJobLockTimeInMillis;
}
public int getRetryWaitTimeInMillis() {
return retryWaitTimeInMillis;
}
public void setRetryWaitTimeInMillis(int retryWaitTimeInMillis) {
this.retryWaitTimeInMillis = retryWaitTimeInMillis; | }
public int getResetExpiredJobsInterval() {
return resetExpiredJobsInterval;
}
public void setResetExpiredJobsInterval(int resetExpiredJobsInterval) {
this.resetExpiredJobsInterval = resetExpiredJobsInterval;
}
public int getResetExpiredJobsPageSize() {
return resetExpiredJobsPageSize;
}
public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) {
this.resetExpiredJobsPageSize = resetExpiredJobsPageSize;
}
public int getNumberOfRetries() {
return numberOfRetries;
}
public void setNumberOfRetries(int numberOfRetries) {
this.numberOfRetries = numberOfRetries;
}
} | repos\Activiti-develop\activiti-core\activiti-spring-boot-starter\src\main\java\org\activiti\spring\boot\AsyncExecutorProperties.java | 1 |
请完成以下Java代码 | public final boolean isFullyAuthenticated() {
return !trustResolver.isAnonymous(authentication) && !trustResolver.isRememberMe(authentication);
}
public Object getPrincipal() {
return authentication.getPrincipal();
}
public void setTrustResolver(AuthenticationTrustResolver trustResolver) {
this.trustResolver = trustResolver;
}
public void setRoleHierarchy(RoleHierarchy roleHierarchy) {
this.roleHierarchy = roleHierarchy;
}
public void setDefaultRolePrefix(String defaultRolePrefix) {
this.defaultRolePrefix = defaultRolePrefix;
}
private Set<String> getAuthoritySet() {
if (roles == null) {
Collection<? extends GrantedAuthority> userAuthorities = authentication.getAuthorities();
if (roleHierarchy != null) {
userAuthorities = roleHierarchy.getReachableGrantedAuthorities(userAuthorities);
}
roles = AuthorityUtils.authorityListToSet(userAuthorities);
}
return roles;
}
@Override
public boolean hasPermission(Object target, Object permission) {
return permissionEvaluator.hasPermission(authentication, target, permission);
}
@Override
public boolean hasPermission(Object targetId, String targetType, Object permission) {
return permissionEvaluator.hasPermission(authentication, (Serializable) targetId, targetType, permission);
}
public void setPermissionEvaluator(PermissionEvaluator permissionEvaluator) {
this.permissionEvaluator = permissionEvaluator;
}
private static String getRoleWithDefaultPrefix(String defaultRolePrefix, String role) {
if (role == null) {
return role;
}
if ((defaultRolePrefix == null) || (defaultRolePrefix.length() == 0)) {
return role; | }
if (role.startsWith(defaultRolePrefix)) {
return role;
}
return defaultRolePrefix + role;
}
@Override
public Object getFilterObject() {
return this.filterObject;
}
@Override
public Object getReturnObject() {
return this.returnObject;
}
@Override
public Object getThis() {
return this;
}
@Override
public void setFilterObject(Object obj) {
this.filterObject = obj;
}
@Override
public void setReturnObject(Object obj) {
this.returnObject = obj;
}
} | repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\custom\security\MySecurityExpressionRoot.java | 1 |
请完成以下Java代码 | public void onBeforeDelete(final I_M_DeliveryDay_Alloc deliveryDayAlloc)
{
final I_M_DeliveryDay deliveryDay = deliveryDayAlloc.getM_DeliveryDay();
if (deliveryDay.isProcessed())
{
throw new AdempiereException("@CannotDelete@: @M_DeliveryDay_Alloc_ID@ (@M_DeliveryDay_ID@ @Processed@=@Y@)");
}
}
@ModelChange(timings = ModelValidator.TYPE_AFTER_DELETE)
public void onAfterDelete(final I_M_DeliveryDay_Alloc deliveryDayAlloc)
{
final I_M_DeliveryDay deliveryDay = deliveryDayAlloc.getM_DeliveryDay();
final I_M_DeliveryDay_Alloc deliveryDayAllocNew = null;
final I_M_DeliveryDay_Alloc deliveryDayAllocOld = deliveryDayAlloc;
updateDeliveryDayWhenAllocationChanged(deliveryDay, deliveryDayAllocNew, deliveryDayAllocOld);
}
private final void updateDeliveryDayWhenAllocationChanged(final I_M_DeliveryDay deliveryDay,
final I_M_DeliveryDay_Alloc deliveryDayAllocNew,
final I_M_DeliveryDay_Alloc deliveryDayAllocOld)
{
final boolean deliveryDayProcessed = deliveryDay.isProcessed();
//
// Call handlers to update the delivery day record
Services.get(IDeliveryDayBL.class) | .getDeliveryDayHandlers()
.updateDeliveryDayWhenAllocationChanged(deliveryDay, deliveryDayAllocNew, deliveryDayAllocOld);
//
// Prohibit changing delivery day if it was processed
if (deliveryDayProcessed)
{
if (InterfaceWrapperHelper.hasChanges(deliveryDay))
{
throw new AdempiereException("Cannot change a delivery day which was already processed"
+ "\n @M_DeliveryDay_ID@: " + deliveryDay
+ "\n @M_DeliveryDay_Alloc_ID@ @New@: " + deliveryDayAllocNew
+ "\n @M_DeliveryDay_Alloc_ID@ @Old@: " + deliveryDayAllocOld);
}
// return it because there is no need to save the changes
return;
}
//
// Save delivery day changes
InterfaceWrapperHelper.save(deliveryDay);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\model\validator\M_DeliveryDay_Alloc.java | 1 |
请完成以下Java代码 | public boolean deleteNode(String path) {
try {
//The version parameter specifies the version of the data to be updated. If the version is different from the real version, the update operation will fail. Specify version as -1 to ignore the version check.
zkClient.delete(path, -1);
return true;
} catch (Exception e) {
log.error("【delete persist node exception】{},{}", path, e);
return false;
}
}
/**
* Get the child nodes of the current node (excluding grandchild nodes)
*
* @param path
*/
public List<String> getChildren(String path) throws KeeperException, InterruptedException {
List<String> list = zkClient.getChildren(path, false);
return list;
} | /**
* Get the value of the specified node
*
* @param path
* @return
*/
public String getData(String path, Watcher watcher) {
try {
Stat stat = new Stat();
byte[] bytes = zkClient.getData(path, watcher, stat);
return new String(bytes);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
} | repos\springboot-demo-master\zookeeper\src\main\java\com\et\zookeeper\api\ZkApi.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public DefaultJmsListenerContainerFactory clusteringJmsListenerContainerFactory(
DefaultJmsListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
configurer.configure(factory, connectionFactory);
factory.setPubSubDomain(false);
return factory;
}
@Bean(CLUSTERING_JMS_TEMPLATE_BEAN_NAME)
public JmsMessagingTemplate clusteringJmsTemplate(ConnectionFactory connectionFactory) {
// 创建 JmsTemplate 对象
JmsTemplate template = new JmsTemplate(connectionFactory);
template.setPubSubDomain(false);
// 创建 JmsMessageTemplate
return new JmsMessagingTemplate(template);
}
// ========== 广播消费 ==========
@Bean(BROADCAST_JMS_LISTENER_CONTAINER_FACTORY_BEAN_NAME)
public DefaultJmsListenerContainerFactory broadcastJmsListenerContainerFactory(
DefaultJmsListenerContainerFactoryConfigurer configurer, ConnectionFactory connectionFactory) {
DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory(); | configurer.configure(factory, connectionFactory);
factory.setPubSubDomain(true);
return factory;
}
@Bean(BROADCAST_JMS_TEMPLATE_BEAN_NAME)
public JmsMessagingTemplate broadcastJmsTemplate(ConnectionFactory connectionFactory) {
// 创建 JmsTemplate 对象
JmsTemplate template = new JmsTemplate(connectionFactory);
template.setPubSubDomain(true);
// 创建 JmsMessageTemplate
return new JmsMessagingTemplate(template);
}
} | repos\SpringBoot-Labs-master\lab-32\lab-32-activemq-demo-message-model\src\main\java\cn\iocoder\springboot\lab32\activemqdemo\config\ActiveMQConfig.java | 2 |
请完成以下Java代码 | class ProcessFrame extends CFrame implements ProcessDialog, ProcessPanelWindow
{
private final ProcessPanel panel;
private final Integer windowNoCreatedHere;
ProcessFrame(final ProcessDialogBuilder builder)
{
super();
if (builder.getWindowNo() <= 0 || builder.getWindowNo() == Env.WINDOW_None)
{
windowNoCreatedHere = Env.createWindowNo(this);
builder.setWindowAndTabNo(windowNoCreatedHere);
}
else
{
windowNoCreatedHere = null;
}
panel = builder.buildPanel();
if (panel.isDisposed())
{
dispose();
return;
}
panel.installTo(this);
}
@Override
public void dispose()
{
final ProcessPanel panel = this.panel;
if (panel != null)
{
panel.dispose();
}
super.dispose();
if (windowNoCreatedHere != null)
{
Env.clearWinContext(windowNoCreatedHere);
}
}
@Override
public void setVisible(boolean visible) | {
super.setVisible(visible);
final ProcessPanel panel = this.panel;
if (panel != null)
{
panel.setVisible(visible);
}
}
@Override
public void enableWindowEvents(final long eventsToEnable)
{
enableEvents(eventsToEnable);
}
@Override
public Window asAWTWindow()
{
return this;
}
public boolean isDisposed()
{
final ProcessPanel panel = this.panel;
return panel == null || panel.isDisposed();
}
@Override
public void showCenterScreen()
{
validate();
pack();
AEnv.showCenterScreen(this);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessFrame.java | 1 |
请完成以下Java代码 | public class Server {
private static final List<User> AUTHENTICATED_USERS = List.of(
new User("1", "admin", "123456", true),
new User("2", "user", "123456", false)
);
private final Controller controller = new Controller();
private final ExecutorService executor = Executors.newFixedThreadPool(5);
public void serve(HttpServletRequest request, HttpServletResponse response) throws InterruptedException, ExecutionException {
Optional<User> user = authenticateUser(request);
if (user.isPresent()) {
Future<?> future = executor.submit(() ->
controller.processRequest(request, response, user.get()));
future.get();
} else {
response.setStatus(401); | }
}
private Optional<User> authenticateUser(HttpServletRequest request) {
return AUTHENTICATED_USERS.stream()
.filter(user -> checkUserPassword(user, request))
.findFirst();
}
private boolean checkUserPassword(User user, HttpServletRequest request) {
return user.name().equals(request.getParameter("user_name"))
&& user.password().equals(request.getParameter("user_pw"));
}
} | repos\tutorials-master\core-java-modules\core-java-20\src\main\java\com\baeldung\scopedvalues\classic\Server.java | 1 |
请完成以下Java代码 | public int doEndTag() throws JspException {
try {
if (!this.authorized && TagLibConfig.isUiSecurityDisabled()) {
this.pageContext.getOut().write(TagLibConfig.getSecuredUiSuffix());
}
}
catch (IOException ex) {
throw new JspException(ex);
}
return EVAL_PAGE;
}
public @Nullable String getId() {
return this.id;
}
public void setId(String id) {
this.id = id;
}
@Override
public @Nullable Tag getParent() {
return this.parent;
}
@Override
public void setParent(Tag parent) {
this.parent = parent;
}
public @Nullable String getVar() {
return this.var;
}
public void setVar(String var) {
this.var = var;
}
@Override
public void release() {
this.parent = null;
this.id = null;
}
@Override
public void setPageContext(PageContext pageContext) {
this.pageContext = pageContext;
}
@Override
protected ServletRequest getRequest() {
return this.pageContext.getRequest();
}
@Override
protected ServletResponse getResponse() {
return this.pageContext.getResponse();
}
@Override
protected ServletContext getServletContext() {
return this.pageContext.getServletContext();
}
private final class PageContextVariableLookupEvaluationContext implements EvaluationContext {
private EvaluationContext delegate;
private PageContextVariableLookupEvaluationContext(EvaluationContext delegate) {
this.delegate = delegate;
}
@Override
public TypedValue getRootObject() { | return this.delegate.getRootObject();
}
@Override
public List<ConstructorResolver> getConstructorResolvers() {
return this.delegate.getConstructorResolvers();
}
@Override
public List<MethodResolver> getMethodResolvers() {
return this.delegate.getMethodResolvers();
}
@Override
public List<PropertyAccessor> getPropertyAccessors() {
return this.delegate.getPropertyAccessors();
}
@Override
public TypeLocator getTypeLocator() {
return this.delegate.getTypeLocator();
}
@Override
public TypeConverter getTypeConverter() {
return this.delegate.getTypeConverter();
}
@Override
public TypeComparator getTypeComparator() {
return this.delegate.getTypeComparator();
}
@Override
public OperatorOverloader getOperatorOverloader() {
return this.delegate.getOperatorOverloader();
}
@Override
public @Nullable BeanResolver getBeanResolver() {
return this.delegate.getBeanResolver();
}
@Override
public void setVariable(String name, @Nullable Object value) {
this.delegate.setVariable(name, value);
}
@Override
public Object lookupVariable(String name) {
Object result = this.delegate.lookupVariable(name);
if (result == null) {
result = JspAuthorizeTag.this.pageContext.findAttribute(name);
}
return result;
}
}
} | repos\spring-security-main\taglibs\src\main\java\org\springframework\security\taglibs\authz\JspAuthorizeTag.java | 1 |
请完成以下Java代码 | public void addUser(User user) {
userMap.put(user.getId(), user);
}
@Override
public Collection<User> getUsers() {
return userMap.values();
}
@Override
public User getUser(String id) {
return userMap.get(id);
}
@Override
public User editUser(User forEdit) throws UserException {
try {
if (forEdit.getId() == null)
throw new UserException("ID cannot be blank");
User toEdit = userMap.get(forEdit.getId());
if (toEdit == null)
throw new UserException("User not found");
if (forEdit.getEmail() != null) {
toEdit.setEmail(forEdit.getEmail()); | }
if (forEdit.getFirstName() != null) {
toEdit.setFirstName(forEdit.getFirstName());
}
if (forEdit.getLastName() != null) {
toEdit.setLastName(forEdit.getLastName());
}
if (forEdit.getId() != null) {
toEdit.setId(forEdit.getId());
}
return toEdit;
} catch (Exception ex) {
throw new UserException(ex.getMessage());
}
}
@Override
public void deleteUser(String id) {
userMap.remove(id);
}
@Override
public boolean userExist(String id) {
return userMap.containsKey(id);
}
} | repos\tutorials-master\web-modules\spark-java\src\main\java\com\baeldung\sparkjava\UserServiceMapImpl.java | 1 |
请完成以下Java代码 | public int getImportedMunicipalityBP_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_ImportedMunicipalityBP_Group_ID);
}
@Override
public org.compiere.model.I_C_BP_Group getImportedPartientBP_Group()
{
return get_ValueAsPO(COLUMNNAME_ImportedPartientBP_Group_ID, org.compiere.model.I_C_BP_Group.class);
}
@Override
public void setImportedPartientBP_Group(final org.compiere.model.I_C_BP_Group ImportedPartientBP_Group)
{
set_ValueFromPO(COLUMNNAME_ImportedPartientBP_Group_ID, org.compiere.model.I_C_BP_Group.class, ImportedPartientBP_Group);
}
@Override
public void setImportedPartientBP_Group_ID (final int ImportedPartientBP_Group_ID)
{
if (ImportedPartientBP_Group_ID < 1)
set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, null);
else
set_Value (COLUMNNAME_ImportedPartientBP_Group_ID, ImportedPartientBP_Group_ID);
}
@Override
public int getImportedPartientBP_Group_ID()
{
return get_ValueAsInt(COLUMNNAME_ImportedPartientBP_Group_ID);
}
@Override
public void setStoreDirectory (final @Nullable java.lang.String StoreDirectory)
{
set_Value (COLUMNNAME_StoreDirectory, StoreDirectory);
} | @Override
public java.lang.String getStoreDirectory()
{
return get_ValueAsString(COLUMNNAME_StoreDirectory);
}
@Override
public void setVia_EAN (final java.lang.String Via_EAN)
{
set_Value (COLUMNNAME_Via_EAN, Via_EAN);
}
@Override
public java.lang.String getVia_EAN()
{
return get_ValueAsString(COLUMNNAME_Via_EAN);
}
} | repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java-gen\de\metas\vertical\healthcare\forum_datenaustausch_ch\commons\model\X_HC_Forum_Datenaustausch_Config.java | 1 |
请完成以下Java代码 | public Collection<ExitCriterion> getExitCriterions() {
return exitCriterionCollection.get(this);
}
public PlanningTable getPlanningTable() {
return planningTableChild.getChild(this);
}
public void setPlanningTable(PlanningTable planningTable) {
planningTableChild.setChild(this, planningTable);
}
public Collection<PlanItemDefinition> getPlanItemDefinitions() {
return planItemDefinitionCollection.get(this);
}
public static void registerType(ModelBuilder modelBuilder) {
ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(Stage.class, CMMN_ELEMENT_STAGE)
.namespaceUri(CMMN11_NS)
.extendsType(PlanFragment.class)
.instanceProvider(new ModelTypeInstanceProvider<Stage>() {
public Stage newInstance(ModelTypeInstanceContext instanceContext) {
return new StageImpl(instanceContext);
}
});
autoCompleteAttribute = typeBuilder.booleanAttribute(CMMN_ATTRIBUTE_AUTO_COMPLETE)
.defaultValue(false)
.build();
exitCriteriaRefCollection = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXIT_CRITERIA_REFS)
.namespace(CMMN10_NS)
.idAttributeReferenceCollection(Sentry.class, CmmnAttributeElementReferenceCollection.class) | .build();
SequenceBuilder sequenceBuilder = typeBuilder.sequence();
planningTableChild = sequenceBuilder.element(PlanningTable.class)
.build();
planItemDefinitionCollection = sequenceBuilder.elementCollection(PlanItemDefinition.class)
.build();
exitCriterionCollection = sequenceBuilder.elementCollection(ExitCriterion.class)
.build();
typeBuilder.build();
}
} | repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\StageImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getLinkType() {
return linkType;
}
@Override
public void setLinkType(String linkType) {
this.linkType = linkType;
}
@Override
public String getScopeId() {
return this.scopeId;
}
@Override
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
@Override
public String getSubScopeId() {
return subScopeId;
}
@Override
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
@Override
public String getScopeType() {
return this.scopeType;
}
@Override
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
@Override
public String getScopeDefinitionId() {
return this.scopeDefinitionId;
}
@Override
public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
@Override
public String getParentElementId() {
return parentElementId;
}
@Override
public void setParentElementId(String parentElementId) {
this.parentElementId = parentElementId;
}
@Override
public String getReferenceScopeId() {
return referenceScopeId;
}
@Override
public void setReferenceScopeId(String referenceScopeId) {
this.referenceScopeId = referenceScopeId;
}
@Override
public String getReferenceScopeType() {
return referenceScopeType;
}
@Override
public void setReferenceScopeType(String referenceScopeType) {
this.referenceScopeType = referenceScopeType;
}
@Override
public String getReferenceScopeDefinitionId() { | return referenceScopeDefinitionId;
}
@Override
public void setReferenceScopeDefinitionId(String referenceScopeDefinitionId) {
this.referenceScopeDefinitionId = referenceScopeDefinitionId;
}
@Override
public String getRootScopeId() {
return rootScopeId;
}
@Override
public void setRootScopeId(String rootScopeId) {
this.rootScopeId = rootScopeId;
}
@Override
public String getRootScopeType() {
return rootScopeType;
}
@Override
public void setRootScopeType(String rootScopeType) {
this.rootScopeType = rootScopeType;
}
@Override
public Date getCreateTime() {
return createTime;
}
@Override
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
@Override
public String getHierarchyType() {
return hierarchyType;
}
@Override
public void setHierarchyType(String hierarchyType) {
this.hierarchyType = hierarchyType;
}
} | repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\EntityLinkEntityImpl.java | 2 |
请完成以下Java代码 | public Integer getTransactionOrder() {
return transactionOrder;
}
@Override
public void setTransactionOrder(Integer transactionOrder) {
this.transactionOrder = transactionOrder;
}
@Override
public String getDeleteReason() {
return deleteReason;
}
@Override
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
@Override
public String getActivityId() {
return activityId;
}
@Override
public void setActivityId(String activityId) {
this.activityId = activityId;
}
@Override
public String getActivityName() {
return activityName;
}
@Override
public void setActivityName(String activityName) {
this.activityName = activityName;
}
@Override
public String getActivityType() {
return activityType;
}
@Override
public void setActivityType(String activityType) {
this.activityType = activityType;
}
@Override
public String getExecutionId() {
return executionId;
}
@Override
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
@Override
public String getAssignee() {
return assignee;
}
@Override
public void setAssignee(String assignee) {
this.assignee = assignee;
}
@Override
public String getCompletedBy() {
return completedBy;
}
@Override
public void setCompletedBy(String completedBy) {
this.completedBy = completedBy;
}
@Override | public String getTaskId() {
return taskId;
}
@Override
public void setTaskId(String taskId) {
this.taskId = taskId;
}
@Override
public String getCalledProcessInstanceId() {
return calledProcessInstanceId;
}
@Override
public void setCalledProcessInstanceId(String calledProcessInstanceId) {
this.calledProcessInstanceId = calledProcessInstanceId;
}
@Override
public String getTenantId() {
return tenantId;
}
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Date getTime() {
return getStartTime();
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("ActivityInstanceEntity[id=").append(id)
.append(", activityId=").append(activityId);
if (activityName != null) {
sb.append(", activityName=").append(activityName);
}
sb.append(", executionId=").append(executionId)
.append(", definitionId=").append(processDefinitionId);
if (StringUtils.isNotEmpty(tenantId)) {
sb.append(", tenantId=").append(tenantId);
}
sb.append("]");
return sb.toString();
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ActivityInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public Collection<AttributeKvEntry> getClientSideAttributes() {
return clientSideAttributesMap.values();
}
public Collection<AttributeKvEntry> getServerSideAttributes() {
return serverPrivateAttributesMap.values();
}
public Collection<AttributeKvEntry> getServerSidePublicAttributes() {
return serverPublicAttributesMap.values();
}
public Optional<AttributeKvEntry> getClientSideAttribute(String attribute) {
return Optional.ofNullable(clientSideAttributesMap.get(attribute));
}
public Optional<AttributeKvEntry> getServerPrivateAttribute(String attribute) {
return Optional.ofNullable(serverPrivateAttributesMap.get(attribute));
}
public Optional<AttributeKvEntry> getServerPublicAttribute(String attribute) {
return Optional.ofNullable(serverPublicAttributesMap.get(attribute));
}
public void remove(AttributeKey key) {
Map<String, AttributeKvEntry> map = getMapByScope(key.getScope());
if (map != null) {
map.remove(key.getAttributeKey());
}
}
public void update(String scope, List<AttributeKvEntry> values) {
Map<String, AttributeKvEntry> map = getMapByScope(scope);
values.forEach(v -> map.put(v.getKey(), v));
} | private Map<String, AttributeKvEntry> getMapByScope(String scope) {
Map<String, AttributeKvEntry> map = null;
if (scope.equalsIgnoreCase(DataConstants.CLIENT_SCOPE)) {
map = clientSideAttributesMap;
} else if (scope.equalsIgnoreCase(DataConstants.SHARED_SCOPE)) {
map = serverPublicAttributesMap;
} else if (scope.equalsIgnoreCase(DataConstants.SERVER_SCOPE)) {
map = serverPrivateAttributesMap;
}
return map;
}
@Override
public String toString() {
return "DeviceAttributes{" +
"clientSideAttributesMap=" + clientSideAttributesMap +
", serverPrivateAttributesMap=" + serverPrivateAttributesMap +
", serverPublicAttributesMap=" + serverPublicAttributesMap +
'}';
}
} | repos\thingsboard-master\common\message\src\main\java\org\thingsboard\server\common\msg\rule\engine\DeviceAttributes.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Step vtollStep1(StepBuilderFactory stepBuilderFactory,
@Qualifier("vtollReader") ItemReader<BudgetVtoll> reader,
@Qualifier("vtollWriter") ItemWriter<BudgetVtoll> writer,
@Qualifier("vtollProcessor") ItemProcessor<BudgetVtoll, BudgetVtoll> processor) {
return stepBuilderFactory
.get("vtollStep1")
.<BudgetVtoll, BudgetVtoll>chunk(5000)//批处理每次提交5000条数据
.reader(reader)//给step绑定reader
.processor(processor)//给step绑定processor
.writer(writer)//给step绑定writer
.faultTolerant()
.retry(Exception.class) // 重试
.noRetry(ParseException.class)
.retryLimit(1) //每条记录重试一次
.skip(Exception.class) | .skipLimit(200) //一共允许跳过200次异常
// .taskExecutor(new SimpleAsyncTaskExecutor()) //设置每个Job通过并发方式执行,一般来讲一个Job就让它串行完成的好
// .throttleLimit(10) //并发任务数为 10,默认为4
.build();
}
@Bean
public Validator<BudgetVtoll> csvBeanValidator() {
return new MyBeanValidator<>();
}
} | repos\SpringBootBucket-master\springboot-batch\src\main\java\com\xncoding\trans\modules\vtoll\BudgetVtollConfig.java | 2 |
请完成以下Java代码 | public String getId() {
return id;
}
public String getJobDefinitionId() {
return jobDefinitionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getFailedActivityId() {
return failedActivityId;
}
public int getRetries() {
return retries;
}
public Date getDueDate() {
return dueDate; | }
public String getProcessDefinitionId() {
return processDefinitionId;
}
public String getProcessDefinitionKey() {
return processDefinitionKey;
}
public boolean isSuspended() {
return suspended;
}
public long getPriority() {
return priority;
}
public String getTenantId() {
return tenantId;
}
public Date getCreateTime() {
return createTime;
}
public String getBatchId() {
return batchId;
}
} | repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\runtime\JobDto.java | 1 |
请完成以下Java代码 | public abstract class NeedsAppDefinitionCmd<T> implements Command<T>, Serializable {
private static final long serialVersionUID = 1L;
protected String appDefinitionId;
public NeedsAppDefinitionCmd(String appDefinitionId) {
this.appDefinitionId = appDefinitionId;
}
@Override
public T execute(CommandContext commandContext) {
if (appDefinitionId == null) {
throw new FlowableIllegalArgumentException("appDefinitionId is null");
} | AppDefinition appDefinition = CommandContextUtil.getAppRepositoryService().getAppDefinition(appDefinitionId);
if (appDefinition == null) {
throw new FlowableObjectNotFoundException("Cannot find app definition with id " + appDefinitionId, AppDefinition.class);
}
return execute(commandContext, appDefinition);
}
/**
* Subclasses must implement in this method their normal command logic.
*/
protected abstract T execute(CommandContext commandContext, AppDefinition appDefinition);
} | repos\flowable-engine-main\modules\flowable-app-engine\src\main\java\org\flowable\app\engine\impl\cmd\NeedsAppDefinitionCmd.java | 1 |
请完成以下Java代码 | public void setProperty(final String key, final int value)
{
setProperty(key, String.valueOf(value));
}
/**
* Get Property
*
* @param key Key
* @return Value
*/
public String getProperty(final String key)
{
if (key == null)
{
return "";
}
if (props == null)
{
return "";
}
final String value = props.getProperty(key, "");
if (Check.isEmpty(value))
{
return "";
}
return value;
} | /**
* Get Property as Boolean
*
* @param key Key
* @return Value
*/
public boolean isPropertyBool(final String key)
{
final String value = getProperty(key);
return DisplayType.toBooleanNonNull(value, false);
}
public void updateContext(final Properties ctx)
{
Env.setContext(ctx, "#ShowTrl", true);
Env.setContext(ctx, "#ShowAdvanced", true);
Env.setAutoCommit(ctx, isPropertyBool(P_AUTO_COMMIT));
Env.setAutoNew(ctx, isPropertyBool(P_AUTO_NEW));
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\UserPreference.java | 1 |
请完成以下Java代码 | public String store(ReceivedFile.FileGroup fileGroup, @NotNull MultipartFile file) {
try {
String fileIdentifier = getCleanedFileName(file.getOriginalFilename());
Path targetPath = getStoredFilePath(fileGroup, fileIdentifier);
file.transferTo(targetPath);
return fileIdentifier;
} catch (IOException e) {
throw new StorageException("Failed to store file " + file, e);
}
}
public Resource loadAsResource(ReceivedFile.FileGroup fileGroup, String fileIdentifier) {
try {
Path targetPath = getStoredFilePath(fileGroup, fileIdentifier);
Resource resource = new UrlResource(targetPath.toUri());
if (resource.exists() || resource.isReadable()) {
return resource;
} else {
throw new IOException("Could not read file: " + targetPath);
}
} catch (IOException e) {
throw new RetrievalException("Could not read file: " + fileIdentifier + " , group " + fileGroup, e);
}
}
private String getCleanedFileName(String originalName) throws IOException {
if (originalName == null || originalName.isEmpty()) {
throw new IOException("Failed to store empty file " + originalName); | }
if (originalName.contains("..")) {
// This is a security check
throw new IOException("Cannot store file with relative path outside current directory " + originalName);
}
return UUID.randomUUID().toString();
}
private String getSubFolder(ReceivedFile.FileGroup fileGroup) throws IOException {
if (fileGroup == ReceivedFile.FileGroup.NOTE_ATTACHMENT) {
return fileGroup.path;
}
throw new IOException("File group subfolder " + fileGroup + " is not implemented");
}
private Path getStoredFilePath(ReceivedFile.FileGroup fileGroup, String fileIdentifier) throws IOException {
return rootLocation.resolve(getSubFolder(fileGroup)).resolve(fileIdentifier);
}
} | repos\spring-boot-web-application-sample-master\main-app\main-webapp\src\main\java\gt\app\modules\file\FileService.java | 1 |
请完成以下Java代码 | public Object getParameterDefaultValue(@NonNull final IProcessDefaultParameter parameter)
{
if (PARAM_IsKeepProposalPrices.contentEquals(parameter.getColumnName()))
{
final I_C_Order proposal = orderBL.getById(OrderId.ofRepoId(getRecord_ID()));
if (docTypeBL.isSalesQuotation(DocTypeId.ofRepoId(proposal.getC_DocType_ID())))
{
return PARAM_DEFAULT_VALUE_YES;
}
}
return IProcessDefaultParametersProvider.DEFAULT_VALUE_NOTAVAILABLE;
}
@Override
protected String doIt()
{ | final I_C_Order newSalesOrder = CreateSalesOrderFromProposalCommand.builder()
.fromProposalId(OrderId.ofRepoId(getRecord_ID()))
.newOrderDocTypeId(newOrderDocTypeId)
.newOrderDateOrdered(newOrderDateOrdered)
.poReference(poReference)
.completeIt(completeIt)
.isKeepProposalPrices(keepProposalPrices)
.build()
.execute();
openOrder(newSalesOrder);
return newSalesOrder.getDocumentNo();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\order\process\C_Order_CreateFromProposal.java | 1 |
请完成以下Java代码 | public static ResponseEntity<StreamingResponseBody> extractResponseEntryFromURL(@NonNull final IDocumentAttachmentEntry entry)
{
final StreamingResponseBody responseBody = outputStream -> {
outputStream.write(new byte[] {});
};
final HttpHeaders headers = new HttpHeaders();
headers.setLocation(entry.getUrl()); // forward to attachment entry's URL
final ResponseEntity<StreamingResponseBody> response = new ResponseEntity<>(responseBody, headers, HttpStatus.FOUND);
return response;
}
@NonNull
public static ResponseEntity<StreamingResponseBody> extractResponseEntryFromLocalFileURL(@NonNull final IDocumentAttachmentEntry attachmentEntry)
{
final String contentType = attachmentEntry.getContentType();
final String filename = attachmentEntry.getFilename();
URL url = null;
StreamingResponseBody responseBody = null;
try
{
url = attachmentEntry.getUrl().toURL();
responseBody = streamFile(url);
}
catch (IOException e)
{
e.printStackTrace();
}
final HttpHeaders headers = new HttpHeaders(); | headers.setContentType(MediaType.parseMediaType(contentType));
headers.set(HttpHeaders.CONTENT_DISPOSITION, "inline; filename=\"" + filename + "\"");
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
return new ResponseEntity<>(responseBody, headers, HttpStatus.OK);
}
@NonNull
private StreamingResponseBody streamFile(@NonNull final URL url) throws IOException
{
final Path filePath = FileUtil.getFilePath(url);
final StreamingResponseBody responseBody = outputStream -> {
Files.copy(filePath, outputStream);
};
return responseBody;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attachments\DocumentAttachmentRestControllerHelper.java | 1 |
请完成以下Java代码 | public boolean fromXmlNode(final I_AD_MigrationStep step, final Element stepNode)
{
step.setSeqNo(Integer.parseInt(stepNode.getAttribute(NODE_SeqNo)));
step.setStepType(stepNode.getAttribute(NODE_StepType));
step.setStatusCode(X_AD_MigrationStep.STATUSCODE_Unapplied);
final Node commentNode = stepNode.getElementsByTagName(NODE_Comments).item(0);
if (commentNode != null)
{
step.setComments(MigrationHandler.getElementText(commentNode));
}
if (X_AD_MigrationStep.STEPTYPE_ApplicationDictionary.equals(step.getStepType()))
{
final NodeList children = stepNode.getElementsByTagName(NODE_PO);
for (int i = 0; i < children.getLength(); i++)
{
final Element poNode = (Element)children.item(i);
step.setAction(poNode.getAttribute(NODE_Action));
step.setTableName(poNode.getAttribute(NODE_Table));
step.setAD_Table_ID(Integer.parseInt(poNode.getAttribute(NODE_AD_Table_ID)));
step.setRecord_ID(Integer.parseInt(poNode.getAttribute(NODE_Record_ID)));
InterfaceWrapperHelper.save(step);
final NodeList data = poNode.getElementsByTagName(NODE_Data);
for (int j = 0; j < data.getLength(); j++)
{
final Properties ctx = InterfaceWrapperHelper.getCtx(step);
final String trxName = InterfaceWrapperHelper.getTrxName(step);
final I_AD_MigrationData stepData = InterfaceWrapperHelper.create(ctx, I_AD_MigrationData.class, trxName);
stepData.setAD_MigrationStep(step);
final Element dataElement = (Element)data.item(j);
Services.get(IXMLHandlerFactory.class)
.getHandler(I_AD_MigrationData.class)
.fromXmlNode(stepData, dataElement);
InterfaceWrapperHelper.save(stepData);
}
}
}
else if (X_AD_MigrationStep.STEPTYPE_SQLStatement.equals(step.getStepType())) | {
step.setDBType(stepNode.getAttribute(NODE_DBType));
final Node sqlNode = stepNode.getElementsByTagName(NODE_SQLStatement).item(0);
if (sqlNode != null)
{
step.setSQLStatement(MigrationHandler.getElementText(sqlNode));
}
final Node rollbackNode = stepNode.getElementsByTagName(NODE_RollbackStatement).item(0);
if (rollbackNode != null)
{
step.setRollbackStatement(MigrationHandler.getElementText(rollbackNode));
}
}
else
{
throw new AdempiereException("Unknown StepType: " + step.getStepType());
}
InterfaceWrapperHelper.save(step);
logger.info("Imported step: " + Services.get(IMigrationBL.class).getSummary(step));
return true;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\migration\xml\impl\MigrationStepHandler.java | 1 |
请完成以下Java代码 | public static Date parseLongDate(String aDate) {
OffsetDateTime offsetDateTime = OffsetDateTime.parse(aDate, longDateFormat);
return Date.from(offsetDateTime.toInstant());
}
public static String dateToString(Date date) {
String dateString = null;
if (date != null) {
dateString = longDateFormatOutputFormater.format(date);
}
return dateString;
}
public static Integer parseToInteger(String integer) {
Integer parsedInteger = null;
try {
parsedInteger = Integer.parseInt(integer);
} catch (Exception e) {
}
return parsedInteger;
}
public static Date parseToDate(String date) {
Date parsedDate = null;
try {
parsedDate = shortDateFormat.parse(date);
} catch (Exception e) {
} | return parsedDate;
}
public static List<String> parseToList(String value) {
if (value == null || value.isEmpty()) {
return null;
}
String[] valueParts = value.split(",");
List<String> values = new ArrayList<>(valueParts.length);
Collections.addAll(values, valueParts);
return values;
}
public static Set<String> parseToSet(String value) {
if (value == null || value.isEmpty()) {
return null;
}
String[] valueParts = value.split(",");
Set<String> values = new HashSet<>(valueParts.length);
Collections.addAll(values, valueParts);
return values;
}
} | repos\flowable-engine-main\modules\flowable-common-rest\src\main\java\org\flowable\common\rest\api\RequestUtil.java | 1 |
请完成以下Java代码 | 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 synchronized void addActionListener(final ActionListener l)
{
listenerList.add(ActionListener.class, l);
} // addActionListener
/**
* Fire Action Performed
*/
private void fireActionPerformed()
{
ActionEvent e = null;
ActionListener[] listeners = listenerList.getListeners(ActionListener.class);
for (int i = 0; i < listeners.length; i++)
{
if (e == null)
e = new ActionEvent(this, ActionEvent.ACTION_PERFORMED, "actionPerformed");
listeners[i].actionPerformed(e);
}
} // fireActionPerformed
private void actionEditConnection()
{
if (!isEnabled() || !m_rw)
{
return;
}
setCursor(Cursor.getPredefinedCursor(Cursor.WAIT_CURSOR));
try
{
final CConnection connection = getValue();
final CConnectionDialog dialog = new CConnectionDialog(connection);
if (dialog.isCancel())
{
return;
}
final CConnection connectionNew = dialog.getConnection();
setValue(connectionNew);
DB.setDBTarget(connectionNew);
fireActionPerformed();
}
finally
{
setCursor(Cursor.getDefaultCursor());
}
}
/**
* MouseListener | */
private class CConnectionEditor_MouseListener extends MouseAdapter
{
/** Mouse Clicked - Open connection editor */
@Override
public void mouseClicked(final MouseEvent e)
{
if (m_active)
return;
m_active = true;
try
{
actionEditConnection();
}
finally
{
m_active = false;
}
}
private boolean m_active = false;
}
} // CConnectionEditor | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\db\CConnectionEditor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | ObservationRegistry observationRegistry() {
return ObservationRegistry.create();
}
@Bean
WebClient webClient(ObservationRegistry observationRegistry) {
String host = "127.0.0.1";
int port = 8080;
if (applicationProperties.getClient() != null) {
port = applicationProperties.getClient().getPort();
host = applicationProperties.getClient().getHost();
}
if (port == 0) {
port = 8080;
}
if (host == null || host.isEmpty()) {
host = "127.0.0.1";
}
return WebClient.builder()
.baseUrl("http://" + host + ":" + port)
.observationRegistry(observationRegistry)
.build();
}
// Just an example for "HTTP Interfaces in Spring " - see https://docs.spring.io/spring-framework/reference/integration/rest-clients.html#rest-http-interface
@Bean
CalculationWebClient calculationWebClient(WebClient webClient) {
WebClientAdapter adapter = WebClientAdapter.create(webClient);
HttpServiceProxyFactory factory = HttpServiceProxyFactory.builderFor(adapter).build();
return factory.createClient(CalculationWebClient.class);
}
//--- Routing with WebFilter --- START ---
@Bean
public SimpleRoutingFilter simpleRoutingFilter() { | LOGGER.info("Bean 'simpleRoutingFilter' created");
return new SimpleRoutingFilter();
}
//--- Routing with WebFilter --- END ---
//--- Routing with RouterFunction --- START ---
@Bean
public RouterFunction<ServerResponse> routingSample1(ServiceController serviceController) {
LOGGER.info("Bean 'routingSample1' created");
return route()
.GET("sleep2", request -> callSleepBasedOnHeaderValue(serviceController, request.headers().header("mode")))
.build();
}
static Mono<ServerResponse> callSleepBasedOnHeaderValue(ServiceController serviceController, List<String> modeHeaderValue) {
final int value = extractSleepValue(modeHeaderValue);
LOGGER.info("ROUTING from /sleep2 to /sleep/{}", value);
return serviceController.sleep(value).flatMap(result -> ServerResponse.ok().body(result, Integer.class));
}
static int extractSleepValue(List<String> modeHeaderValue) {
return !modeHeaderValue.isEmpty() && modeHeaderValue.getFirst().equals("short") ? 1000 : 10000;
}
//--- Routing with RouterFunction --- END ---
} | repos\spring-boot3-demo-master\src\main\java\com\giraone\sb3\demo\config\WebClientConfig.java | 2 |
请完成以下Java代码 | void fixAllBlocks()
{
int begin = 0;
if (numBlocks() > NUM_EXTRA_BLOCKS)
{
begin = numBlocks() - NUM_EXTRA_BLOCKS;
}
int end = numBlocks();
for (int blockId = begin; blockId != end; ++blockId)
{
fixBlock(blockId);
}
}
void fixBlock(int blockId)
{
int begin = blockId * BLOCK_SIZE;
int end = begin + BLOCK_SIZE;
int unusedOffset = 0;
for (int offset = begin; offset != end; ++offset)
{
if (!extras(offset).isUsed)
{
unusedOffset = offset; | break;
}
}
for (int id = begin; id != end; ++id)
{
if (!extras(id).isFixed)
{
reserveId(id);
int[] units = _units.getBuffer();
// units[id].setLabel(id ^ unused_offset);
units[id] = (units[id] & ~0xFF)
| ((id ^ unusedOffset) & 0xFF);
}
}
}
private AutoIntPool _units = new AutoIntPool();
private DoubleArrayBuilderExtraUnit[] _extras;
private AutoBytePool _labels = new AutoBytePool();
private int[] _table;
private int _extrasHead;
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\DoubleArrayBuilder.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Result<DegradeRuleEntity> updateIfNotNull(Long id, String app, String limitApp, String resource,
Double count, Integer timeWindow, Integer grade) {
if (id == null) {
return Result.ofFail(-1, "id can't be null");
}
if (grade != null) {
if (grade < RuleConstant.DEGRADE_GRADE_RT || grade > RuleConstant.DEGRADE_GRADE_EXCEPTION_COUNT) {
return Result.ofFail(-1, "Invalid grade: " + grade);
}
}
DegradeRuleEntity entity = repository.findById(id);
if (entity == null) {
return Result.ofFail(-1, "id " + id + " dose not exist");
}
if (StringUtil.isNotBlank(app)) {
entity.setApp(app.trim());
}
if (StringUtil.isNotBlank(limitApp)) {
entity.setLimitApp(limitApp.trim());
}
if (StringUtil.isNotBlank(resource)) {
entity.setResource(resource.trim());
}
if (count != null) {
entity.setCount(count);
}
if (timeWindow != null) {
entity.setTimeWindow(timeWindow);
}
if (grade != null) {
entity.setGrade(grade);
}
Date date = new Date();
entity.setGmtModified(date);
try {
entity = repository.save(entity);
} catch (Throwable throwable) {
logger.error("save error:", throwable);
return Result.ofThrowable(-1, throwable);
}
if (!publishRules(entity.getApp(), entity.getIp(), entity.getPort())) {
logger.info("publish degrade rules fail after rule update");
}
return Result.ofSuccess(entity);
}
@ResponseBody
@RequestMapping("/delete.json")
@AuthAction(PrivilegeType.DELETE_RULE) | public Result<Long> delete(Long id) {
if (id == null) {
return Result.ofFail(-1, "id can't be null");
}
DegradeRuleEntity oldEntity = repository.findById(id);
if (oldEntity == null) {
return Result.ofSuccess(null);
}
try {
repository.delete(id);
} catch (Throwable throwable) {
logger.error("delete error:", throwable);
return Result.ofThrowable(-1, throwable);
}
if (!publishRules(oldEntity.getApp(), oldEntity.getIp(), oldEntity.getPort())) {
logger.info("publish degrade rules fail after rule delete");
}
return Result.ofSuccess(id);
}
private boolean publishRules(String app, String ip, Integer port) {
List<DegradeRuleEntity> rules = repository.findAllByMachine(MachineInfo.of(app, ip, port));
try {
rulePublisher.publish(app, rules);
} catch (Exception e) {
logger.error("推送降级规则失败 {}", e.getMessage(), e);
return false;
}
return true;
}
} | repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\DegradeController.java | 2 |
请完成以下Java代码 | public Criteria andSendTimeNotIn(List<Date> values) {
addCriterion("send_time not in", values, "sendTime");
return (Criteria) this;
}
public Criteria andSendTimeBetween(Date value1, Date value2) {
addCriterion("send_time between", value1, value2, "sendTime");
return (Criteria) this;
}
public Criteria andSendTimeNotBetween(Date value1, Date value2) {
addCriterion("send_time not between", value1, value2, "sendTime");
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\SmsFlashPromotionLogExample.java | 1 |
请完成以下Java代码 | public class ThreadPoolJobExecutor extends JobExecutor {
protected ThreadPoolExecutor threadPoolExecutor;
protected void startExecutingJobs() {
startJobAcquisitionThread();
}
protected void stopExecutingJobs() {
stopJobAcquisitionThread();
}
public void executeJobs(List<String> jobIds, ProcessEngineImpl processEngine) {
try {
threadPoolExecutor.execute(getExecuteJobsRunnable(jobIds, processEngine));
} catch (RejectedExecutionException e) {
logRejectedExecution(processEngine, jobIds.size());
rejectedJobsHandler.jobsRejected(jobIds, processEngine, this); | } finally {
int totalQueueCapacity = calculateTotalQueueCapacity(threadPoolExecutor.getQueue().size(),
threadPoolExecutor.getQueue().remainingCapacity());
logJobExecutionInfo(processEngine, threadPoolExecutor.getQueue().size(), totalQueueCapacity,
threadPoolExecutor.getMaximumPoolSize(), threadPoolExecutor.getPoolSize());
}
}
// getters / setters
public ThreadPoolExecutor getThreadPoolExecutor() {
return threadPoolExecutor;
}
public void setThreadPoolExecutor(ThreadPoolExecutor threadPoolExecutor) {
this.threadPoolExecutor = threadPoolExecutor;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\ThreadPoolJobExecutor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void redisLock(int i) {
RedisLock redisLock = new RedisLock(redisTemplate, "redisLock:" + i % 10, 5 * 60, 50000);
try {
long now = System.currentTimeMillis();
if (redisLock.lock()) {
logger.info("=" + (System.currentTimeMillis() - now));
// TODO 获取到锁要执行的代码块
logger.info("j:" + j++);
} else {
logger.info("k:" + k++);
}
} catch (Exception e) {
logger.info(e.getMessage(), e);
} finally {
redisLock.unlock();
}
}
public void redisLock2(int i) {
RedisLock2 redisLock2 = new RedisLock2(redisTemplate, "redisLock:" + i % 10, 5 * 60, 50000);
try {
long now = System.currentTimeMillis();
if (redisLock2.lock()) {
logger.info("=" + (System.currentTimeMillis() - now));
// TODO 获取到锁要执行的代码块
logger.info("j:" + j++);
} else {
logger.info("k:" + k++);
}
} catch (Exception e) {
logger.info(e.getMessage(), e);
} finally {
redisLock2.unlock();
}
}
public void redisLock3(int i) {
RedisLock3 redisLock3 = new RedisLock3(redisTemplate, "redisLock:" + i % 10, 5 * 60, 50000);
try {
long now = System.currentTimeMillis();
if (redisLock3.tryLock()) { | logger.info("=" + (System.currentTimeMillis() - now));
// TODO 获取到锁要执行的代码块
logger.info("j:" + j++);
} else {
logger.info("k:" + k++);
}
} catch (Exception e) {
logger.info(e.getMessage(), e);
} finally {
redisLock3.unlock();
}
}
public String set(final String key, final String value, final String nxxx, final String expx,
final long seconds) {
Assert.isTrue(!StringUtils.isEmpty(key), "key不能为空");
return redisTemplate.execute(new RedisCallback<String>() {
@Override
public String doInRedis(RedisConnection connection) throws DataAccessException {
String command = Command.SET.name();
byte[] keys = SafeEncoder.encode(key);
byte[] values = SafeEncoder.encode(value);
byte[] nxs = SafeEncoder.encode("NX");
byte[] exs = SafeEncoder.encode("EX");
byte[] secondsByte = SafeEncoder.encode(String.valueOf(seconds));
Object result = connection.execute(command, keys, values, nxs, exs, secondsByte);
if (result == null) {
return null;
}
return new String((byte[]) result);
}
});
}
} | repos\spring-boot-student-master\spring-boot-student-data-redis-distributed-lock\src\main\java\com\xiaolyuh\service\PersonService.java | 2 |
请完成以下Java代码 | protected String doIt() throws Exception
{
m_C_ProjectPhase_ID = getRecord_ID();
log.info("doIt - C_ProjectPhase_ID=" + m_C_ProjectPhase_ID);
if (m_C_ProjectPhase_ID == 0)
throw new IllegalArgumentException("C_ProjectPhase_ID == 0");
MProjectPhase fromPhase = new MProjectPhase (getCtx(), m_C_ProjectPhase_ID, get_TrxName());
MProject fromProject = ProjectGenOrder.getProject (getCtx(), fromPhase.getC_Project_ID(), get_TrxName());
MOrder order = new MOrder (fromProject, true, MOrder.DocSubType_OnCredit);
order.setDescription(order.getDescription() + " - " + fromPhase.getName());
if (!order.save())
throw new Exception("Could not create Order");
// Create an order on Phase Level
if (fromPhase.getM_Product_ID() != 0)
{
MOrderLine ol = new MOrderLine(order);
ol.setLine(fromPhase.getSeqNo());
StringBuffer sb = new StringBuffer (fromPhase.getName());
if (fromPhase.getDescription() != null && fromPhase.getDescription().length() > 0)
sb.append(" - ").append(fromPhase.getDescription());
ol.setDescription(sb.toString());
//
ol.setM_Product_ID(fromPhase.getM_Product_ID(), true);
ol.setQty(fromPhase.getQty());
ol.setPrice();
if (fromPhase.getPriceActual() != null && fromPhase.getPriceActual().compareTo(Env.ZERO) != 0)
ol.setPrice(fromPhase.getPriceActual());
orderLineBL.setTax(ol);
if (!ol.save())
log.error("doIt - Lines not generated");
return "@C_Order_ID@ " + order.getDocumentNo() + " (1)";
}
// Project Tasks
int count = 0;
List<I_C_ProjectTask> tasks = fromPhase.getTasks ();
for (int i = 0; i < tasks.size(); i++) | {
MOrderLine ol = new MOrderLine(order);
ol.setLine(tasks.get(i).getSeqNo());
StringBuffer sb = new StringBuffer (tasks.get(i).getName());
if (tasks.get(i).getDescription() != null && tasks.get(i).getDescription().length() > 0)
sb.append(" - ").append(tasks.get(i).getDescription());
ol.setDescription(sb.toString());
//
ol.setM_Product_ID(tasks.get(i).getM_Product_ID(), true);
ol.setQty(tasks.get(i).getQty());
ol.setPrice();
orderLineBL.setTax(ol);
if (ol.save())
count++;
} // for all lines
if (tasks.size() != count)
log.error("doIt - Lines difference - ProjectTasks=" + tasks.size() + " <> Saved=" + count);
return "@C_Order_ID@ " + order.getDocumentNo() + " (" + count + ")";
} // doIt
} // ProjectPhaseGenOrder | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\de\metas\project\process\legacy\ProjectPhaseGenOrder.java | 1 |
请完成以下Java代码 | protected List<CaseDefinition> getDeployedCaseDefinitionArtifacts(DeploymentEntity deployment) {
CommandContext commandContext = Context.getCommandContext();
// in case deployment was created by this command
List<CaseDefinition> entities = deployment.getDeployedCaseDefinitions();
if (entities == null) {
String deploymentId = deployment.getId();
CaseDefinitionManager caseDefinitionManager = commandContext.getCaseDefinitionManager();
return caseDefinitionManager.findCaseDefinitionByDeploymentId(deploymentId);
}
return entities;
}
protected void logProcessDefinitionRegistrations(StringBuilder builder, List<ProcessDefinition> processDefinitions) {
if(processDefinitions.isEmpty()) {
builder.append("Deployment does not provide any process definitions.");
} else {
builder.append("Will execute process definitions ");
builder.append("\n");
for (ProcessDefinition processDefinition : processDefinitions) {
builder.append("\n");
builder.append(" ");
builder.append(processDefinition.getKey());
builder.append("[version: ");
builder.append(processDefinition.getVersion());
builder.append(", id: ");
builder.append(processDefinition.getId());
builder.append("]");
}
builder.append("\n");
}
}
protected void logCaseDefinitionRegistrations(StringBuilder builder, List<CaseDefinition> caseDefinitions) {
if(caseDefinitions.isEmpty()) {
builder.append("Deployment does not provide any case definitions.");
} else {
builder.append("\n");
builder.append("Will execute case definitions ");
builder.append("\n");
for (CaseDefinition caseDefinition : caseDefinitions) { | builder.append("\n");
builder.append(" ");
builder.append(caseDefinition.getKey());
builder.append("[version: ");
builder.append(caseDefinition.getVersion());
builder.append(", id: ");
builder.append(caseDefinition.getId());
builder.append("]");
}
builder.append("\n");
}
}
public String getRegistrationSummary() {
StringBuilder builder = new StringBuilder();
for (Entry<String, DefaultProcessApplicationRegistration> entry : registrationsByDeploymentId.entrySet()) {
if(builder.length()>0) {
builder.append(", ");
}
builder.append(entry.getKey());
builder.append("->");
builder.append(entry.getValue().getReference().getName());
}
return builder.toString();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\application\ProcessApplicationManager.java | 1 |
请完成以下Java代码 | public void setMake(String make) {
this.make = make;
}
public String getModel() {
return model;
}
public void setModel(String model) {
this.model = model;
}
public int getYear() {
return year;
}
public void setYear(int year) {
this.year = year;
}
@Override | public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
Car car = (Car) o;
return year == car.year && Objects.equals(id, car.id) && Objects.equals(make, car.make) && Objects.equals(model, car.model);
}
@Override
public int hashCode() {
return Objects.hash(id, make, model, year);
}
} | repos\tutorials-master\persistence-modules\spring-data-cassandra-2\src\main\java\org\baeldung\springcassandra\model\Car.java | 1 |
请完成以下Java代码 | public List<Allergen> getByIds(@NonNull final Collection<AllergenId> ids)
{
return getAll().getByIds(ids);
}
private AllergenMap getAll()
{
return cache.getOrLoad(0, this::retrieveAll);
}
private AllergenMap retrieveAll()
{
final ImmutableList<Allergen> list = queryBL.createQueryBuilder(I_M_Allergen.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(AllergenRepository::fromRecord) | .collect(ImmutableList.toImmutableList());
return new AllergenMap(list);
}
private static Allergen fromRecord(final I_M_Allergen record)
{
final IModelTranslationMap trl = InterfaceWrapperHelper.getModelTranslationMap(record);
return Allergen.builder()
.id(AllergenId.ofRepoId(record.getM_Allergen_ID()))
.name(trl.getColumnTrl(I_M_Allergen.COLUMNNAME_Name, record.getName()))
.color(StringUtils.trimBlankToNull(record.getColor()))
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\allergen\AllergenRepository.java | 1 |
请完成以下Java代码 | public void setAD_Table_ID (int AD_Table_ID)
{
if (AD_Table_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Table_ID, Integer.valueOf(AD_Table_ID));
}
/** Get DB-Tabelle.
@return Database Table information
*/
public int getAD_Table_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Table_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Staled.
@param IsStaled Staled */
public void setIsStaled (boolean IsStaled)
{
set_Value (COLUMNNAME_IsStaled, Boolean.valueOf(IsStaled));
}
/** Get Staled.
@return Staled */
public boolean isStaled ()
{
Object oo = get_Value(COLUMNNAME_IsStaled);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Gueltig.
@param IsValid
Element ist gueltig
*/
public void setIsValid (boolean IsValid)
{
set_Value (COLUMNNAME_IsValid, Boolean.valueOf(IsValid));
}
/** Get Gueltig.
@return Element ist gueltig
*/
public boolean isValid ()
{
Object oo = get_Value(COLUMNNAME_IsValid);
if (oo != null)
{
if (oo instanceof Boolean) | return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Last Refresh Date.
@param LastRefreshDate Last Refresh Date */
public void setLastRefreshDate (Timestamp LastRefreshDate)
{
set_Value (COLUMNNAME_LastRefreshDate, LastRefreshDate);
}
/** Get Last Refresh Date.
@return Last Refresh Date */
public Timestamp getLastRefreshDate ()
{
return (Timestamp)get_Value(COLUMNNAME_LastRefreshDate);
}
/** Set Staled Since.
@param StaledSinceDate Staled Since */
public void setStaledSinceDate (Timestamp StaledSinceDate)
{
set_Value (COLUMNNAME_StaledSinceDate, StaledSinceDate);
}
/** Get Staled Since.
@return Staled Since */
public Timestamp getStaledSinceDate ()
{
return (Timestamp)get_Value(COLUMNNAME_StaledSinceDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\adempiere\model\X_AD_Table_MView.java | 1 |
请完成以下Java代码 | public void setEMail (final java.lang.String EMail)
{
set_Value (COLUMNNAME_EMail, EMail);
}
@Override
public java.lang.String getEMail()
{
return get_ValueAsString(COLUMNNAME_EMail);
}
@Override
public void setIsSmtpAuthorization (final boolean IsSmtpAuthorization)
{
set_Value (COLUMNNAME_IsSmtpAuthorization, IsSmtpAuthorization);
}
@Override
public boolean isSmtpAuthorization()
{
return get_ValueAsBoolean(COLUMNNAME_IsSmtpAuthorization);
}
@Override
public void setIsStartTLS (final boolean IsStartTLS)
{
set_Value (COLUMNNAME_IsStartTLS, IsStartTLS);
}
@Override
public boolean isStartTLS()
{
return get_ValueAsBoolean(COLUMNNAME_IsStartTLS);
}
@Override
public void setMSGRAPH_ClientId (final @Nullable java.lang.String MSGRAPH_ClientId)
{
set_Value (COLUMNNAME_MSGRAPH_ClientId, MSGRAPH_ClientId);
}
@Override
public java.lang.String getMSGRAPH_ClientId()
{
return get_ValueAsString(COLUMNNAME_MSGRAPH_ClientId);
}
@Override
public void setMSGRAPH_ClientSecret (final @Nullable java.lang.String MSGRAPH_ClientSecret)
{
set_Value (COLUMNNAME_MSGRAPH_ClientSecret, MSGRAPH_ClientSecret);
}
@Override
public java.lang.String getMSGRAPH_ClientSecret()
{
return get_ValueAsString(COLUMNNAME_MSGRAPH_ClientSecret);
}
@Override
public void setMSGRAPH_TenantId (final @Nullable java.lang.String MSGRAPH_TenantId)
{
set_Value (COLUMNNAME_MSGRAPH_TenantId, MSGRAPH_TenantId);
}
@Override
public java.lang.String getMSGRAPH_TenantId()
{
return get_ValueAsString(COLUMNNAME_MSGRAPH_TenantId);
}
@Override
public void setPassword (final @Nullable java.lang.String Password)
{
set_Value (COLUMNNAME_Password, Password);
}
@Override
public java.lang.String getPassword()
{
return get_ValueAsString(COLUMNNAME_Password);
}
@Override
public void setSMTPHost (final @Nullable java.lang.String SMTPHost)
{
set_Value (COLUMNNAME_SMTPHost, SMTPHost);
}
@Override
public java.lang.String getSMTPHost()
{
return get_ValueAsString(COLUMNNAME_SMTPHost);
}
@Override
public void setSMTPPort (final int SMTPPort)
{ | set_Value (COLUMNNAME_SMTPPort, SMTPPort);
}
@Override
public int getSMTPPort()
{
return get_ValueAsInt(COLUMNNAME_SMTPPort);
}
/**
* Type AD_Reference_ID=541904
* Reference name: AD_MailBox_Type
*/
public static final int TYPE_AD_Reference_ID=541904;
/** SMTP = smtp */
public static final String TYPE_SMTP = "smtp";
/** MSGraph = msgraph */
public static final String TYPE_MSGraph = "msgraph";
@Override
public void setType (final java.lang.String Type)
{
set_Value (COLUMNNAME_Type, Type);
}
@Override
public java.lang.String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setUserName (final @Nullable java.lang.String UserName)
{
set_Value (COLUMNNAME_UserName, UserName);
}
@Override
public java.lang.String getUserName()
{
return get_ValueAsString(COLUMNNAME_UserName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_MailBox.java | 1 |
请完成以下Java代码 | public String[] getWhereClauses(final List<Object> params)
{
return new String[0];
}
@Override
public String getText()
{
return null;
}
@Override
public void save(final Properties ctx, final int windowNo, final IInfoWindowGridRowBuilders builders)
{
for (final IHUPackingAware record : packingInfos.values())
{
// We need to create a key that depends on both the product and the PIIP.
// Note that we assume that both columns are read-only and therefore won't change!
// Keep in sync with the other controllers in this package!
// It's 1:17am, it has to be rolled out tomorrow and i *won't* make it any nicer tonight.
// Future generations will have to live with this shit or rewrite it.
final int recordId = new HashCodeBuilder()
.append(record.getM_Product_ID())
.append(record.getM_HU_PI_Item_Product_ID())
.toHashCode();
final OrderLineHUPackingGridRowBuilder builder = new OrderLineHUPackingGridRowBuilder();
builder.setSource(record);
builders.addGridTabRowBuilder(recordId, builder);
}
}
/**
* Gets existing {@link IHUPackingAware} record for given row (wrapped as IHUPackingAware) or null.
*
* @param rowIndexModel
* @return {@link IHUPackingAware} or null
*/
private IHUPackingAware getSavedHUPackingAware(final IHUPackingAware rowRecord)
{
final ArrayKey key = mkKey(rowRecord);
return packingInfos.get(key);
}
@Override
public void prepareEditor(final CEditor editor, final Object value, final int rowIndexModel, final int columnIndexModel)
{
// nothing
}
@Override | public String getProductCombinations()
{
final List<Integer> piItemProductIds = new ArrayList<Integer>();
for (final IHUPackingAware record : packingInfos.values())
{
piItemProductIds.add(record.getM_HU_PI_Item_Product_ID());
}
if (!piItemProductIds.isEmpty() && piItemProductIds != null)
{
final StringBuilder sb = new StringBuilder(piItemProductIds.get(0).toString());
for (int i = 1; i < piItemProductIds.size(); i++)
{
sb.append(", " + piItemProductIds.get(i).toString());
}
return " AND (" + M_HU_PI_Item_Product_table_alias + "." + I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_Product_ID + " IN " + " ( " + sb + " ) "
+ " OR " + M_HU_PI_Item_Product_table_alias + "." + I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_Product_ID + " IS NULL" + ") ";
}
return null;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\InfoProductQtyPacksController.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public boolean isActive() { | return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
} | repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\dynamicinsert\model\Account.java | 1 |
请完成以下Java代码 | public void setReferenceTargetElementType(ModelElementTypeImpl referenceTargetElementType) {
this.referenceTargetElementType = referenceTargetElementType;
}
public Collection<ModelElementInstance> findReferenceSourceElements(ModelElementInstance referenceTargetElement) {
if(referenceTargetElementType.isBaseTypeOf(referenceTargetElement.getElementType())) {
ModelElementType owningElementType = getReferenceSourceElementType();
return referenceTargetElement.getModelInstance().getModelElementsByType(owningElementType);
}
else {
return Collections.emptyList();
}
}
/**
* Update the reference identifier of the reference source model element instance
*
* @param referenceSourceElement the reference source model element instance
* @param oldIdentifier the old reference identifier
* @param newIdentifier the new reference identifier
*/
protected abstract void updateReference(ModelElementInstance referenceSourceElement, String oldIdentifier, String newIdentifier);
/**
* Update the reference identifier
*
* @param referenceTargetElement the reference target model element instance
* @param oldIdentifier the old reference identifier
* @param newIdentifier the new reference identifier
*/
public void referencedElementUpdated(ModelElementInstance referenceTargetElement, String oldIdentifier, String newIdentifier) {
for (ModelElementInstance referenceSourceElement : findReferenceSourceElements(referenceTargetElement)) {
updateReference(referenceSourceElement, oldIdentifier, newIdentifier);
}
}
/**
* Remove the reference in the reference source model element instance
*
* @param referenceSourceElement the reference source model element instance | */
protected abstract void removeReference(ModelElementInstance referenceSourceElement, ModelElementInstance referenceTargetElement);
/**
* Remove the reference if the target element is removed
*
* @param referenceTargetElement the reference target model element instance, which is removed
* @param referenceIdentifier the identifier of the reference to filter reference source elements
*/
public void referencedElementRemoved(ModelElementInstance referenceTargetElement, Object referenceIdentifier) {
for (ModelElementInstance referenceSourceElement : findReferenceSourceElements(referenceTargetElement)) {
if (referenceIdentifier.equals(getReferenceIdentifier(referenceSourceElement))) {
removeReference(referenceSourceElement, referenceTargetElement);
}
}
}
} | repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\reference\ReferenceImpl.java | 1 |
请完成以下Java代码 | public void setC_InvoiceLine(final org.compiere.model.I_C_InvoiceLine C_InvoiceLine)
{
set_ValueFromPO(COLUMNNAME_C_InvoiceLine_ID, org.compiere.model.I_C_InvoiceLine.class, C_InvoiceLine);
}
@Override
public void setC_InvoiceLine_ID (final int C_InvoiceLine_ID)
{
if (C_InvoiceLine_ID < 1)
set_Value (COLUMNNAME_C_InvoiceLine_ID, null);
else
set_Value (COLUMNNAME_C_InvoiceLine_ID, C_InvoiceLine_ID);
}
@Override
public int getC_InvoiceLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_InvoiceLine_ID);
}
@Override
public void setC_InvoiceLine_Tax_ID (final int C_InvoiceLine_Tax_ID)
{
if (C_InvoiceLine_Tax_ID < 1)
set_Value (COLUMNNAME_C_InvoiceLine_Tax_ID, null);
else
set_Value (COLUMNNAME_C_InvoiceLine_Tax_ID, C_InvoiceLine_Tax_ID);
}
@Override
public int getC_InvoiceLine_Tax_ID()
{
return get_ValueAsInt(COLUMNNAME_C_InvoiceLine_Tax_ID);
}
@Override
public org.compiere.model.I_C_Invoice_Verification_Set getC_Invoice_Verification_Set()
{
return get_ValueAsPO(COLUMNNAME_C_Invoice_Verification_Set_ID, org.compiere.model.I_C_Invoice_Verification_Set.class);
}
@Override
public void setC_Invoice_Verification_Set(final org.compiere.model.I_C_Invoice_Verification_Set C_Invoice_Verification_Set)
{
set_ValueFromPO(COLUMNNAME_C_Invoice_Verification_Set_ID, org.compiere.model.I_C_Invoice_Verification_Set.class, C_Invoice_Verification_Set);
}
@Override
public void setC_Invoice_Verification_Set_ID (final int C_Invoice_Verification_Set_ID)
{ | if (C_Invoice_Verification_Set_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_Set_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_Set_ID, C_Invoice_Verification_Set_ID);
}
@Override
public int getC_Invoice_Verification_Set_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Invoice_Verification_Set_ID);
}
@Override
public void setC_Invoice_Verification_SetLine_ID (final int C_Invoice_Verification_SetLine_ID)
{
if (C_Invoice_Verification_SetLine_ID < 1)
set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_SetLine_ID, null);
else
set_ValueNoCheck (COLUMNNAME_C_Invoice_Verification_SetLine_ID, C_Invoice_Verification_SetLine_ID);
}
@Override
public int getC_Invoice_Verification_SetLine_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Invoice_Verification_SetLine_ID);
}
@Override
public void setRelevantDate (final @Nullable java.sql.Timestamp RelevantDate)
{
set_ValueNoCheck (COLUMNNAME_RelevantDate, RelevantDate);
}
@Override
public java.sql.Timestamp getRelevantDate()
{
return get_ValueAsTimestamp(COLUMNNAME_RelevantDate);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Verification_SetLine.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final class EndpointAutoConfiguration {
@Bean
@ConditionalOnMissingBean
ParameterValueMapper endpointOperationParameterMapper(@EndpointConverter ObjectProvider<Converter<?, ?>> converters,
@EndpointConverter ObjectProvider<GenericConverter> genericConverters) {
ConversionService conversionService = createConversionService(converters.orderedStream().toList(),
genericConverters.orderedStream().toList());
return new ConversionServiceParameterValueMapper(conversionService);
}
private ConversionService createConversionService(List<Converter<?, ?>> converters,
List<GenericConverter> genericConverters) {
if (genericConverters.isEmpty() && converters.isEmpty()) {
return ApplicationConversionService.getSharedInstance();
}
ApplicationConversionService conversionService = new ApplicationConversionService();
converters.forEach(conversionService::addConverter); | genericConverters.forEach(conversionService::addConverter);
return conversionService;
}
@Bean
@ConditionalOnMissingBean
CachingOperationInvokerAdvisor endpointCachingOperationInvokerAdvisor(Environment environment) {
return new CachingOperationInvokerAdvisor(new EndpointIdTimeToLivePropertyFunction(environment));
}
@Bean
@ConditionalOnMissingBean(EndpointAccessResolver.class)
PropertiesEndpointAccessResolver propertiesEndpointAccessResolver(Environment environment) {
return new PropertiesEndpointAccessResolver(environment);
}
} | repos\spring-boot-4.0.1\module\spring-boot-actuator-autoconfigure\src\main\java\org\springframework\boot\actuate\autoconfigure\endpoint\EndpointAutoConfiguration.java | 2 |
请完成以下Java代码 | public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
@Override
public void setSeqNoGrid (final int SeqNoGrid)
{
set_Value (COLUMNNAME_SeqNoGrid, SeqNoGrid);
}
@Override
public int getSeqNoGrid()
{
return get_ValueAsInt(COLUMNNAME_SeqNoGrid);
}
@Override
public void setSortNo (final @Nullable BigDecimal SortNo)
{
set_Value (COLUMNNAME_SortNo, SortNo);
}
@Override
public BigDecimal getSortNo() | {
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_SortNo);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSpanX (final int SpanX)
{
set_Value (COLUMNNAME_SpanX, SpanX);
}
@Override
public int getSpanX()
{
return get_ValueAsInt(COLUMNNAME_SpanX);
}
@Override
public void setSpanY (final int SpanY)
{
set_Value (COLUMNNAME_SpanY, SpanY);
}
@Override
public int getSpanY()
{
return get_ValueAsInt(COLUMNNAME_SpanY);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Field.java | 1 |
请完成以下Java代码 | protected boolean beforeDelete()
{
final MInOut parent = getParent();
final DocStatus docStatus = DocStatus.ofCode(parent.getDocStatus());
if (docStatus.isDraftedOrInProgress())
{
return true;
}
throw new AdempiereException("@CannotDelete@");
} // beforeDelete
/**
* String Representation
*
* @return info
*/
@Override
public String toString()
{
StringBuffer sb = new StringBuffer("MInOutLine[").append(get_ID())
.append(",M_Product_ID=").append(getM_Product_ID())
.append(",QtyEntered=").append(getQtyEntered())
.append(",MovementQty=").append(getMovementQty())
.append(",M_AttributeSetInstance_ID=").append(getM_AttributeSetInstance_ID())
.append("]");
return sb.toString();
} // toString
/**
* Get Base value for Cost Distribution
*
* @param CostDistribution cost Distribution
* @return base number
*/
public BigDecimal getBase(String CostDistribution)
{
if (MLandedCost.LANDEDCOSTDISTRIBUTION_Costs.equals(CostDistribution))
{
MInvoiceLine m_il = MInvoiceLine.getOfInOutLine(this);
if (m_il == null)
{
log.error("No Invoice Line for: " + this.toString());
return BigDecimal.ZERO;
}
return m_il.getLineNetAmt();
}
else if (MLandedCost.LANDEDCOSTDISTRIBUTION_Line.equals(CostDistribution))
{
return BigDecimal.ONE;
}
else if (MLandedCost.LANDEDCOSTDISTRIBUTION_Quantity.equals(CostDistribution))
{
return getMovementQty();
}
else if (MLandedCost.LANDEDCOSTDISTRIBUTION_Volume.equals(CostDistribution))
{
MProduct product = getProduct();
if (product == null)
{
log.error("No Product");
return BigDecimal.ZERO;
} | return getMovementQty().multiply(product.getVolume());
}
else if (MLandedCost.LANDEDCOSTDISTRIBUTION_Weight.equals(CostDistribution))
{
MProduct product = getProduct();
if (product == null)
{
log.error("No Product");
return BigDecimal.ZERO;
}
return getMovementQty().multiply(product.getWeight());
}
//
log.error("Invalid Criteria: " + CostDistribution);
return BigDecimal.ZERO;
} // getBase
public boolean sameOrderLineUOM()
{
if (getC_OrderLine_ID() <= 0)
{
return false;
}
final I_C_OrderLine oLine = getC_OrderLine();
if (oLine.getC_UOM_ID() != getC_UOM_ID())
{
return false;
}
// inout has orderline and both has the same UOM
return true;
}
} // MInOutLine | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MInOutLine.java | 1 |
请完成以下Java代码 | private void loadDataFromSingleValue(
@NonNull final KPIDataResult.Builder data,
@NonNull final NumericMetricsAggregation.SingleValue aggregation)
{
for (final KPIField field : kpi.getFields())
{
final ElasticsearchDatasourceFieldDescriptor fieldDatasourceDescriptor = datasourceDescriptor.getFieldByName(field.getFieldName());
final Object value;
if ("value".equals(fieldDatasourceDescriptor.getEsPathAsString()))
{
value = aggregation.value();
}
else
{
throw new IllegalStateException("Only ES path ending with 'value' allowed for field: " + field);
}
data.putValue(
aggregation.getName(),
KPIDataSetValuesAggregationKey.NO_KEY,
field.getFieldName(),
KPIDataValue.ofValueAndField(value, field));
}
}
@NonNull
private static SearchSourceBuilder toSearchSourceBuilder(final String json) throws IOException
{
final SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
final SearchModule searchModule = new SearchModule(Settings.EMPTY, false, ImmutableList.of());
try (final XContentParser parser = XContentFactory.xContent(XContentType.JSON)
.createParser(
new NamedXContentRegistry(searchModule.getNamedXContents()),
LoggingDeprecationHandler.INSTANCE,
json))
{
searchSourceBuilder.parseXContent(parser); | }
return searchSourceBuilder;
}
private static Instant convertToInstant(final Object valueObj)
{
if (valueObj == null)
{
return Instant.ofEpochMilli(0);
}
else if (valueObj instanceof org.joda.time.DateTime)
{
final long millis = ((DateTime)valueObj).getMillis();
return Instant.ofEpochMilli(millis);
}
else if (valueObj instanceof Long)
{
return Instant.ofEpochMilli((Long)valueObj);
}
else if (valueObj instanceof Number)
{
return Instant.ofEpochMilli(((Number)valueObj).longValue());
}
else
{
throw new AdempiereException("Cannot convert " + valueObj + " to Instant.");
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\data\ElasticsearchKPIDataLoader.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ProfileApi {
private ProfileQueryService profileQueryService;
private UserRepository userRepository;
@GetMapping
public ResponseEntity getProfile(
@PathVariable("username") String username, @AuthenticationPrincipal User user) {
return profileQueryService
.findByUsername(username, user)
.map(this::profileResponse)
.orElseThrow(ResourceNotFoundException::new);
}
@PostMapping(path = "follow")
public ResponseEntity follow(
@PathVariable("username") String username, @AuthenticationPrincipal User user) {
return userRepository
.findByUsername(username)
.map(
target -> {
FollowRelation followRelation = new FollowRelation(user.getId(), target.getId());
userRepository.saveRelation(followRelation);
return profileResponse(profileQueryService.findByUsername(username, user).get());
})
.orElseThrow(ResourceNotFoundException::new);
}
@DeleteMapping(path = "follow")
public ResponseEntity unfollow(
@PathVariable("username") String username, @AuthenticationPrincipal User user) {
Optional<User> userOptional = userRepository.findByUsername(username); | if (userOptional.isPresent()) {
User target = userOptional.get();
return userRepository
.findRelation(user.getId(), target.getId())
.map(
relation -> {
userRepository.removeRelation(relation);
return profileResponse(profileQueryService.findByUsername(username, user).get());
})
.orElseThrow(ResourceNotFoundException::new);
} else {
throw new ResourceNotFoundException();
}
}
private ResponseEntity profileResponse(ProfileData profile) {
return ResponseEntity.ok(
new HashMap<String, Object>() {
{
put("profile", profile);
}
});
}
} | repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\api\ProfileApi.java | 2 |
请完成以下Java代码 | public void setDPD_StoreOrder_Log_ID (int DPD_StoreOrder_Log_ID)
{
if (DPD_StoreOrder_Log_ID < 1)
set_ValueNoCheck (COLUMNNAME_DPD_StoreOrder_Log_ID, null);
else
set_ValueNoCheck (COLUMNNAME_DPD_StoreOrder_Log_ID, Integer.valueOf(DPD_StoreOrder_Log_ID));
}
/** Get Dpd StoreOrder Log.
@return Dpd StoreOrder Log */
@Override
public int getDPD_StoreOrder_Log_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DPD_StoreOrder_Log_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Duration (ms).
@param DurationMillis Duration (ms) */
@Override
public void setDurationMillis (int DurationMillis)
{
set_Value (COLUMNNAME_DurationMillis, Integer.valueOf(DurationMillis));
}
/** Get Duration (ms).
@return Duration (ms) */
@Override
public int getDurationMillis ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_DurationMillis);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Fehler.
@param IsError
Ein Fehler ist bei der Durchführung aufgetreten
*/
@Override
public void setIsError (boolean IsError)
{
set_Value (COLUMNNAME_IsError, Boolean.valueOf(IsError));
}
/** Get Fehler.
@return Ein Fehler ist bei der Durchführung aufgetreten
*/
@Override | public boolean isError ()
{
Object oo = get_Value(COLUMNNAME_IsError);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
/** Set Request Message.
@param RequestMessage Request Message */
@Override
public void setRequestMessage (java.lang.String RequestMessage)
{
set_Value (COLUMNNAME_RequestMessage, RequestMessage);
}
/** Get Request Message.
@return Request Message */
@Override
public java.lang.String getRequestMessage ()
{
return (java.lang.String)get_Value(COLUMNNAME_RequestMessage);
}
/** Set Response Message.
@param ResponseMessage Response Message */
@Override
public void setResponseMessage (java.lang.String ResponseMessage)
{
set_Value (COLUMNNAME_ResponseMessage, ResponseMessage);
}
/** Get Response Message.
@return Response Message */
@Override
public java.lang.String getResponseMessage ()
{
return (java.lang.String)get_Value(COLUMNNAME_ResponseMessage);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-gen\de\metas\shipper\gateway\dpd\model\X_DPD_StoreOrder_Log.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class C_User_Assigned_Role
{
private static final AdMessageKey MSG_USER_ROLE_ALREADY_ASSIGNED = AdMessageKey.of("UserRoleAlreadyAssigned");
private final IQueryBL queryBL = Services.get(IQueryBL.class);
@ModelChange(timings = ModelValidator.TYPE_BEFORE_NEW, ifColumnsChanged = { I_C_User_Assigned_Role.COLUMNNAME_C_User_Role_ID, I_C_User_Assigned_Role.COLUMNNAME_AD_User_ID })
public void validateRoleUniqueForBPartner(@NonNull final I_C_User_Assigned_Role assignedRole)
{
final IQuery<I_AD_User> currentBpartnerQuery = queryBL.createQueryBuilder(I_AD_User.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_AD_User.COLUMNNAME_AD_User_ID, assignedRole.getAD_User_ID())
.create();
final IQuery<I_C_User_Assigned_Role> uniqueForBpartnerQuery = queryBL.createQueryBuilder(I_C_User_Role.class)
.addOnlyActiveRecordsFilter()
.addEqualsFilter(I_C_User_Role.COLUMNNAME_C_User_Role_ID, assignedRole.getC_User_Role_ID())
.addEqualsFilter(I_C_User_Role.COLUMNNAME_IsUniqueForBPartner, true)
.andCollectChildren(I_C_User_Assigned_Role.COLUMN_C_User_Role_ID) | .addOnlyActiveRecordsFilter().create();
final boolean anyMatch = queryBL.createQueryBuilder(I_AD_User.class)
.addOnlyActiveRecordsFilter()
.addInSubQueryFilter(I_AD_User.COLUMNNAME_AD_User_ID, I_C_User_Assigned_Role.COLUMNNAME_AD_User_ID, uniqueForBpartnerQuery)
.addInSubQueryFilter(I_AD_User.COLUMNNAME_C_BPartner_ID, I_AD_User.COLUMNNAME_C_BPartner_ID, currentBpartnerQuery)
.create()
.anyMatch();
if (anyMatch)
{
throw new AdempiereException(MSG_USER_ROLE_ALREADY_ASSIGNED).markAsUserValidationError();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\user\role\interceptor\C_User_Assigned_Role.java | 2 |
请完成以下Java代码 | public void setEvent_UUID (final java.lang.String Event_UUID)
{
set_ValueNoCheck (COLUMNNAME_Event_UUID, Event_UUID);
}
@Override
public java.lang.String getEvent_UUID()
{
return get_ValueAsString(COLUMNNAME_Event_UUID);
}
@Override
public void setIsError (final boolean IsError)
{
set_Value (COLUMNNAME_IsError, IsError);
}
@Override
public boolean isError()
{
return get_ValueAsBoolean(COLUMNNAME_IsError);
}
@Override
public void setIsErrorAcknowledged (final boolean IsErrorAcknowledged)
{
set_Value (COLUMNNAME_IsErrorAcknowledged, IsErrorAcknowledged);
}
@Override | public boolean isErrorAcknowledged()
{
return get_ValueAsBoolean(COLUMNNAME_IsErrorAcknowledged);
}
@Override
public void setRecord_ID (final int Record_ID)
{
if (Record_ID < 0)
set_Value (COLUMNNAME_Record_ID, null);
else
set_Value (COLUMNNAME_Record_ID, Record_ID);
}
@Override
public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\event\model\X_AD_EventLog.java | 1 |
请完成以下Java代码 | public <T extends ServerResponse, R extends ServerResponse> RouterFunctions.Builder after(
BiFunction<ServerRequest, T, R> responseProcessor) {
builder.after(responseProcessor);
return this;
}
@Override
public <T extends ServerResponse> RouterFunctions.Builder onError(Predicate<Throwable> predicate,
BiFunction<Throwable, ServerRequest, T> responseProvider) {
builder.onError(predicate, responseProvider);
return this;
}
@Override
public <T extends ServerResponse> RouterFunctions.Builder onError(Class<? extends Throwable> exceptionType,
BiFunction<Throwable, ServerRequest, T> responseProvider) {
builder.onError(exceptionType, responseProvider); | return this;
}
@Override
public RouterFunctions.Builder withAttribute(String name, Object value) {
builder.withAttribute(name, value);
return this;
}
@Override
public RouterFunctions.Builder withAttributes(Consumer<Map<String, Object>> attributesConsumer) {
builder.withAttributes(attributesConsumer);
return this;
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayRouterFunctionsBuilder.java | 1 |
请完成以下Java代码 | class AuthenticationExtensionsClientOutputsDeserializer extends StdDeserializer<AuthenticationExtensionsClientOutputs> {
private static final Log logger = LogFactory.getLog(AuthenticationExtensionsClientOutputsDeserializer.class);
/**
* Creates a new instance.
*/
AuthenticationExtensionsClientOutputsDeserializer() {
super(AuthenticationExtensionsClientOutputs.class);
}
@Override
public AuthenticationExtensionsClientOutputs deserialize(JsonParser parser, DeserializationContext ctxt)
throws JacksonException {
List<AuthenticationExtensionsClientOutput<?>> outputs = new ArrayList<>();
for (String key = parser.nextName(); key != null; key = parser.nextName()) {
JsonToken startObject = parser.nextValue();
if (startObject != JsonToken.START_OBJECT) {
break; | }
if (CredentialPropertiesOutput.EXTENSION_ID.equals(key)) {
CredentialPropertiesOutput output = parser.readValueAs(CredentialPropertiesOutput.class);
outputs.add(output);
}
else {
if (logger.isDebugEnabled()) {
logger.debug("Skipping unknown extension with id " + key);
}
parser.nextValue();
}
}
return new ImmutableAuthenticationExtensionsClientOutputs(outputs);
}
} | repos\spring-security-main\webauthn\src\main\java\org\springframework\security\web\webauthn\jackson\AuthenticationExtensionsClientOutputsDeserializer.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setTotalPrice(String totalPrice) {
this.totalPrice = totalPrice;
}
public ReceiptEntity getReceiptEntity() {
return receiptEntity;
}
public void setReceiptEntity(ReceiptEntity receiptEntity) {
this.receiptEntity = receiptEntity;
}
public LocationEntity getLocationEntity() {
return locationEntity;
}
public void setLocationEntity(LocationEntity locationEntity) {
this.locationEntity = locationEntity;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
public String getExpressNo() {
return expressNo;
}
public void setExpressNo(String expressNo) {
this.expressNo = expressNo; | }
public UserEntity getBuyer() {
return buyer;
}
public void setBuyer(UserEntity buyer) {
this.buyer = buyer;
}
@Override
public String toString() {
return "OrdersEntity{" +
"id='" + id + '\'' +
", buyer=" + buyer +
", company=" + company +
", productOrderList=" + productOrderList +
", orderStateEnum=" + orderStateEnum +
", orderStateTimeList=" + orderStateTimeList +
", payModeEnum=" + payModeEnum +
", totalPrice='" + totalPrice + '\'' +
", receiptEntity=" + receiptEntity +
", locationEntity=" + locationEntity +
", remark='" + remark + '\'' +
", expressNo='" + expressNo + '\'' +
'}';
}
} | repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\entity\order\OrdersEntity.java | 2 |
请完成以下Java代码 | public Criteria andPriceBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("price between", value1, value2, "price");
return (Criteria) this;
}
public Criteria andPriceNotBetween(BigDecimal value1, BigDecimal value2) {
addCriterion("price not between", value1, value2, "price");
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\PmsProductLadderExample.java | 1 |
请完成以下Java代码 | public class StaxParser {
public static List<WebSite> parse(String path) {
List<WebSite> websites = new ArrayList<WebSite>();
WebSite website = null;
XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
try {
XMLEventReader reader = xmlInputFactory.createXMLEventReader(new FileInputStream(path));
while (reader.hasNext()) {
XMLEvent nextEvent = reader.nextEvent();
if (nextEvent.isStartElement()) {
StartElement startElement = nextEvent.asStartElement();
switch (startElement.getName()
.getLocalPart()) {
case "website":
website = new WebSite();
Attribute url = startElement.getAttributeByName(new QName("url"));
if (url != null) {
website.setUrl(url.getValue());
}
break;
case "name":
nextEvent = reader.nextEvent();
website.setName(nextEvent.asCharacters()
.getData());
break;
case "category":
nextEvent = reader.nextEvent();
website.setCategory(nextEvent.asCharacters()
.getData());
break;
case "status":
nextEvent = reader.nextEvent();
website.setStatus(nextEvent.asCharacters()
.getData());
break;
} | }
if (nextEvent.isEndElement()) {
EndElement endElement = nextEvent.asEndElement();
if (endElement.getName()
.getLocalPart()
.equals("website")) {
websites.add(website);
}
}
}
} catch (XMLStreamException xse) {
System.out.println("XMLStreamException");
xse.printStackTrace();
} catch (FileNotFoundException fnfe) {
System.out.println("FileNotFoundException");
fnfe.printStackTrace();
}
return websites;
}
} | repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\stax\StaxParser.java | 1 |
请完成以下Java代码 | public Class<? extends MilestoneInstanceEntity> getManagedEntityClass() {
return MilestoneInstanceEntityImpl.class;
}
@Override
public MilestoneInstanceEntity create() {
return new MilestoneInstanceEntityImpl();
}
@SuppressWarnings("unchecked")
@Override
public List<MilestoneInstance> findMilestoneInstancesByQueryCriteria(MilestoneInstanceQueryImpl query) {
return getDbSqlSession().selectList("selectMilestoneInstancesByQueryCriteria", query, getManagedEntityClass());
}
@Override
public long findMilestoneInstancesCountByQueryCriteria(MilestoneInstanceQueryImpl query) {
return (Long) getDbSqlSession().selectOne("selectMilestoneInstanceCountByQueryCriteria", query);
}
@Override
public void deleteByCaseDefinitionId(String caseDefinitionId) {
getDbSqlSession().delete("deleteMilestoneInstanceByCaseDefinitionId", caseDefinitionId, getManagedEntityClass()); | }
@Override
public void deleteByCaseInstanceId(String caseInstanceId) {
bulkDelete("deleteMilestoneInstanceByCaseInstanceId", milestoneInstanceByCaseInstanceIdCachedEntityMatcher, caseInstanceId);
}
public static class MilestoneInstanceByCaseInstanceIdCachedEntityMatcher extends CachedEntityMatcherAdapter<MilestoneInstanceEntity> {
@Override
public boolean isRetained(MilestoneInstanceEntity entity, Object param) {
String caseInstanceId = (String) param;
return caseInstanceId.equals(entity.getCaseInstanceId());
}
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\data\impl\MybatisMilestoneInstanceDataManager.java | 1 |
请完成以下Java代码 | public class AddingNewLineToString {
public static void main(String[] args) {
String line1 = "Humpty Dumpty sat on a wall.";
String line2 = "Humpty Dumpty had a great fall.";
String rhyme = "";
System.out.println("***New Line in a String in Java***");
//1. Using "\n"
System.out.println("1. Using \\n");
rhyme = line1 + "\n" + line2;
System.out.println(rhyme);
//2. Using "\r\n"
System.out.println("2. Using \\r\\n");
rhyme = line1 + "\r\n" + line2;
System.out.println(rhyme);
//3. Using "\r"
System.out.println("3. Using \\r");
rhyme = line1 + "\r" + line2;
System.out.println(rhyme);
//4. Using "\n\r" Note that this is not same as "\r\n"
// Using "\n\r" is equivalent to adding two lines
System.out.println("4. Using \\n\\r");
rhyme = line1 + "\n\r" + line2;
System.out.println(rhyme);
//5. Using System.lineSeparator()
System.out.println("5. Using System.lineSeparator()");
rhyme = line1 + System.lineSeparator() + line2;
System.out.println(rhyme);
//6. Using System.getProperty("line.separator")
System.out.println("6. Using System.getProperty(\"line.separator\")");
rhyme = line1 + System.getProperty("line.separator") + line2;
System.out.println(rhyme);
//7. Using %n
System.out.println("7. Using %n");
rhyme = "Humpty Dumpty sat on a wall.%nHumpty Dumpty had a great fall.";
System.out.println(rhyme);
System.out.println("***HTML to rendered in a browser***");
//1. Line break for HTML using <br>
System.out.println("1. Line break for HTML using <br>");
rhyme = line1 + "<br>" + line2;
System.out.println(rhyme); | //2. Line break for HTML using “ ”
System.out.println("2. Line break for HTML using ");
rhyme = line1 + " " + line2;
System.out.println(rhyme);
//3. Line break for HTML using “ ”
System.out.println("3. Line break for HTML using ");
rhyme = line1 + " " + line2;
System.out.println(rhyme);
//4. Line break for HTML using “
 ;”
System.out.println("4. Line break for HTML using ");
rhyme = line1 + " " + line2;
System.out.println(rhyme);
//5. Line break for HTML using \n”
System.out.println("5. Line break for HTML using \\n");
rhyme = line1 + "\n" + line2;
System.out.println(rhyme);
}
} | repos\tutorials-master\core-java-modules\core-java-string-operations\src\main\java\com\baeldung\newline\AddingNewLineToString.java | 1 |
请完成以下Java代码 | public WFProcess startWorkflow(final WorkflowStartRequest request)
{
final UserId invokerId = request.getInvokerId();
final InventoryId inventoryId = InventoryWFProcessStartParams.ofParams(request.getWfParameters()).getInventoryId();
final Inventory inventory = jobService.startJob(inventoryId, invokerId);
return toWFProcess(inventory);
}
@Override
public WFProcess continueWorkflow(final WFProcessId wfProcessId, final UserId callerId)
{
final InventoryId inventoryId = toInventoryId(wfProcessId);
final Inventory inventory = jobService.reassignJob(inventoryId, callerId);
return toWFProcess(inventory);
}
@Override
public void abort(final WFProcessId wfProcessId, final UserId callerId)
{
jobService.abort(wfProcessId, callerId);
}
@Override
public void abortAll(final UserId callerId)
{
jobService.abortAll(callerId);
}
@Override
public void logout(final @NonNull UserId userId)
{
abortAll(userId);
}
@Override
public WFProcess getWFProcessById(final WFProcessId wfProcessId)
{
final Inventory inventory = jobService.getById(toInventoryId(wfProcessId));
return toWFProcess(inventory);
}
@Override
public WFProcessHeaderProperties getHeaderProperties(final @NonNull WFProcess wfProcess)
{
final WarehousesLoadingCache warehouses = warehouseService.newLoadingCache(); | final Inventory inventory = getInventory(wfProcess);
return WFProcessHeaderProperties.builder()
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("DocumentNo"))
.value(inventory.getDocumentNo())
.build())
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("MovementDate"))
.value(TranslatableStrings.date(inventory.getMovementDate().toLocalDate()))
.build())
.entry(WFProcessHeaderProperty.builder()
.caption(TranslatableStrings.adElementOrMessage("M_Warehouse_ID"))
.value(inventory.getWarehouseId() != null
? warehouses.getById(inventory.getWarehouseId()).getWarehouseName()
: "")
.build())
.build();
}
@NonNull
public static Inventory getInventory(final @NonNull WFProcess wfProcess)
{
return wfProcess.getDocumentAs(Inventory.class);
}
public static WFProcess mapJob(@NonNull final WFProcess wfProcess, @NonNull final UnaryOperator<Inventory> mapper)
{
final Inventory inventory = getInventory(wfProcess);
final Inventory inventoryChanged = mapper.apply(inventory);
return !Objects.equals(inventory, inventoryChanged) ? toWFProcess(inventoryChanged) : wfProcess;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\InventoryMobileApplication.java | 1 |
请完成以下Java代码 | public Collection<Class<? extends AbstractStockEstimateEvent>> getHandledEventType()
{
return ImmutableList.of(StockEstimateCreatedEvent.class, StockEstimateDeletedEvent.class);
}
@Override
public void handleEvent(@NonNull final AbstractStockEstimateEvent event)
{
final UpdateMainDataRequest dataUpdateRequest = createDataUpdateRequestForEvent(event);
dataUpdateRequestHandler.handleDataUpdateRequest(dataUpdateRequest);
}
private UpdateMainDataRequest createDataUpdateRequestForEvent(
@NonNull final AbstractStockEstimateEvent stockEstimateEvent)
{
final OrgId orgId = stockEstimateEvent.getOrgId();
final ZoneId timeZone = orgDAO.getTimeZone(orgId);
final MainDataRecordIdentifier identifier = MainDataRecordIdentifier.builder()
.productDescriptor(stockEstimateEvent.getMaterialDescriptor())
.date(TimeUtil.getDay(stockEstimateEvent.getDate(), timeZone))
.warehouseId(stockEstimateEvent.getMaterialDescriptor().getWarehouseId()) | .build();
final BigDecimal qtyStockEstimate = stockEstimateEvent instanceof StockEstimateDeletedEvent
? BigDecimal.ZERO
: stockEstimateEvent.getQuantityDelta();
final Integer qtyStockSeqNo = stockEstimateEvent instanceof StockEstimateDeletedEvent
? 0
: stockEstimateEvent.getQtyStockEstimateSeqNo();
return UpdateMainDataRequest.builder()
.identifier(identifier)
.qtyStockEstimateSeqNo(qtyStockSeqNo)
.qtyStockEstimateCount(qtyStockEstimate)
.qtyStockEstimateTime(stockEstimateEvent.getDate())
.build();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.material\cockpit\src\main\java\de\metas\material\cockpit\view\eventhandler\AbstractStockEstimateHandler.java | 1 |
请完成以下Java代码 | public ProcessInstanceWithVariables execute(CommandContext commandContext) {
ProcessDefinitionEntity processDefinition = new GetDeployedProcessDefinitionCmd(instantiationBuilder, false).execute(commandContext);
for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) {
checker.checkCreateProcessInstance(processDefinition);
}
// Start the process instance
ExecutionEntity processInstance = processDefinition.createProcessInstance(instantiationBuilder.getBusinessKey(),
instantiationBuilder.getCaseInstanceId());
if (instantiationBuilder.getTenantId() != null) {
processInstance.setTenantId(instantiationBuilder.getTenantId());
} | final ExecutionVariableSnapshotObserver variablesListener = new ExecutionVariableSnapshotObserver(processInstance);
processInstance.start(instantiationBuilder.getVariables());
commandContext.getOperationLogManager().logProcessInstanceOperation(
UserOperationLogEntry.OPERATION_TYPE_CREATE,
processInstance.getId(),
processInstance.getProcessDefinitionId(),
processInstance.getProcessDefinition().getKey(),
Collections.singletonList(PropertyChange.EMPTY_CHANGE));
return new ProcessInstanceWithVariablesImpl(processInstance, variablesListener.getVariables());
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\StartProcessInstanceCmd.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Mono<UserData> create(CreateUserData createUserData) {
UserData userData = new UserData(UUID.randomUUID().toString(), createUserData.getEmail(), createUserData.getName());
data.put(userData.getId(), userData);
return Mono.just(userData);
}
@Override
public Mono<UserData> getEmployee(String id) {
UserData userData = data.get(id);
if (userData != null) {
return Mono.just(userData);
} else {
return Mono.empty();
}
}
@Override
public Flux<UserData> getAll() {
return Flux.fromIterable(data.values());
}
@Override
public Mono<UserData> update(UserData employee) {
data.put(employee.getId(), employee);
return Mono.just(employee);
}
@Override
public Mono<UserData> delete(String id) {
UserData userData = data.remove(id); | if (userData != null) {
return Mono.just(userData);
} else {
return Mono.empty();
}
}
@Override
public void createUsersBulk(Integer n) {
LOG.info("createUsersBulk n={} ...", n);
for (int i=0; i<n; i++) {
String id = "user-id-" + i;
data.put(id, new UserData(id, "email" + i + "@corp.com", "name-" + i));
}
LOG.info("created {} users", n);
}
@Override
public Publisher<UserData> getAllStream() {
LOG.info("getAllStream: ");
return new UserDataPublisher(data.values().stream().collect(Collectors.toUnmodifiableList()));
}
} | repos\spring-examples-java-17\spring-webflux\src\main\java\itx\examples\webflux\services\UserServiceImpl.java | 2 |
请完成以下Java代码 | public void setEditorSourceValueId(String editorSourceValueId) {
this.editorSourceValueId = editorSourceValueId;
}
@Override
public String getEditorSourceExtraValueId() {
return editorSourceExtraValueId;
}
@Override
public void setEditorSourceExtraValueId(String editorSourceExtraValueId) {
this.editorSourceExtraValueId = editorSourceExtraValueId;
}
@Override
public String getTenantId() {
return tenantId; | }
@Override
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public boolean hasEditorSource() {
return this.editorSourceValueId != null;
}
@Override
public boolean hasEditorSourceExtra() {
return this.editorSourceExtraValueId != null;
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\ModelEntityImpl.java | 1 |
请完成以下Java代码 | public void assignServiceToDeliveryOrder(@NonNull final DeliveryOrderId deliveryOrderId, @NonNull final ShipperId shipperId, @NonNull final CarrierService service)
{
final CarrierService actualService = getOrCreateService(shipperId, service.getExternalId(), service.getName());
final I_Carrier_ShipmentOrder_Service po = InterfaceWrapperHelper.newInstance(I_Carrier_ShipmentOrder_Service.class);
po.setCarrier_ShipmentOrder_ID(deliveryOrderId.getRepoId());
po.setCarrier_Service_ID(CarrierServiceId.toRepoId(actualService.getId()));
InterfaceWrapperHelper.saveRecord(po);
}
@NonNull
public CarrierService getOrCreateService(@NonNull final ShipperId shipperId, @NonNull final String externalId, @NonNull final String name)
{
final CarrierService cachedService = getCachedServiceByShipperExternalId(shipperId, externalId);
if (cachedService != null)
{
return cachedService;
}
return createShipperService(shipperId, externalId, name);
}
@Nullable
private CarrierService getCachedServiceByShipperExternalId(@NonNull final ShipperId shipperId, @Nullable final String externalId)
{
if (externalId == null)
{
return null;
}
return carrierServicesByExternalId.getOrLoad(shipperId + externalId, () ->
queryBL.createQueryBuilder(I_Carrier_Service.class)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_M_Shipper_ID, shipperId)
.addEqualsFilter(I_Carrier_Goods_Type.COLUMNNAME_ExternalId, externalId)
.firstOptional()
.map(CarrierShipmentOrderServiceRepository::fromRecord)
.orElse(null));
}
private static CarrierService fromRecord(@NotNull final I_Carrier_Service service)
{ | return CarrierService.builder()
.id(CarrierServiceId.ofRepoId(service.getCarrier_Service_ID()))
.externalId(service.getExternalId())
.name(service.getName())
.build();
}
private CarrierService createShipperService(@NonNull final ShipperId shipperId, @NonNull final String externalId, @NonNull final String name)
{
final I_Carrier_Service po = InterfaceWrapperHelper.newInstance(I_Carrier_Service.class);
po.setM_Shipper_ID(shipperId.getRepoId());
po.setExternalId(externalId);
po.setName(name);
InterfaceWrapperHelper.saveRecord(po);
return fromRecord(po);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\CarrierShipmentOrderServiceRepository.java | 1 |
请完成以下Java代码 | public void run() {
// 加一个分布式锁,只放一个请求去刷新缓存
RedisLock redisLock = new RedisLock((RedisTemplate) redisOperations, cacheKeyStr + "_lock");
try {
if (redisLock.lock()) {
// 获取锁之后再判断一下过期时间,看是否需要加载数据
Long ttl = CustomizedRedisCache.this.redisOperations.getExpire(cacheKeyStr);
if (null != ttl && ttl <= CustomizedRedisCache.this.preloadSecondTime) {
// 通过获取代理方法信息重新加载缓存数据
CustomizedRedisCache.this.getCacheSupport().refreshCacheByKey(CustomizedRedisCache.super.getName(), cacheKeyStr);
}
}
} catch (Exception e) {
logger.info(e.getMessage(), e);
} finally {
redisLock.unlock();
}
}
});
}
}
public long getExpirationSecondTime() {
return expirationSecondTime;
}
/**
* 获取RedisCacheKey
*
* @param key
* @return | */
public RedisCacheKey getRedisCacheKey(Object key) {
return new RedisCacheKey(key).usePrefix(this.prefix)
.withKeySerializer(redisOperations.getKeySerializer());
}
/**
* 获取RedisCacheKey
*
* @param key
* @return
*/
public String getCacheKey(Object key) {
return new String(getRedisCacheKey(key).getKeyBytes());
}
} | repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\CustomizedRedisCache.java | 1 |
请完成以下Java代码 | public final class OFXFileBankStatementLoader extends OFXBankStatementHandler implements BankStatementLoaderInterface
{
/**
* Method init
* @param controller MBankStatementLoader
* @return boolean
* @see org.compiere.impexp.BankStatementLoaderInterface#init(MBankStatementLoader)
*/
public boolean init(MBankStatementLoader controller)
{
boolean result = false;
FileInputStream m_stream = null;
try
{
// Try to open the file specified as a process parameter
if (controller.getLocalFileName() != null)
{
m_stream = new FileInputStream(controller.getLocalFileName());
}
// Try to open the file specified as part of the loader configuration
else if (controller.getFileName() != null)
{
m_stream = new FileInputStream(controller.getFileName());
}
else
{
return result;
}
if (!super.init(controller))
{
return result;
}
if (m_stream == null)
{
return result;
}
result = attachInput(m_stream);
}
catch(Exception e) | {
m_errorMessage = "ErrorReadingData";
m_errorDescription = "";
}
return result;
} // init
/**
* Method characters
* @param ch char[]
* @param start int
* @param length int
* @throws SAXException
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
public void characters (char ch[], int start, int length)
throws SAXException
{
/*
* There are no additional things to do when importing from file.
* All data is handled by OFXBankStatementHandler
*/
super.characters(ch, start, length);
} // characterS
} // OFXFileBankStatementLoader | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-legacy\org\compiere\impexp\OFXFileBankStatementLoader.java | 1 |
请完成以下Java代码 | public List<ExecutionListener> getExecutionListeners() {
return (List) super.getListeners(ExecutionListener.EVENTNAME_TAKE);
}
@Deprecated
public void setExecutionListeners(List<ExecutionListener> executionListeners) {
for (ExecutionListener executionListener : executionListeners) {
addExecutionListener(executionListener);
}
}
public String toString() {
return "("+source.getId()+")--"+(id!=null?id+"-->(":">(")+destination.getId()+")";
}
// getters and setters //////////////////////////////////////////////////////
public PvmProcessDefinition getProcessDefinition() {
return processDefinition;
}
protected void setSource(ActivityImpl source) { | this.source = source;
}
public PvmActivity getDestination() {
return destination;
}
public List<Integer> getWaypoints() {
return waypoints;
}
public void setWaypoints(List<Integer> waypoints) {
this.waypoints = waypoints;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\TransitionImpl.java | 1 |
请完成以下Java代码 | private ListenableFuture<Void> save(EdgeEventEntity entity) {
log.debug("Saving EdgeEventEntity [{}] ", entity);
if (entity.getTenantId() == null) {
log.trace("Save system edge event with predefined id {}", systemTenantId);
entity.setTenantId(systemTenantId);
}
if (entity.getUuid() == null) {
entity.setUuid(Uuids.timeBased());
}
return addToQueue(entity);
}
private ListenableFuture<Void> addToQueue(EdgeEventEntity entity) {
return queue.add(entity);
}
@Override
public PageData<EdgeEvent> findEdgeEvents(UUID tenantId, EdgeId edgeId, Long seqIdStart, Long seqIdEnd, TimePageLink pageLink) {
return DaoUtil.toPageData(
edgeEventRepository | .findEdgeEventsByTenantIdAndEdgeId(
tenantId,
edgeId.getId(),
pageLink.getTextSearch(),
pageLink.getStartTime(),
pageLink.getEndTime(),
seqIdStart,
seqIdEnd,
DaoUtil.toPageable(pageLink, SORT_ORDERS)));
}
@Override
public void cleanupEvents(long ttl) {
partitioningRepository.dropPartitionsBefore(TABLE_NAME, ttl, TimeUnit.HOURS.toMillis(partitionSizeInHours));
}
@Override
public void createPartition(EdgeEventEntity entity) {
partitioningRepository.createPartitionIfNotExists(TABLE_NAME, entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours));
}
} | repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\edge\JpaBaseEdgeEventDao.java | 1 |
请完成以下Java代码 | public class GlobalExceptionHandler {
Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);
/**
* 统一处理 BindException 错误
*
* @param ex 参数验证失败错误
* @return 参数验证失败响应
*/
@ExceptionHandler(BindException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public Wrapper<?> processBindException(BindException ex, HttpSession httpSession, HttpServletRequest request) {
// 获取错误信息
List<FieldError> fieldErrors = ex.getBindingResult().getFieldErrors();
// 目前消息只返回一条错误信息,所以只需要取第一条错误信息即可
Map<String, String> errorMap = null;
if (fieldErrors.size() > 0) { | errorMap = new HashMap<>(fieldErrors.size());
for (FieldError fieldError : fieldErrors) {
errorMap.put(fieldError.getField(), fieldError.getDefaultMessage());
}
}
// 请求路径
String url = request.getRequestURI();
logger.warn("请求sessionId:{},请求接口:{},请求参数:{}, 异常信息: {}", httpSession.getId(), url, errorMap, ex.getMessage(), ex);
return WrapMapper.wrap(10000, "参数校验异常", errorMap);
}
} | repos\spring-boot-student-master\spring-boot-student-validated\src\main\java\com\xiaolyuh\handler\GlobalExceptionHandler.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setLastNotifyTime(Date lastNotifyTime) {
this.lastNotifyTime = lastNotifyTime;
}
/** 通知次数 **/
public Integer getNotifyTimes() {
return notifyTimes;
}
/** 通知次数 **/
public void setNotifyTimes(Integer notifyTimes) {
this.notifyTimes = notifyTimes;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
/** 限制通知次数 **/
public Integer getLimitNotifyTimes() {
return limitNotifyTimes;
}
/** 限制通知次数 **/
public void setLimitNotifyTimes(Integer limitNotifyTimes) {
this.limitNotifyTimes = limitNotifyTimes;
}
/** 通知URL **/
public String getUrl() {
return url;
}
/** 通知URL **/
public void setUrl(String url) {
this.url = url == null ? null : url.trim();
}
/** 商户编号 **/
public String getMerchantNo() {
return merchantNo;
} | /** 商户编号 **/
public void setMerchantNo(String merchantNo) {
this.merchantNo = merchantNo == null ? null : merchantNo.trim();
}
/** 商户订单号 **/
public String getMerchantOrderNo() {
return merchantOrderNo;
}
/** 商户订单号 **/
public void setMerchantOrderNo(String merchantOrderNo) {
this.merchantOrderNo = merchantOrderNo == null ? null : merchantOrderNo.trim();
}
public String getNotifyType() {
return notifyType;
}
public void setNotifyType(String notifyType) {
this.notifyType = notifyType;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\entity\RpNotifyRecord.java | 2 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.