instruction string | input string | output string | source_file string | priority int64 |
|---|---|---|---|---|
请完成以下Java代码 | private boolean isUsePreliminaryDocumentNo()
{
return _usePreliminaryDocumentNo;
}
@NonNull
private DocumentNoBuilder.CalendarYearMonthAndDay getCalendarYearMonthAndDay(@NonNull final DocumentSequenceInfo docSeqInfo)
{
final CalendarYearMonthAndDay.CalendarYearMonthAndDayBuilder calendarYearMonthAndDayBuilder = CalendarYearMonthAndDay.builder()
.calendarYear(getCalendarYear(docSeqInfo.getDateColumn()))
.calendarMonth(DEFAULT_CALENDAR_MONTH_TO_USE)
.calendarDay(DEFAULT_CALENDAR_DAY_TO_USE);
if (docSeqInfo.isStartNewDay())
{
calendarYearMonthAndDayBuilder.calendarMonth(getCalendarMonth(docSeqInfo.getDateColumn()));
calendarYearMonthAndDayBuilder.calendarDay(getCalendarDay(docSeqInfo.getDateColumn()));
}
else if (docSeqInfo.isStartNewMonth()) | {
calendarYearMonthAndDayBuilder.calendarMonth(getCalendarMonth(docSeqInfo.getDateColumn()));
}
return calendarYearMonthAndDayBuilder.build();
}
@Builder
@Value
private static class CalendarYearMonthAndDay
{
String calendarYear;
String calendarMonth;
String calendarDay;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\sequence\impl\DocumentNoBuilder.java | 1 |
请完成以下Java代码 | protected String getOrderByValue(String sortBy) {
return super.getOrderBy();
}
@Override
protected boolean isValidSortByValue(String value) {
return false;
}
private List<QueryVariableValue> createQueryVariableValues(VariableSerializers variableTypes, List<VariableQueryParameterDto> variables, String dbType) {
List<QueryVariableValue> values = new ArrayList<QueryVariableValue>();
if (variables == null) {
return values;
} | for (VariableQueryParameterDto variable : variables) {
QueryVariableValue value = new QueryVariableValue(
variable.getName(),
resolveVariableValue(variable.getValue()),
ConditionQueryParameterDto.getQueryOperator(variable.getOperator()),
false);
value.initialize(variableTypes, dbType);
values.add(value);
}
return values;
}
} | repos\camunda-bpm-platform-master\webapps\assembly\src\main\java\org\camunda\bpm\cockpit\impl\plugin\base\dto\query\ProcessDefinitionQueryDto.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PersistentAuditEvent implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "event_id")
private Long id;
@NotNull
@Column(nullable = false)
private String principal;
@Column(name = "event_date")
private Instant auditEventDate;
@Column(name = "event_type")
private String auditEventType;
@ElementCollection
@MapKeyColumn(name = "name")
@Column(name = "value")
@CollectionTable(name = "jhi_persistent_audit_evt_data", joinColumns=@JoinColumn(name="event_id"))
private Map<String, String> data = new HashMap<>();
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPrincipal() {
return principal;
}
public void setPrincipal(String principal) {
this.principal = principal;
}
public Instant getAuditEventDate() {
return auditEventDate;
}
public void setAuditEventDate(Instant auditEventDate) { | this.auditEventDate = auditEventDate;
}
public String getAuditEventType() {
return auditEventType;
}
public void setAuditEventType(String auditEventType) {
this.auditEventType = auditEventType;
}
public Map<String, String> getData() {
return data;
}
public void setData(Map<String, String> data) {
this.data = data;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
PersistentAuditEvent persistentAuditEvent = (PersistentAuditEvent) o;
return !(persistentAuditEvent.getId() == null || getId() == null) && Objects.equals(getId(), persistentAuditEvent.getId());
}
@Override
public int hashCode() {
return Objects.hashCode(getId());
}
@Override
public String toString() {
return "PersistentAuditEvent{" +
"principal='" + principal + '\'' +
", auditEventDate=" + auditEventDate +
", auditEventType='" + auditEventType + '\'' +
'}';
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\PersistentAuditEvent.java | 2 |
请完成以下Java代码 | public boolean isNoValue()
{
return noValue;
}
public boolean isSingleValue()
{
return singleValue != null;
}
public boolean isMultipleValues()
{
return multipleValues != null;
}
@Nullable
public Object getSingleValueAsObject()
{
if (noValue)
{
return null;
}
else if (singleValue != null)
{
return singleValue;
}
else
{
throw new AdempiereException("Not a single value instance: " + this);
}
}
public ImmutableList<Object> getMultipleValues()
{
if (multipleValues != null)
{
return multipleValues;
}
else
{
throw new AdempiereException("Not a multiple values instance: " + this);
}
}
@Nullable
public Integer getSingleValueAsInteger(@Nullable final Integer defaultValue)
{
final Object value = getSingleValueAsObject();
if (value == null)
{
return defaultValue;
}
else if (value instanceof Number)
{
return ((Number)value).intValue();
}
else
{
final String valueStr = StringUtils.trimBlankToNull(value.toString());
if (valueStr == null)
{
return defaultValue;
}
else
{
return Integer.parseInt(valueStr);
}
}
}
@Nullable
public String getSingleValueAsString()
{
final Object value = getSingleValueAsObject();
return value != null ? value.toString() : null;
}
public Stream<IdsToFilter> streamSingleValues()
{
if (noValue)
{
return Stream.empty();
}
else if (singleValue != null)
{
return Stream.of(this);
} | else
{
Objects.requireNonNull(multipleValues);
return multipleValues.stream().map(IdsToFilter::ofSingleValue);
}
}
public ImmutableList<Object> toImmutableList()
{
if (noValue)
{
return ImmutableList.of();
}
else if (singleValue != null)
{
return ImmutableList.of(singleValue);
}
else
{
Objects.requireNonNull(multipleValues);
return multipleValues;
}
}
public IdsToFilter mergeWith(@NonNull final IdsToFilter other)
{
if (other.isNoValue())
{
return this;
}
else if (isNoValue())
{
return other;
}
else
{
final ImmutableSet<Object> multipleValues = Stream.concat(toImmutableList().stream(), other.toImmutableList().stream())
.distinct()
.collect(ImmutableSet.toImmutableSet());
return ofMultipleValues(multipleValues);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\lookup\IdsToFilter.java | 1 |
请完成以下Java代码 | public boolean isSingleProductStorageMatching(@NonNull final I_M_HU hu, @NonNull final ProductId productId)
{
return getStorage(hu).isSingleProductStorageMatching(productId);
}
@NonNull
public IHUProductStorage getSingleHUProductStorage(@NonNull final I_M_HU hu)
{
return getStorage(hu).getSingleHUProductStorage();
}
@Override
public List<IHUProductStorage> getProductStorages(@NonNull final I_M_HU hu)
{
return getStorage(hu).getProductStorages();
}
@Override
public IHUProductStorage getProductStorage(@NonNull final I_M_HU hu, @NonNull ProductId productId)
{
return getStorage(hu).getProductStorage(productId);
} | @Override
public @NonNull ImmutableMap<HuId, Set<ProductId>> getHUProductIds(@NonNull final List<I_M_HU> hus)
{
final Map<HuId, Set<ProductId>> huId2ProductIds = new HashMap<>();
streamHUProductStorages(hus)
.forEach(productStorage -> {
final Set<ProductId> productIds = new HashSet<>();
productIds.add(productStorage.getProductId());
huId2ProductIds.merge(productStorage.getHuId(), productIds, (oldValues, newValues) -> {
oldValues.addAll(newValues);
return oldValues;
});
});
return ImmutableMap.copyOf(huId2ProductIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\storage\impl\DefaultHUStorageFactory.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class F2FPayController extends BaseController {
private static final Logger logger = LoggerFactory.getLogger(F2FPayController.class);
@Autowired
private RpTradePaymentManagerService rpTradePaymentManagerService;
@Autowired
private CnpPayService cnpPayService;
@Autowired
private RpTradePaymentQueryService queryService;
/**
* 条码支付,商户通过前置设备获取到用户支付授权码后,请求支付网关支付.
*
* @return
*/
@RequestMapping("/doPay")
public String initPay(@ModelAttribute F2FPayRequestBo f2FPayRequestBo, BindingResult bindingResult, HttpServletRequest httpServletRequest, ModelMap modelMap) {
try{
//获取支付配置
RpUserPayConfig rpUserPayConfig = cnpPayService.checkParamAndGetUserPayConfig(f2FPayRequestBo, bindingResult, httpServletRequest);
//发起支付
F2FPayResultVo f2FPayResultVo = rpTradePaymentManagerService.f2fPay(rpUserPayConfig ,f2FPayRequestBo);
logger.debug("条码支付--支付结果==>{}", f2FPayResultVo);
modelMap.put("result", f2FPayResultVo);
return "/f2fAffirmPay";
} catch (BizException e) {
logger.error("业务异常:", e);
modelMap.put("errorMsg", e.getMsg()); | return "exception/exception";
} catch (Exception e) {
logger.error("系统异常:", e);
modelMap.put("errorMsg", "系统异常");
return "exception/exception";
}
}
@RequestMapping("/order/query")
@ResponseBody
public String orderQuery(String trxNo) {
return JSONObject.toJSONString(queryService.getRecordByTrxNo(trxNo));
}
} | repos\roncoo-pay-master\roncoo-pay-web-gateway\src\main\java\com\roncoo\pay\controller\F2FPayController.java | 2 |
请完成以下Java代码 | public class SysUser {
private Integer id;
private String username;
private String password;
private List<SysRole> roles;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username; | }
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<SysRole> getRoles() {
return roles;
}
public void setRoles(List<SysRole> roles) {
this.roles = roles;
}
} | repos\springBoot-master\springboot-SpringSecurity0\src\main\java\com\us\example\domain\SysUser.java | 1 |
请完成以下Java代码 | public Integer getShowStatus() {
return showStatus;
}
public void setShowStatus(Integer showStatus) {
this.showStatus = showStatus;
}
public byte[] getPic() {
return pic;
}
public void setPic(byte[] pic) {
this.pic = pic;
}
@Override | public String toString() {
StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName());
sb.append(" [");
sb.append("Hash = ").append(hashCode());
sb.append(", id=").append(id);
sb.append(", name=").append(name);
sb.append(", subTitle=").append(subTitle);
sb.append(", sort=").append(sort);
sb.append(", showStatus=").append(showStatus);
sb.append(", pic=").append(pic);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\CmsPrefrenceArea.java | 1 |
请完成以下Java代码 | public void setBill_BPartner_ID (final int Bill_BPartner_ID)
{
if (Bill_BPartner_ID < 1)
set_Value (COLUMNNAME_Bill_BPartner_ID, null);
else
set_Value (COLUMNNAME_Bill_BPartner_ID, Bill_BPartner_ID);
}
@Override
public int getBill_BPartner_ID()
{
return get_ValueAsInt(COLUMNNAME_Bill_BPartner_ID);
}
@Override
public org.compiere.model.I_C_Invoice getC_Invoice()
{
return get_ValueAsPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class);
}
@Override
public void setC_Invoice(final org.compiere.model.I_C_Invoice C_Invoice)
{
set_ValueFromPO(COLUMNNAME_C_Invoice_ID, org.compiere.model.I_C_Invoice.class, C_Invoice);
}
@Override
public void setC_Invoice_ID (final int C_Invoice_ID)
{
throw new IllegalArgumentException ("C_Invoice_ID is virtual column"); }
@Override
public int getC_Invoice_ID()
{
return get_ValueAsInt(COLUMNNAME_C_Invoice_ID);
}
@Override
public void setIsDeliveryStop (final boolean IsDeliveryStop)
{
set_Value (COLUMNNAME_IsDeliveryStop, IsDeliveryStop);
}
@Override
public boolean isDeliveryStop()
{
return get_ValueAsBoolean(COLUMNNAME_IsDeliveryStop);
}
@Override
public void setIsPaid (final boolean IsPaid)
{
throw new IllegalArgumentException ("IsPaid is virtual column"); }
@Override
public boolean isPaid()
{
return get_ValueAsBoolean(COLUMNNAME_IsPaid);
}
@Override
public void setM_Shipment_Constraint_ID (final int M_Shipment_Constraint_ID)
{
if (M_Shipment_Constraint_ID < 1)
set_ValueNoCheck (COLUMNNAME_M_Shipment_Constraint_ID, null);
else
set_ValueNoCheck (COLUMNNAME_M_Shipment_Constraint_ID, M_Shipment_Constraint_ID);
} | @Override
public int getM_Shipment_Constraint_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Shipment_Constraint_ID);
}
@Override
public void setSourceDoc_Record_ID (final int SourceDoc_Record_ID)
{
if (SourceDoc_Record_ID < 1)
set_Value (COLUMNNAME_SourceDoc_Record_ID, null);
else
set_Value (COLUMNNAME_SourceDoc_Record_ID, SourceDoc_Record_ID);
}
@Override
public int getSourceDoc_Record_ID()
{
return get_ValueAsInt(COLUMNNAME_SourceDoc_Record_ID);
}
@Override
public void setSourceDoc_Table_ID (final int SourceDoc_Table_ID)
{
if (SourceDoc_Table_ID < 1)
set_Value (COLUMNNAME_SourceDoc_Table_ID, null);
else
set_Value (COLUMNNAME_SourceDoc_Table_ID, SourceDoc_Table_ID);
}
@Override
public int getSourceDoc_Table_ID()
{
return get_ValueAsInt(COLUMNNAME_SourceDoc_Table_ID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\inoutcandidate\model\X_M_Shipment_Constraint.java | 1 |
请完成以下Java代码 | public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getCategoryId() {
return categoryId;
}
public void setCategoryId(Long categoryId) {
this.categoryId = categoryId;
}
@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(", createTime=").append(createTime);
sb.append(", name=").append(name);
sb.append(", url=").append(url);
sb.append(", description=").append(description);
sb.append(", categoryId=").append(categoryId);
sb.append(", serialVersionUID=").append(serialVersionUID);
sb.append("]");
return sb.toString();
}
} | repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsResource.java | 1 |
请完成以下Java代码 | public void validateWorkpackageProcessor(final I_C_Queue_PackageProcessor packageProcessorDef)
{
final IWorkpackageProcessor packageProcessor = getWorkpackageProcessor(packageProcessorDef, false); // checkBlacklist=false
Check.assumeNotNull(packageProcessor, "No " + IWorkpackageProcessor.class + " could be loaded for {}", packageProcessorDef);
// If everything is ok, make sure to remove it from list
blacklist.removeFromBlacklist(packageProcessorDef.getC_Queue_PackageProcessor_ID());
}
protected IWorkpackageProcessor getWorkpackageProcessorInstance(final String classname)
{
final IWorkpackageProcessor packageProcessor = Util.getInstance(IWorkpackageProcessor.class, classname);
return packageProcessor;
}
@Override
public boolean isWorkpackageProcessorBlacklisted(final int workpackageProcessorId)
{
return blacklist.isBlacklisted(workpackageProcessorId);
}
public WorkpackageProcessorBlackList getBlackList()
{
return blacklist;
}
private volatile WorkpackageProcessorFactoryJMX mbean = null;
@Override
public synchronized Object getMBean()
{
if (mbean == null)
{
mbean = new WorkpackageProcessorFactoryJMX(this);
}
return mbean;
}
@Override | public IMutableQueueProcessorStatistics getWorkpackageProcessorStatistics(@NonNull IWorkpackageProcessor workpackageProcessor)
{
// NOTE: keep in sync with getWorkpackageProcessorStatistics(I_C_Queue_PackageProcessor workpackage). Both methods shall build the name in the same way
final String workpackageProcessorName = workpackageProcessor.getClass().getName();
return new MonitorableQueueProcessorStatistics(workpackageProcessorName);
}
@Override
public IMutableQueueProcessorStatistics getWorkpackageProcessorStatistics(@NonNull final I_C_Queue_PackageProcessor workpackageProcessorDef)
{
// NOTE: keep in sync with getWorkpackageProcessorStatistics(IWorkpackageProcessor workpackageProcessor). Both methods shall build the name in the same way
final String workpackageProcessorName = workpackageProcessorDef.getClassname();
return new MonitorableQueueProcessorStatistics(workpackageProcessorName);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\async\processor\impl\WorkpackageProcessorFactory.java | 1 |
请完成以下Java代码 | public URLConnection openConnection(URL url) throws IOException {
if (url.getPath() == null || url.getPath().trim().length() == 0) {
throw new MalformedURLException("Path can not be null or empty. Syntax: " + SYNTAX);
}
bpmnXmlURL = new URL(url.getPath());
LOGGER.debug("BPMN xml URL is: [{}]", bpmnXmlURL);
return new Connection(url);
}
public URL getBpmnXmlURL() {
return bpmnXmlURL;
}
public class Connection extends URLConnection {
public Connection(URL url) {
super(url);
}
@Override
public void connect() throws IOException {
} | @Override
public InputStream getInputStream() throws IOException {
try {
ByteArrayOutputStream os = new ByteArrayOutputStream();
BpmnTransformer.transform(bpmnXmlURL, os);
os.close();
return new ByteArrayInputStream(os.toByteArray());
} catch (Exception e) {
LOGGER.error("Error opening spring xml url", e);
throw (IOException) new IOException("Error opening spring xml url").initCause(e);
}
}
}
} | repos\flowable-engine-main\modules\flowable-osgi\src\main\java\org\flowable\osgi\BpmnURLHandler.java | 1 |
请完成以下Java代码 | public String getImplementation() {
return implementation;
}
public Date getCreateTime() {
return createTime;
}
public Date getCreateTimeAfter() {
return createTimeAfter;
}
public Date getCreateTimeBefore() {
return createTimeBefore;
}
public String getResourceName() {
return resourceName;
} | public String getResourceNameLike() {
return resourceNameLike;
}
public String getCategoryNotEquals() {
return categoryNotEquals;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
public boolean isWithoutTenantId() {
return withoutTenantId;
}
} | repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\ChannelDefinitionQueryImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class ResponseStatusController {
@GetMapping(value = "/ok", produces = MediaType.APPLICATION_JSON_VALUE)
public Flux<String> ok() {
return Flux.just("ok");
}
@GetMapping(value = "/no-content", produces = MediaType.APPLICATION_JSON_VALUE)
@ResponseStatus(HttpStatus.NO_CONTENT)
public Flux<String> noContent() {
return Flux.empty();
}
@GetMapping(value = "/accepted", produces = MediaType.APPLICATION_JSON_VALUE)
public Flux<String> accepted(ServerHttpResponse response) {
response.setStatusCode(HttpStatus.ACCEPTED);
return Flux.just("accepted");
}
@GetMapping(value = "/bad-request")
public Mono<String> badRequest() {
return Mono.error(new IllegalArgumentException());
}
@ResponseStatus(value = HttpStatus.BAD_REQUEST, reason = "Illegal arguments")
@ExceptionHandler(IllegalArgumentException.class)
public void illegalArgument() {
}
@GetMapping(value = "/unauthorized") | public ResponseEntity<Mono<String>> unathorized() {
return ResponseEntity
.status(HttpStatus.UNAUTHORIZED)
.header("X-Reason", "user-invalid")
.body(Mono.just("unauthorized"));
}
@Bean
public RouterFunction<ServerResponse> notFound() {
return RouterFunctions.route(GET("/statuses/not-found"), request -> ServerResponse
.notFound()
.build());
}
} | repos\tutorials-master\spring-reactive-modules\spring-webflux-2\src\main\java\com\baeldung\webflux\responsestatus\ResponseStatusController.java | 2 |
请完成以下Java代码 | public User getById(CacheKey key) {
return cache.get(key);
}
public void storeById(CacheKey key, User user) {
cache.put(key, user);
}
public static class CacheKey {
private final Object value;
public CacheKey(String value) {
this.value = value;
}
public CacheKey(Long value) {
this.value = value; | }
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
CacheKey cacheKey = (CacheKey) o;
return value.equals(cacheKey.value);
}
@Override
public int hashCode() {
return Objects.hash(value);
}
}
} | repos\tutorials-master\core-java-modules\core-java-collections-maps-5\src\main\java\com\baeldung\map\multikey\WrapperClassUserCache.java | 1 |
请完成以下Java代码 | public boolean isFunctionRow(final int row)
{
return false;
}
@Override
public boolean isPageBreak(final int row, final int col)
{
return false;
}
private final HashMap<String, MLookup> m_buttonLookups = new HashMap<>();
private MLookup getButtonLookup(final GridField mField)
{
MLookup lookup = m_buttonLookups.get(mField.getColumnName());
if (lookup != null)
{
return lookup;
}
// TODO: refactor with org.compiere.grid.ed.VButton.setField(GridField)
if (mField.getColumnName().endsWith("_ID") && !IColumnBL.isRecordIdColumnName(mField.getColumnName()))
{
lookup = lookupFactory.get(Env.getCtx(), mField.getWindowNo(), 0,
mField.getAD_Column_ID(), DisplayType.Search);
}
else if (mField.getAD_Reference_Value_ID() != null)
{
// Assuming List
lookup = lookupFactory.get(Env.getCtx(), mField.getWindowNo(), 0,
mField.getAD_Column_ID(), DisplayType.List);
}
//
m_buttonLookups.put(mField.getColumnName(), lookup);
return lookup;
}
@Override | protected List<CellValue> getNextRow()
{
final ArrayList<CellValue> result = new ArrayList<>();
for (int i = 0; i < getColumnCount(); i++)
{
result.add(getValueAt(rowNumber, i));
}
rowNumber++;
return result;
}
@Override
protected boolean hasNextRow()
{
return rowNumber < getRowCount();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\impexp\spreadsheet\excel\GridTabExcelExporter.java | 1 |
请完成以下Java代码 | public String getMessageName() {
return messageName;
}
public String getBusinessKey() {
return businessKey;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public Map<String, Object> getCorrelationProcessInstanceVariables() {
return correlationProcessInstanceVariables;
}
public Map<String, Object> getCorrelationLocalVariables() {
return correlationLocalVariables;
}
public Map<String, Object> getPayloadProcessInstanceVariables() {
return payloadProcessInstanceVariables;
} | public VariableMap getPayloadProcessInstanceVariablesLocal() {
return payloadProcessInstanceVariablesLocal;
}
public VariableMap getPayloadProcessInstanceVariablesToTriggeredScope() {
return payloadProcessInstanceVariablesToTriggeredScope;
}
public boolean isExclusiveCorrelation() {
return isExclusiveCorrelation;
}
public String getTenantId() {
return tenantId;
}
public boolean isTenantIdSet() {
return isTenantIdSet;
}
public boolean isExecutionsOnly() {
return executionsOnly;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\MessageCorrelationBuilderImpl.java | 1 |
请完成以下Java代码 | protected String getExpressionTextForLanguage(DmnExpressionImpl expression, String expressionLanguage) {
String expressionText = expression.getExpression();
if (expressionText != null) {
if (isJuelExpression(expressionLanguage) && !StringUtil.isExpression(expressionText)) {
return "${" + expressionText + "}";
} else {
return expressionText;
}
} else {
return null;
}
}
private boolean isJuelExpression(String expressionLanguage) {
return DefaultDmnEngineConfiguration.JUEL_EXPRESSION_LANGUAGE.equalsIgnoreCase(expressionLanguage);
}
protected ScriptEngine getScriptEngineForName(String expressionLanguage) {
ensureNotNull("expressionLanguage", expressionLanguage);
ScriptEngine scriptEngine = scriptEngineResolver.getScriptEngineForLanguage(expressionLanguage);
if (scriptEngine != null) { | return scriptEngine;
} else {
throw LOG.noScriptEngineFoundForLanguage(expressionLanguage);
}
}
protected boolean isElExpression(String expressionLanguage) {
return isJuelExpression(expressionLanguage);
}
public boolean isFeelExpressionLanguage(String expressionLanguage) {
ensureNotNull("expressionLanguage", expressionLanguage);
return expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE) ||
expressionLanguage.toLowerCase().equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_ALTERNATIVE) ||
expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN12) ||
expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN13) ||
expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN14) ||
expressionLanguage.equals(DefaultDmnEngineConfiguration.FEEL_EXPRESSION_LANGUAGE_DMN15);
}
} | repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\evaluation\ExpressionEvaluationHandler.java | 1 |
请完成以下Java代码 | public UUID getId() {
return id;
}
public String getContent() {
return content;
}
public Boolean getCorrectAnswer() {
return correctAnswer;
}
public Boolean getShouldBeAsked() {
return shouldBeAsked;
}
public Boolean isEasy() {
return isEasy;
}
public Boolean getWasAskedBefore() {
return wasAskedBefore;
}
public void setId(UUID id) {
this.id = id;
} | public void setContent(String content) {
this.content = content;
}
public void setCorrectAnswer(Boolean correctAnswer) {
this.correctAnswer = correctAnswer;
}
public void setShouldBeAsked(Boolean shouldBeAsked) {
this.shouldBeAsked = shouldBeAsked;
}
public void setEasy(Boolean easy) {
isEasy = easy;
}
public void setWasAskedBefore(Boolean wasAskedBefore) {
this.wasAskedBefore = wasAskedBefore;
}
} | repos\tutorials-master\persistence-modules\hibernate-mapping-2\src\main\java\com\baeldung\hibernate\booleanconverters\model\Question.java | 1 |
请完成以下Java代码 | public void setByteValue(byte[] byteValue) {
this.byteValue = byteValue;
}
public int getRevision() {
return revision;
}
public void setRevision(int revision) {
this.revision = revision;
}
public void setByteArrayId(String id) {
byteArrayId = id;
}
public String getByteArrayId() {
return byteArrayId;
}
public String getVariableInstanceId() {
return variableInstanceId;
}
public void setVariableInstanceId(String variableInstanceId) {
this.variableInstanceId = variableInstanceId;
}
public String getScopeActivityInstanceId() {
return scopeActivityInstanceId;
}
public void setScopeActivityInstanceId(String scopeActivityInstanceId) {
this.scopeActivityInstanceId = scopeActivityInstanceId;
}
public void setInitial(Boolean isInitial) {
this.isInitial = isInitial;
}
public Boolean isInitial() {
return isInitial;
}
@Override
public String toString() { | return this.getClass().getSimpleName()
+ "[variableName=" + variableName
+ ", variableInstanceId=" + variableInstanceId
+ ", revision=" + revision
+ ", serializerName=" + serializerName
+ ", longValue=" + longValue
+ ", doubleValue=" + doubleValue
+ ", textValue=" + textValue
+ ", textValue2=" + textValue2
+ ", byteArrayId=" + byteArrayId
+ ", activityInstanceId=" + activityInstanceId
+ ", scopeActivityInstanceId=" + scopeActivityInstanceId
+ ", eventType=" + eventType
+ ", executionId=" + executionId
+ ", id=" + id
+ ", processDefinitionId=" + processDefinitionId
+ ", processInstanceId=" + processInstanceId
+ ", taskId=" + taskId
+ ", timestamp=" + timestamp
+ ", tenantId=" + tenantId
+ ", isInitial=" + isInitial
+ "]";
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricVariableUpdateEventEntity.java | 1 |
请完成以下Java代码 | public void setAD_Workflow_Access_ID (int AD_Workflow_Access_ID)
{
if (AD_Workflow_Access_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Workflow_Access_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Workflow_Access_ID, Integer.valueOf(AD_Workflow_Access_ID));
}
/** Get AD_Workflow_Access.
@return AD_Workflow_Access */
@Override
public int getAD_Workflow_Access_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workflow_Access_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_Workflow getAD_Workflow() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_Workflow_ID, org.compiere.model.I_AD_Workflow.class);
}
@Override
public void setAD_Workflow(org.compiere.model.I_AD_Workflow AD_Workflow)
{
set_ValueFromPO(COLUMNNAME_AD_Workflow_ID, org.compiere.model.I_AD_Workflow.class, AD_Workflow);
}
/** Set Workflow.
@param AD_Workflow_ID
Workflow or combination of tasks
*/
@Override
public void setAD_Workflow_ID (int AD_Workflow_ID)
{
if (AD_Workflow_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_Workflow_ID, Integer.valueOf(AD_Workflow_ID));
}
/** Get Workflow.
@return Workflow or combination of tasks
*/
@Override
public int getAD_Workflow_ID ()
{ | Integer ii = (Integer)get_Value(COLUMNNAME_AD_Workflow_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Lesen und Schreiben.
@param IsReadWrite
Field is read / write
*/
@Override
public void setIsReadWrite (boolean IsReadWrite)
{
set_Value (COLUMNNAME_IsReadWrite, Boolean.valueOf(IsReadWrite));
}
/** Get Lesen und Schreiben.
@return Field is read / write
*/
@Override
public boolean isReadWrite ()
{
Object oo = get_Value(COLUMNNAME_IsReadWrite);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Workflow_Access.java | 1 |
请完成以下Java代码 | public int getM_Product_ID()
{
return get_ValueAsInt(COLUMNNAME_M_Product_ID);
}
@Override
public void setName(final java.lang.String Name)
{
set_Value(COLUMNNAME_Name, Name);
}
@Override
public java.lang.String getName()
{
return get_ValueAsString(COLUMNNAME_Name);
}
@Override
public void setValue(final @Nullable java.lang.String Value)
{
set_Value(COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value); | }
@Override
public void setWidth(final @Nullable BigDecimal Width)
{
set_Value(COLUMNNAME_Width, Width);
}
@Override
public BigDecimal getWidth()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Width);
return bd != null ? bd : BigDecimal.ZERO;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PackagingContainer.java | 1 |
请完成以下Java代码 | public void addDeploymentMappings(List<ImmutablePair<String, String>> mappingsList, Collection<String> idList) {
if (ids != null) {
ids = null;
mappings = null;
}
Set<String> missingIds = idList == null ? null : new HashSet<>(idList);
mappingsList.forEach(pair -> {
String deploymentId = pair.getLeft();
Set<String> idSet = collectedMappings.get(deploymentId);
if (idSet == null) {
idSet = new HashSet<>();
collectedMappings.put(deploymentId, idSet);
}
idSet.add(pair.getRight());
if (missingIds != null) {
missingIds.remove(pair.getRight());
}
});
// add missing ids to "null" deployment id
if (missingIds != null && !missingIds.isEmpty()) {
Set<String> nullIds = collectedMappings.get(null);
if (nullIds == null) {
nullIds = new HashSet<>();
collectedMappings.put(null, nullIds);
}
nullIds.addAll(missingIds);
}
}
/**
* @return the list of ids that are mapped to deployment ids, ordered by
* deployment id
*/
public List<String> getIds() { | if (ids == null) {
createDeploymentMappings();
}
return ids;
}
/**
* @return the list of {@link DeploymentMapping}s
*/
public DeploymentMappings getMappings() {
if (mappings == null) {
createDeploymentMappings();
}
return mappings;
}
public boolean isEmpty() {
return collectedMappings.isEmpty();
}
protected void createDeploymentMappings() {
ids = new ArrayList<>();
mappings = new DeploymentMappings();
for (Entry<String, Set<String>> mapping : collectedMappings.entrySet()) {
ids.addAll(mapping.getValue());
mappings.add(new DeploymentMapping(mapping.getKey(), mapping.getValue().size()));
}
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\batch\BatchElementConfiguration.java | 1 |
请完成以下Java代码 | public String getNamespace() {
return namespace;
}
public void setNamespace(String namespace) {
this.namespace = namespace;
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
if (namespacePrefix != null) {
sb.append(namespacePrefix);
if (name != null) {
sb.append(":").append(name);
}
} else {
sb.append(name);
}
if (value != null) {
sb.append("=").append(value);
} | return sb.toString();
}
@Override
public DmnExtensionAttribute clone() {
DmnExtensionAttribute clone = new DmnExtensionAttribute();
clone.setValues(this);
return clone;
}
public void setValues(DmnExtensionAttribute otherAttribute) {
setName(otherAttribute.getName());
setValue(otherAttribute.getValue());
setNamespacePrefix(otherAttribute.getNamespacePrefix());
setNamespace(otherAttribute.getNamespace());
}
} | repos\flowable-engine-main\modules\flowable-dmn-model\src\main\java\org\flowable\dmn\model\DmnExtensionAttribute.java | 1 |
请完成以下Java代码 | public void setPrescriptionRequestTimestamp (final @Nullable java.sql.Timestamp PrescriptionRequestTimestamp)
{
set_Value (COLUMNNAME_PrescriptionRequestTimestamp, PrescriptionRequestTimestamp);
}
@Override
public java.sql.Timestamp getPrescriptionRequestTimestamp()
{
return get_ValueAsTimestamp(COLUMNNAME_PrescriptionRequestTimestamp);
}
@Override
public void setPrescriptionRequestUpdateAt (final @Nullable java.sql.Timestamp PrescriptionRequestUpdateAt)
{
set_Value (COLUMNNAME_PrescriptionRequestUpdateAt, PrescriptionRequestUpdateAt);
}
@Override
public java.sql.Timestamp getPrescriptionRequestUpdateAt()
{
return get_ValueAsTimestamp(COLUMNNAME_PrescriptionRequestUpdateAt);
}
/**
* PrescriptionType AD_Reference_ID=541296
* Reference name: Rezepttyp
*/
public static final int PRESCRIPTIONTYPE_AD_Reference_ID=541296;
/** Arzneimittel = 0 */
public static final String PRESCRIPTIONTYPE_Arzneimittel = "0";
/** Verbandstoffe = 1 */
public static final String PRESCRIPTIONTYPE_Verbandstoffe = "1";
/** BtM-Rezept = 2 */
public static final String PRESCRIPTIONTYPE_BtM_Rezept = "2";
/** Pflegehilfsmittel = 3 */
public static final String PRESCRIPTIONTYPE_Pflegehilfsmittel = "3";
/** Hilfsmittel zum Verbrauch bestimmt = 4 */
public static final String PRESCRIPTIONTYPE_HilfsmittelZumVerbrauchBestimmt = "4";
/** Hilfsmittel zum Gebrauch bestimmt = 5 */
public static final String PRESCRIPTIONTYPE_HilfsmittelZumGebrauchBestimmt = "5";
@Override
public void setPrescriptionType (final @Nullable java.lang.String PrescriptionType)
{
set_Value (COLUMNNAME_PrescriptionType, PrescriptionType);
}
@Override
public java.lang.String getPrescriptionType()
{
return get_ValueAsString(COLUMNNAME_PrescriptionType);
} | @Override
public void setStartDate (final @Nullable java.sql.Timestamp StartDate)
{
set_Value (COLUMNNAME_StartDate, StartDate);
}
@Override
public java.sql.Timestamp getStartDate()
{
return get_ValueAsTimestamp(COLUMNNAME_StartDate);
}
@Override
public void setTherapyTypeIds (final @Nullable java.lang.String TherapyTypeIds)
{
set_Value (COLUMNNAME_TherapyTypeIds, TherapyTypeIds);
}
@Override
public java.lang.String getTherapyTypeIds()
{
return get_ValueAsString(COLUMNNAME_TherapyTypeIds);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.healthcare.alberta\src\main\java-gen\de\metas\vertical\healthcare\alberta\model\X_Alberta_PrescriptionRequest.java | 1 |
请完成以下Java代码 | public List<User> getUserList() {
// 处理"/users/"的GET请求,用来获取用户列表
// 还可以通过@RequestParam从页面中传递参数来进行查询条件或者翻页信息的传递
List<User> r = new ArrayList<User>(users.values());
return r;
}
@RequestMapping(value="/", method=RequestMethod.POST)
public String postUser(@ModelAttribute User user) {
// 处理"/users/"的POST请求,用来创建User
// 除了@ModelAttribute绑定参数之外,还可以通过@RequestParam从页面中传递参数
users.put(user.getId(), user);
return "success";
}
@RequestMapping(value="/{id}", method=RequestMethod.GET)
public User getUser(@PathVariable Long id) {
// 处理"/users/{id}"的GET请求,用来获取url中id值的User信息
// url中的id可通过@PathVariable绑定到函数的参数中
return users.get(id);
} | @RequestMapping(value="/{id}", method=RequestMethod.PUT)
public String putUser(@PathVariable Long id, @ModelAttribute User user) {
// 处理"/users/{id}"的PUT请求,用来更新User信息
User u = users.get(id);
u.setName(user.getName());
u.setAge(user.getAge());
users.put(id, u);
return "success";
}
@RequestMapping(value="/{id}", method=RequestMethod.DELETE)
public String deleteUser(@PathVariable Long id) {
// 处理"/users/{id}"的DELETE请求,用来删除User
users.remove(id);
return "success";
}
} | repos\SpringBoot-Learning-master\1.x\Chapter3-1-1\src\main\java\com\didispace\web\UserController.java | 1 |
请完成以下Java代码 | public void setSasSignature (final @Nullable String SasSignature)
{
set_Value (COLUMNNAME_SasSignature, SasSignature);
}
@Override
public String getSasSignature()
{
return get_ValueAsString(COLUMNNAME_SasSignature);
}
/**
* Type AD_Reference_ID=542016
* Reference name: ExternalSystem_Outbound_Endpoint_EndpointType
*/
public static final int TYPE_AD_Reference_ID=542016;
/** HTTP = HTTP */
public static final String TYPE_HTTP = "HTTP";
/** SFTP = SFTP */
public static final String TYPE_SFTP = "SFTP";
/** FILE = FILE */
public static final String TYPE_FILE = "FILE";
/** EMAIL = EMAIL */
public static final String TYPE_EMAIL = "EMAIL";
/** TCP = TCP */
public static final String TYPE_TCP = "TCP";
@Override
public void setType (final String Type) | {
set_Value (COLUMNNAME_Type, Type);
}
@Override
public String getType()
{
return get_ValueAsString(COLUMNNAME_Type);
}
@Override
public void setValue (final String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Outbound_Endpoint.java | 1 |
请完成以下Java代码 | public void setIncludeSubDomains(boolean includeSubDomains) {
this.includeSubDomains = includeSubDomains;
updateHstsHeaderValue();
}
/**
* <p>
* If true, preload will be included in HSTS Header. The default is false.
* </p>
*
* <p>
* See <a href="https://tools.ietf.org/html/rfc6797#section-6.1.2">Section 6.1.2</a>
* for additional details.
* </p>
* @param preload true to include preload, else false
* @since 5.2.0
*/
public void setPreload(boolean preload) {
this.preload = preload;
updateHstsHeaderValue();
}
private void updateHstsHeaderValue() {
String headerValue = "max-age=" + this.maxAgeInSeconds;
if (this.includeSubDomains) {
headerValue += " ; includeSubDomains";
}
if (this.preload) {
headerValue += " ; preload";
} | this.hstsHeaderValue = headerValue;
}
private static final class SecureRequestMatcher implements RequestMatcher {
@Override
public boolean matches(HttpServletRequest request) {
return request.isSecure();
}
@Override
public String toString() {
return "Is Secure";
}
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\header\writers\HstsHeaderWriter.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class DataEntryField
{
DataEntryFieldId id;
ITranslatableString caption;
ITranslatableString description;
FieldType type;
boolean mandatory;
boolean availableInApi;
/** empty, unless type=list */
ImmutableList<DataEntryListValue> listValues;
@Builder
private DataEntryField(
@NonNull final DataEntryFieldId id,
@NonNull final ITranslatableString caption,
@NonNull final ITranslatableString description,
@NonNull final FieldType type,
final boolean mandatory, | final boolean availableInApi,
@Singular final List<DataEntryListValue> listValues)
{
this.id = id;
this.caption = caption;
this.description = description;
this.type = type;
this.mandatory = mandatory;
this.availableInApi = availableInApi;
this.listValues = ImmutableList.copyOf(listValues);
}
public Optional<DataEntryListValue> getFirstListValueMatching(@NonNull final Predicate<DataEntryListValue> predicate)
{
return listValues.stream()
.filter(predicate)
.findFirst();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\layout\DataEntryField.java | 2 |
请在Spring Boot框架中完成以下Java代码 | private Set<String> getSuccessors(DirectedAcyclicGraph<String, DefaultEdge> dag, String vertex) {
// get outgoingEdges
Set<DefaultEdge> outgoingEdges = dag.outgoingEdgesOf(vertex);
// find the next node
return outgoingEdges.stream()
.map(edge -> dag.getEdgeTarget(edge))
.collect(Collectors.toSet());
}
// init beans by layer
private void initializeBeansInLayers(List<Set<String>> layers, ConfigurableListableBeanFactory beanFactory) {
for (Set<String> layer : layers) {
// Beans of the same layer can be initialized in parallel
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (String beanName : layer) {
// only load beans that wrote by yourself
if (shouldLoadBean(beanName)) {
CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
try {
beanFactory.getBean(beanName); // init Bean
} catch (Exception e) {
System.err.println("Failed to initialize bean: " + beanName);
e.printStackTrace();
} | }, executorService);
futures.add(future);
}
}
//Wait for all beans in the current layer to be initialized before initializing the next layer.
CompletableFuture<Void> allOf = CompletableFuture.allOf(futures.toArray(new CompletableFuture[0]));
allOf.join(); // make sure to be done on current layer
}
}
private boolean shouldLoadBean(String beanName) {
return beanName.startsWith("helloWorldController")
||beanName.startsWith("serviceOne")
||beanName.startsWith("serviceTwo")
||beanName.startsWith("serviceThree");
}
} | repos\springboot-demo-master\dag\src\main\java\com\et\config\DAGBeanInitializer.java | 2 |
请完成以下Java代码 | public void setMessage(String message) {
this.message = message;
}
/**
* Sets the 编号 ,返回自身的引用.
*
* @param code
* the new 编号
*
* @return the wrapper
*/
public Wrapper<T> code(int code) {
this.setCode(code);
return this;
}
/**
* Sets the 信息 ,返回自身的引用.
*
* @param message
* the new 信息
*
* @return the wrapper
*/
public Wrapper<T> message(String message) {
this.setMessage(message);
return this;
} | /**
* Sets the 结果数据 ,返回自身的引用.
*
* @param result
* the new 结果数据
*
* @return the wrapper
*/
public Wrapper<T> result(T result) {
this.setData(result);
return this;
}
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
} | repos\spring-boot-student-master\spring-boot-student-validated\src\main\java\com\xiaolyuh\wrapper\Wrapper.java | 1 |
请完成以下Java代码 | public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getTaskId() {
return taskId;
}
public void setTaskId(String taskId) {
this.taskId = taskId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getContentId() {
return contentId;
} | public void setContentId(String contentId) {
this.contentId = contentId;
}
public ByteArrayEntity getContent() {
return content;
}
public void setContent(ByteArrayEntity content) {
this.content = content;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public Date getTime() {
return time;
}
public void setTime(Date time) {
this.time = time;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\AttachmentEntityImpl.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public boolean isEmpty()
{
return getMap().isEmpty();
}
@Override
public boolean containsKey(final Object key)
{
return getMap().containsKey(key);
}
@Override
public boolean containsValue(final Object value)
{
return getMap().containsValue(value);
}
@Override
public String get(final Object key)
{
return getMap().get(key);
}
@Override
public String put(final String key, final String value)
{
throw new UnsupportedOperationException();
}
@Override
public String remove(final Object key)
{
throw new UnsupportedOperationException();
}
@Override
public void putAll(final Map<? extends String, ? extends String> m)
{
throw new UnsupportedOperationException();
} | @Override
public void clear()
{
throw new UnsupportedOperationException();
}
@Override
public Set<String> keySet()
{
return getMap().keySet();
}
@Override
public Collection<String> values()
{
return getMap().values();
}
@Override
public Set<java.util.Map.Entry<String, String>> entrySet()
{
return getMap().entrySet();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\xls\engine\ResourceBundleMapWrapper.java | 2 |
请完成以下Java代码 | public class JwtBearerGrantRequest extends AbstractOAuth2AuthorizationGrantRequest {
private final Jwt jwt;
/**
* Constructs a {@code JwtBearerGrantRequest} using the provided parameters.
* @param clientRegistration the client registration
* @param jwt the JWT assertion
*/
public JwtBearerGrantRequest(ClientRegistration clientRegistration, Jwt jwt) {
super(AuthorizationGrantType.JWT_BEARER, clientRegistration);
Assert.isTrue(AuthorizationGrantType.JWT_BEARER.equals(clientRegistration.getAuthorizationGrantType()),
"clientRegistration.authorizationGrantType must be AuthorizationGrantType.JWT_BEARER");
Assert.notNull(jwt, "jwt cannot be null");
this.jwt = jwt;
}
/**
* Returns the {@link Jwt JWT} assertion.
* @return the {@link Jwt} assertion
*/
public Jwt getJwt() {
return this.jwt;
}
/** | * Populate default parameters for the JWT Bearer Grant.
* @param grantRequest the authorization grant request
* @return a {@link MultiValueMap} of the parameters used in the OAuth 2.0 Access
* Token Request body
*/
static MultiValueMap<String, String> defaultParameters(JwtBearerGrantRequest grantRequest) {
ClientRegistration clientRegistration = grantRequest.getClientRegistration();
MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>();
if (!CollectionUtils.isEmpty(clientRegistration.getScopes())) {
parameters.set(OAuth2ParameterNames.SCOPE,
StringUtils.collectionToDelimitedString(clientRegistration.getScopes(), " "));
}
parameters.set(OAuth2ParameterNames.ASSERTION, grantRequest.getJwt().getTokenValue());
return parameters;
}
} | repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\endpoint\JwtBearerGrantRequest.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class StoredProcedure1 {
private static final Logger log = LoggerFactory.getLogger(StoredProcedure1.class);
@Autowired
@Qualifier("jdbcBookRepository")
private BookRepository bookRepository;
@Autowired
private JdbcTemplate jdbcTemplate;
private SimpleJdbcCall simpleJdbcCall;
// init SimpleJdbcCall
@PostConstruct
void init() {
// o_name and O_NAME, same
jdbcTemplate.setResultsMapCaseInsensitive(true);
simpleJdbcCall = new SimpleJdbcCall(jdbcTemplate)
.withProcedureName("get_book_by_id");
}
private static final String SQL_STORED_PROC = ""
+ " CREATE OR REPLACE PROCEDURE get_book_by_id "
+ " ("
+ " p_id IN BOOKS.ID%TYPE,"
+ " o_name OUT BOOKS.NAME%TYPE,"
+ " o_price OUT BOOKS.PRICE%TYPE"
+ " ) AS"
+ " BEGIN"
+ " SELECT NAME, PRICE INTO o_name, o_price from BOOKS WHERE ID = p_id;"
+ " END;";
public void start() {
log.info("Creating Store Procedures and Function...");
jdbcTemplate.execute(SQL_STORED_PROC);
/* Test Stored Procedure */
Book book = findById(2L).orElseThrow(IllegalArgumentException::new);
// Book{id=2, name='Mkyong in Java', price=1.99}
System.out.println(book);
}
Optional<Book> findById(Long id) { | SqlParameterSource in = new MapSqlParameterSource()
.addValue("p_id", id);
Optional result = Optional.empty();
try {
Map out = simpleJdbcCall.execute(in);
if (out != null) {
Book book = new Book();
book.setId(id);
book.setName((String) out.get("O_NAME"));
book.setPrice((BigDecimal) out.get("O_PRICE"));
result = Optional.of(book);
}
} catch (Exception e) {
// ORA-01403: no data found, or any java.sql.SQLException
System.err.println(e.getMessage());
}
return result;
}
} | repos\spring-boot-master\spring-jdbc\src\main\java\com\mkyong\sp\StoredProcedure1.java | 2 |
请完成以下Java代码 | public static DatabaseDriver fromJdbcUrl(@Nullable String url) {
if (StringUtils.hasLength(url)) {
Assert.isTrue(url.startsWith("jdbc"), "'url' must start with \"jdbc\"");
String urlWithoutPrefix = url.substring("jdbc".length()).toLowerCase(Locale.ENGLISH);
for (DatabaseDriver driver : values()) {
for (String urlPrefix : driver.getUrlPrefixes()) {
String prefix = ":" + urlPrefix + ":";
if (driver != UNKNOWN && urlWithoutPrefix.startsWith(prefix)) {
return driver;
}
}
}
}
return UNKNOWN;
}
/** | * Find a {@link DatabaseDriver} for the given product name.
* @param productName product name
* @return the database driver or {@link #UNKNOWN} if not found
*/
public static DatabaseDriver fromProductName(@Nullable String productName) {
if (StringUtils.hasLength(productName)) {
for (DatabaseDriver candidate : values()) {
if (candidate.matchProductName(productName)) {
return candidate;
}
}
}
return UNKNOWN;
}
} | repos\spring-boot-4.0.1\module\spring-boot-jdbc\src\main\java\org\springframework\boot\jdbc\DatabaseDriver.java | 1 |
请完成以下Java代码 | private void checkInvoiceBPartnerCombination(final ImportRecordsSelection selection)
{
final StringBuilder sql = new StringBuilder("UPDATE I_BankStatement "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'Err=Invalid Invoice<->BPartner, ' "
+ "WHERE I_BankStatement_ID IN "
+ "(SELECT I_BankStatement_ID "
+ "FROM I_BankStatement i"
+ " INNER JOIN C_Invoice v ON (i.C_Invoice_ID=v.C_Invoice_ID) "
+ "WHERE i.C_BPartner_ID IS NOT NULL "
+ " AND v.C_BPartner_ID IS NOT NULL "
+ " AND v.C_BPartner_ID<>i.C_BPartner_ID) ")
.append(selection.toSqlWhereClause());
DB.executeUpdateAndThrowExceptionOnFail(sql.toString(), ITrx.TRXNAME_ThreadInherited);
}
private void detectDuplicates(final ImportRecordsSelection selection)
{
final StringBuilder sql = new StringBuilder("SELECT i.I_BankStatement_ID, l.C_BankStatementLine_ID, i.EftTrxID "
+ "FROM I_BankStatement i, C_BankStatement s, C_BankStatementLine l "
+ "WHERE i.I_isImported='N' "
+ "AND s.C_BankStatement_ID=l.C_BankStatement_ID "
+ "AND i.EftTrxID IS NOT NULL AND "
// Concatenate EFT Info
+ "(l.EftTrxID||l.EftAmt||l.EftStatementLineDate||l.EftValutaDate||l.EftTrxType||l.EftCurrency||l.EftReference||s.EftStatementReference "
+ "||l.EftCheckNo||l.EftMemo||l.EftPayee||l.EftPayeeAccount) "
+ "= "
+ "(i.EftTrxID||i.EftAmt||i.EftStatementLineDate||i.EftValutaDate||i.EftTrxType||i.EftCurrency||i.EftReference||i.EftStatementReference "
+ "||i.EftCheckNo||i.EftMemo||i.EftPayee||i.EftPayeeAccount) ");
final StringBuilder updateSql = new StringBuilder("UPDATE I_Bankstatement "
+ "SET I_IsImported='E', I_ErrorMsg=I_ErrorMsg||'Err=Duplicate['||?||']' "
+ "WHERE I_BankStatement_ID=?")
.append(selection.toSqlWhereClause());
PreparedStatement pupdt = DB.prepareStatement(updateSql.toString(), ITrx.TRXNAME_ThreadInherited);
PreparedStatement pstmtDuplicates = null;
int no = 0;
try
{ | pstmtDuplicates = DB.prepareStatement(sql.toString(), ITrx.TRXNAME_ThreadInherited);
ResultSet rs = pstmtDuplicates.executeQuery();
while (rs.next())
{
String info = "Line_ID=" + rs.getInt(2) // l.C_BankStatementLine_ID
+ ",EDTTrxID=" + rs.getString(3); // i.EftTrxID
pupdt.setString(1, info);
pupdt.setInt(2, rs.getInt(1)); // i.I_BankStatement_ID
pupdt.executeUpdate();
no++;
}
rs.close();
pstmtDuplicates.close();
pupdt.close();
rs = null;
pstmtDuplicates = null;
pupdt = null;
}
catch (Exception e)
{
logger.error("DetectDuplicates {}", e.getMessage());
}
logger.warn("Duplicates= {}", no);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\impexp\BankStatementImportTableSqlUpdater.java | 1 |
请完成以下Java代码 | public int getAD_Role_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public org.compiere.model.I_AD_User getAD_User() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class);
}
@Override
public void setAD_User(org.compiere.model.I_AD_User AD_User)
{
set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User);
}
/** Set Ansprechpartner.
@param AD_User_ID
User within the system - Internal or Business Partner Contact
*/
@Override
public void setAD_User_ID (int AD_User_ID)
{
if (AD_User_ID < 0)
set_ValueNoCheck (COLUMNNAME_AD_User_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID));
}
/** Get Ansprechpartner.
@return User within the system - Internal or Business Partner Contact
*/
@Override
public int getAD_User_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set AD_User_Roles. | @param AD_User_Roles_ID AD_User_Roles */
@Override
public void setAD_User_Roles_ID (int AD_User_Roles_ID)
{
if (AD_User_Roles_ID < 1)
set_ValueNoCheck (COLUMNNAME_AD_User_Roles_ID, null);
else
set_ValueNoCheck (COLUMNNAME_AD_User_Roles_ID, Integer.valueOf(AD_User_Roles_ID));
}
/** Get AD_User_Roles.
@return AD_User_Roles */
@Override
public int getAD_User_Roles_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_Roles_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_User_Roles.java | 1 |
请完成以下Java代码 | public int hashCode() {
int result = 0;
result = 31 * result + (itemSubjectRef.getStructureRef() != null ? itemSubjectRef.getStructureRef().hashCode() : 0);
result = 31 * result + (id != null ? id.hashCode() : 0);
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (value != null ? value.hashCode() : 0);
return result;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
} | ValuedDataObject otherObject = (ValuedDataObject) o;
if (!otherObject.getItemSubjectRef().getStructureRef().equals(this.itemSubjectRef.getStructureRef())) {
return false;
}
if (!otherObject.getId().equals(this.id)) {
return false;
}
if (!otherObject.getName().equals(this.name)) {
return false;
}
return otherObject.getValue().equals(this.value.toString());
}
} | repos\flowable-engine-main\modules\flowable-bpmn-model\src\main\java\org\flowable\bpmn\model\ValuedDataObject.java | 1 |
请完成以下Java代码 | default @Nullable MessageConverter getMessageConverter() {
return null;
}
/**
* Get the task executor to use for this endpoint's listener container.
* Overrides any executor set on the container factory.
* @return the executor.
* @since 2.2
*/
default @Nullable TaskExecutor getTaskExecutor() {
return null;
}
/**
* Called by the container factory with the factory's batchListener property.
* @param batchListener the batchListener to set.
* @since 2.2
*/
default void setBatchListener(boolean batchListener) {
}
/**
* Whether this endpoint is for a batch listener.
* @return {@link Boolean#TRUE} if batch.
* @since 3.0
*/
@Nullable
Boolean getBatchListener();
/**
* Set a {@link BatchingStrategy} to use when debatching messages.
* @param batchingStrategy the batching strategy.
* @since 2.2
* @see #setBatchListener(boolean)
*/
default void setBatchingStrategy(BatchingStrategy batchingStrategy) {
}
/**
* Return this endpoint's batching strategy, or null.
* @return the strategy.
* @since 2.4.7
*/
default @Nullable BatchingStrategy getBatchingStrategy() {
return null;
}
/**
* Override the container factory's {@link AcknowledgeMode}.
* @return the acknowledgment mode.
* @since 2.2
*/
default @Nullable AcknowledgeMode getAckMode() {
return null;
}
/**
* Return a {@link ReplyPostProcessor} to post process a reply message before it is
* sent. | * @return the post processor.
* @since 2.2.5
*/
default @Nullable ReplyPostProcessor getReplyPostProcessor() {
return null;
}
/**
* Get the reply content type.
* @return the content type.
* @since 2.3
*/
default @Nullable String getReplyContentType() {
return null;
}
/**
* Return whether the content type set by a converter prevails or not.
* @return false to always apply the reply content type.
* @since 2.3
*/
default boolean isConverterWinsContentType() {
return true;
}
} | repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\RabbitListenerEndpoint.java | 1 |
请完成以下Java代码 | public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() { | return age;
}
public void setAge(int age) {
this.age = age;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
} | repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\persistence\model\Person.java | 1 |
请完成以下Java代码 | private static Optional<Quantity> computeQtyIssued(final @NonNull ImmutableList<RawMaterialsIssueStep> steps)
{
return steps.stream()
.map(RawMaterialsIssueStep::getIssued)
.filter(Objects::nonNull)
.map(PPOrderIssueSchedule.Issued::getQtyIssued)
.reduce(Quantity::add);
}
private static WFActivityStatus computeStatus(
final @NonNull Quantity qtyToIssue,
final @NonNull Quantity qtyIssued,
final @NonNull ImmutableList<RawMaterialsIssueStep> steps)
{
if (qtyIssued.isZero())
{
return WFActivityStatus.NOT_STARTED;
}
else if (qtyToIssue.compareTo(qtyIssued) <= 0
|| steps.stream().allMatch(RawMaterialsIssueStep::isIssued))
{
return WFActivityStatus.COMPLETED;
}
else
{
return WFActivityStatus.IN_PROGRESS;
}
}
public Optional<Quantity> getQtyToIssueMin()
{
return issuingToleranceSpec != null
? Optional.of(issuingToleranceSpec.subtractFrom(qtyToIssue))
: Optional.empty();
}
public Optional<Quantity> getQtyToIssueMax()
{
return issuingToleranceSpec != null
? Optional.of(issuingToleranceSpec.addTo(qtyToIssue))
: Optional.empty();
}
public RawMaterialsIssueLine withChangedRawMaterialsIssueStep(
@NonNull final PPOrderIssueScheduleId issueScheduleId,
@NonNull UnaryOperator<RawMaterialsIssueStep> mapper)
{
final ImmutableList<RawMaterialsIssueStep> stepsNew = CollectionUtils.map(
steps,
step -> PPOrderIssueScheduleId.equals(step.getId(), issueScheduleId) ? mapper.apply(step) : step);
return withSteps(stepsNew);
}
@NonNull
public RawMaterialsIssueLine withSteps(final ImmutableList<RawMaterialsIssueStep> stepsNew)
{ | return !Objects.equals(this.steps, stepsNew)
? toBuilder().steps(stepsNew).build()
: this;
}
public boolean containsRawMaterialsIssueStep(final PPOrderIssueScheduleId issueScheduleId)
{
return steps.stream().anyMatch(step -> PPOrderIssueScheduleId.equals(step.getId(), issueScheduleId));
}
@NonNull
public ITranslatableString getProductValueAndProductName()
{
final TranslatableStringBuilder message = TranslatableStrings.builder()
.append(getProductValue())
.append(" ")
.append(getProductName());
return message.build();
}
@NonNull
public Quantity getQtyLeftToIssue()
{
return qtyToIssue.subtract(qtyIssued);
}
public boolean isAllowManualIssue()
{
return !issueMethod.isIssueOnlyForReceived();
}
public boolean isIssueOnlyForReceived() {return issueMethod.isIssueOnlyForReceived();}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\model\RawMaterialsIssueLine.java | 1 |
请完成以下Java代码 | public void setLastname (final @Nullable java.lang.String Lastname)
{
set_Value (COLUMNNAME_Lastname, Lastname);
}
@Override
public java.lang.String getLastname()
{
return get_ValueAsString(COLUMNNAME_Lastname);
}
@Override
public void setPhone (final @Nullable java.lang.String Phone)
{
set_Value (COLUMNNAME_Phone, Phone);
}
@Override
public java.lang.String getPhone()
{
return get_ValueAsString(COLUMNNAME_Phone);
}
@Override
public void setPhone2 (final @Nullable java.lang.String Phone2)
{
set_Value (COLUMNNAME_Phone2, Phone2);
}
@Override
public java.lang.String getPhone2()
{ | return get_ValueAsString(COLUMNNAME_Phone2);
}
@Override
public void setTitle (final @Nullable java.lang.String Title)
{
set_Value (COLUMNNAME_Title, Title);
}
@Override
public java.lang.String getTitle()
{
return get_ValueAsString(COLUMNNAME_Title);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Contact_QuickInput.java | 1 |
请完成以下Java代码 | public String getProcessMsg()
{
return m_processMsg;
} // getProcessMsg
/**
* Get Document Owner (Responsible)
*
* @return AD_User_ID (Created)
*/
@Override
public int getDoc_User_ID()
{
return getCreatedBy();
} // getDoc_User_ID
/**
* Get Document Approval Amount
*
* @return DR amount
*/
@Override
public BigDecimal getApprovalAmt()
{
return getTotalDr();
} // getApprovalAmt
/**
* Document Status is Complete or Closed
*
* @return true if CO, CL or RE
*/
@Deprecated | public boolean isComplete()
{
return Services.get(IGLJournalBL.class).isComplete(this);
} // isComplete
// metas: cg: 02476
private static void setAmtPrecision(final I_GL_Journal journal)
{
final AcctSchemaId acctSchemaId = AcctSchemaId.ofRepoIdOrNull(journal.getC_AcctSchema_ID());
if (acctSchemaId == null)
{
return;
}
final AcctSchema as = Services.get(IAcctSchemaDAO.class).getById(acctSchemaId);
final CurrencyPrecision precision = as.getStandardPrecision();
final BigDecimal controlAmt = precision.roundIfNeeded(journal.getControlAmt());
journal.setControlAmt(controlAmt);
}
} // MJournal | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\model\MJournal.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Step step2() {
return new StepBuilder("job1step2", jobRepository).<String, String> chunk(3, transactionManager)
.reader(new ListItemReader<>(Arrays.asList("7", "2", "3", "10", "5", "6")))
.processor(new ItemProcessor<String, String>() {
@Override
public String process(String item) throws Exception {
LOGGER.info("Processing of chunks");
return String.valueOf(Integer.parseInt(item) * -1);
}
})
.writer(new ItemWriter<String>() {
@Override
public void write(Chunk<? extends String> items) throws Exception {
for (String item : items) {
LOGGER.info(">> " + item);
}
}
})
.build();
} | @Bean
public Job job2(Step job2step1) {
return new JobBuilder("job2", jobRepository).incrementer(new RunIdIncrementer())
.start(job2step1)
.build();
}
@Bean
public Step job2step1() {
return new StepBuilder("job2step1", jobRepository).tasklet(new Tasklet() {
@Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
LOGGER.info("This job is from Baeldung");
return RepeatStatus.FINISHED;
}
}, transactionManager)
.build();
}
} | repos\tutorials-master\spring-cloud-modules\spring-cloud-task\springcloudtaskbatch\src\main\java\com\baeldung\task\JobConfiguration.java | 2 |
请完成以下Java代码 | public Map<String, Collection<ITableRecordReference>> getTableName2Record()
{
final Map<String, Collection<ITableRecordReference>> result = new HashMap<>();
tableName2Record.entrySet().forEach(e -> {
result.put(e.getKey(), e.getValue());
});
return result;
}
@Override
public int size()
{
return size;
}
@Override
public boolean isQueueEmpty()
{
final boolean iteratorEmpty = !iterator.hasNext();
return iteratorEmpty && queueItemsToProcess.isEmpty();
}
@Override
public ITableRecordReference nextFromQueue()
{
final WorkQueue result = nextFromQueue0();
if (result.getDLM_Partition_Workqueue_ID() > 0)
{
queueItemsToDelete.add(result);
}
return result.getTableRecordReference();
}
private WorkQueue nextFromQueue0()
{
if (iterator.hasNext())
{
// once we get the record from the queue, we also add it to our result
final WorkQueue next = iterator.next();
final ITableRecordReference tableRecordReference = next.getTableRecordReference();
final IDLMAware model = tableRecordReference.getModel(ctxAware, IDLMAware.class);
add0(tableRecordReference, model.getDLM_Partition_ID(), true);
return next;
}
return queueItemsToProcess.removeFirst();
}
@Override
public List<WorkQueue> getQueueRecordsToStore()
{
return queueItemsToProcess;
} | @Override
public List<WorkQueue> getQueueRecordsToDelete()
{
return queueItemsToDelete;
}
/**
* @return the {@link Partition} from the last invokation of {@link #clearAfterPartitionStored(Partition)}, or an empty partition.
*/
@Override
public Partition getPartition()
{
return partition;
}
@Override
public void registerHandler(IIterateResultHandler handler)
{
handlerSupport.registerListener(handler);
}
@Override
public List<IIterateResultHandler> getRegisteredHandlers()
{
return handlerSupport.getRegisteredHandlers();
}
@Override
public boolean isHandlerSignaledToStop()
{
return handlerSupport.isHandlerSignaledToStop();
}
@Override
public String toString()
{
return "IterateResult [queueItemsToProcess.size()=" + queueItemsToProcess.size()
+ ", queueItemsToDelete.size()=" + queueItemsToDelete.size()
+ ", size=" + size
+ ", tableName2Record.size()=" + tableName2Record.size()
+ ", dlmPartitionId2Record.size()=" + dlmPartitionId2Record.size()
+ ", iterator=" + iterator
+ ", ctxAware=" + ctxAware
+ ", partition=" + partition + "]";
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\CreatePartitionIterateResult.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class WebSocketConfig extends AbstractWebSocketMessageBrokerConfigurer {
/**
* Register Stomp endpoints: the url to open the WebSocket connection.
*/
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
// Register the "/ws" endpoint, enabling the SockJS protocol.
// SockJS is used (both client and server side) to allow alternative
// messaging options if WebSocket is not available.
registry.addEndpoint("/ws").withSockJS();
return;
}
// /** | // * Configure the message broker.
// */
// @Override
// public void configureMessageBroker(MessageBrokerRegistry config) {
//
// // Enable a simple memory-based message broker to send messages to the
// // client on destinations prefixed with "/queue".
// // Simple message broker handles subscription requests from clients, stores
// // them in memory, and broadcasts messages to connected clients with
// // matching destinations.
// config.enableSimpleBroker("/queue");
//
// return;
// }
} // class WebSocketConfig | repos\spring-boot-samples-master\spring-boot-web-socket-user-notifications\src\main\java\netgloo\configs\WebSocketConfig.java | 2 |
请完成以下Java代码 | public boolean isNewOrChange()
{
return isNew() || isChange();
}
public boolean isChangeOrDelete()
{
return isChange() || isDelete();
}
public boolean isDelete()
{
return this == BEFORE_DELETE || this == AFTER_DELETE;
}
public boolean isBefore()
{
return this == BEFORE_NEW
|| this == BEFORE_CHANGE
|| this == BEFORE_DELETE
|| this == BEFORE_DELETE_REPLICATION
|| this == BEFORE_SAVE_TRX;
}
public boolean isAfter()
{
return this == AFTER_NEW
|| this == AFTER_NEW_REPLICATION | || this == AFTER_CHANGE
|| this == AFTER_CHANGE_REPLICATION
|| this == AFTER_DELETE;
}
public boolean isBeforeSaveTrx()
{
return this == BEFORE_SAVE_TRX;
}
public static boolean isBeforeSaveTrx(final TimingType timingType)
{
return timingType instanceof ModelChangeType
? ((ModelChangeType)timingType).isBeforeSaveTrx()
: false;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\modelvalidator\ModelChangeType.java | 1 |
请完成以下Java代码 | public void deleteBPartnerLocations(@NonNull final I_C_BPartner bpartner)
{
int deleteCount = 0;
deleteCount = queryBL.createQueryBuilder(I_C_BPartner_Location.class)
.addEqualsFilter(I_C_BPartner_Location.COLUMNNAME_C_BPartner_ID, bpartner.getC_BPartner_ID())
.create()
.delete();
logger.info("Deleted {} C_BPartner_Location records", deleteCount);
deleteCount = queryBL.createQueryBuilder(I_C_BPartner_Product.class)
.addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_C_BPartner_ID, bpartner.getC_BPartner_ID())
.create()
.delete();
logger.info("Deleted {} C_BPartner_Product records", deleteCount);
deleteCount = queryBL.createQueryBuilder(I_C_BPartner_CreditLimit.class)
.addEqualsFilter(I_C_BPartner_CreditLimit.COLUMNNAME_C_BPartner_ID, bpartner.getC_BPartner_ID())
.create()
.delete();
logger.info("Deleted {} C_BPartner_CreditLimit records", deleteCount);
deleteCount = queryBL.createQueryBuilder(I_C_BPartner_Product_Stats.class)
.addEqualsFilter(I_C_BPartner_Product_Stats.COLUMNNAME_C_BPartner_ID, bpartner.getC_BPartner_ID())
.create()
.delete();
logger.info("Deleted {} C_BPartner_Product_Stats records", deleteCount);
deleteCount = queryBL.createQueryBuilder(I_C_BPartner_Stats.class)
.addEqualsFilter(I_C_BPartner_Stats.COLUMNNAME_C_BPartner_ID, bpartner.getC_BPartner_ID())
.create()
.delete();
logger.info("Deleted {} C_BPartner_Stats records", deleteCount);
deleteCount = queryBL.createQueryBuilder(I_C_BP_BankAccount.class)
.addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID, bpartner.getC_BPartner_ID())
.create()
.delete();
logger.info("Deleted {} C_BP_BankAccount records", deleteCount); | deleteCount = queryBL.createQueryBuilder(I_C_BP_PrintFormat.class)
.addEqualsFilter(I_C_BP_PrintFormat.COLUMNNAME_C_BPartner_ID, bpartner.getC_BPartner_ID())
.create()
.delete();
logger.info("Deleted {} C_BP_PrintFormat records", deleteCount);
deleteCount = queryBL.createQueryBuilder(I_C_BP_Withholding.class)
.addEqualsFilter(I_C_BP_Withholding.COLUMNNAME_C_BPartner_ID, bpartner.getC_BPartner_ID())
.create()
.delete();
logger.info("Deleted {} C_BP_Withholding records", deleteCount);
deleteCount = queryBL.createQueryBuilder(I_AD_User.class)
.addEqualsFilter(I_AD_User.COLUMNNAME_C_BPartner_ID, bpartner.getC_BPartner_ID())
.create()
.delete();
logger.info("Deleted {} AD_User records", deleteCount);
}
@ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = { I_C_BPartner.COLUMNNAME_C_BPartner_SalesRep_ID, I_C_BPartner.COLUMNNAME_C_BPartner_ID })
public void validateSalesRep(final I_C_BPartner partner)
{
final BPartnerId bPartnerId = BPartnerId.ofRepoId(partner.getC_BPartner_ID());
final BPartnerId salesRepId = BPartnerId.ofRepoIdOrNull(partner.getC_BPartner_SalesRep_ID());
bPartnerBL.validateSalesRep(bPartnerId, salesRepId);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\model\interceptor\C_BPartner.java | 1 |
请完成以下Java代码 | public static class RequestOptions {
private NoCacheStrategy noCacheStrategy = NoCacheStrategy.SKIP_UPDATE_CACHE_ENTRY;
public NoCacheStrategy getNoCacheStrategy() {
return noCacheStrategy;
}
public void setNoCacheStrategy(NoCacheStrategy noCacheStrategy) {
this.noCacheStrategy = noCacheStrategy;
}
@Override
public String toString() {
return "RequestOptions{" + "noCacheStrategy=" + noCacheStrategy + '}';
}
}
/**
* When client sends "no-cache" directive in "Cache-Control" header, the response
* should be re-validated from upstream. There are several strategies that indicates | * what to do with the new fresh response.
*/
public enum NoCacheStrategy {
/**
* Update the cache entry by the fresh response coming from upstream with a new
* time to live.
*/
UPDATE_CACHE_ENTRY,
/**
* Skip the update. The client will receive the fresh response, other clients will
* receive the old entry in cache.
*/
SKIP_UPDATE_CACHE_ENTRY
}
} | repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\LocalResponseCacheProperties.java | 1 |
请完成以下Java代码 | public void markEnded(String deleteReason) {
if (this.endTime == null) {
this.deleteReason = deleteReason;
this.endTime = Context.getProcessEngineConfiguration().getClock().getCurrentTime();
this.durationInMillis = endTime.getTime() - startTime.getTime();
}
}
// getters and setters ////////////////////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public Date getStartTime() {
return startTime;
}
public Date getEndTime() {
return endTime;
}
public Long getDurationInMillis() {
return durationInMillis;
} | public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public void setStartTime(Date startTime) {
this.startTime = startTime;
}
public void setEndTime(Date endTime) {
this.endTime = endTime;
}
public void setDurationInMillis(Long durationInMillis) {
this.durationInMillis = durationInMillis;
}
public String getDeleteReason() {
return deleteReason;
}
public void setDeleteReason(String deleteReason) {
this.deleteReason = deleteReason;
}
} | repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricScopeInstanceEntityImpl.java | 1 |
请完成以下Java代码 | public int getRecord_ID()
{
return sched.getM_ShipmentSchedule_ID();
}
@Override
public ZonedDateTime getDeliveryDate()
{
return shipmentScheduleDeliveryDayBL.getDeliveryDateCurrent(sched);
}
@Override
public BPartnerLocationId getBPartnerLocationId()
{
return shipmentScheduleEffectiveBL.getBPartnerLocationId(sched);
}
@Override
public int getM_Product_ID()
{ | return sched.getM_Product_ID();
}
@Override
public boolean isToBeFetched()
{
// Shipment Schedules are about sending materials to customer
return false;
}
@Override
public int getAD_Org_ID()
{
return sched.getAD_Org_ID();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\ShipmentScheduleDeliveryDayAllocable.java | 1 |
请完成以下Java代码 | public void recordEntityLinkCreated(EntityLinkEntity entityLink) {
for (HistoryManager historyManager : historyManagers) {
historyManager.recordEntityLinkCreated(entityLink);
}
}
@Override
public void recordEntityLinkDeleted(EntityLinkEntity entityLink) {
for (HistoryManager historyManager : historyManagers) {
historyManager.recordEntityLinkDeleted(entityLink);
}
}
@Override
public void updateProcessBusinessKeyInHistory(ExecutionEntity processInstance) {
for (HistoryManager historyManager : historyManagers) {
historyManager.updateProcessBusinessKeyInHistory(processInstance);
}
}
@Override
public void updateProcessBusinessStatusInHistory(ExecutionEntity processInstance) {
for (HistoryManager historyManager : historyManagers) {
historyManager.updateProcessBusinessStatusInHistory(processInstance);
}
}
@Override
public void updateProcessDefinitionIdInHistory(ProcessDefinitionEntity processDefinitionEntity, ExecutionEntity processInstance) {
for (HistoryManager historyManager : historyManagers) {
historyManager.updateProcessDefinitionIdInHistory(processDefinitionEntity, processInstance);
}
}
@Override
public void updateActivity(ExecutionEntity executionEntity, String oldActivityId, FlowElement newFlowElement, TaskEntity task, Date updateTime) {
for (HistoryManager historyManager : historyManagers) {
historyManager.updateActivity(executionEntity, oldActivityId, newFlowElement, task, updateTime);
}
}
@Override
public void updateHistoricActivityInstance(ActivityInstance activityInstance) {
for (HistoryManager historyManager : historyManagers) {
historyManager.updateHistoricActivityInstance(activityInstance); | }
}
@Override
public void createHistoricActivityInstance(ActivityInstance activityInstance) {
for (HistoryManager historyManager : historyManagers) {
historyManager.createHistoricActivityInstance(activityInstance);
}
}
@Override
public void recordHistoricUserTaskLogEntry(HistoricTaskLogEntryBuilder taskLogEntryBuilder) {
for (HistoryManager historyManager : historyManagers) {
historyManager.recordHistoricUserTaskLogEntry(taskLogEntryBuilder);
}
}
@Override
public void deleteHistoryUserTaskLog(long logNumber) {
for (HistoryManager historyManager : historyManagers) {
historyManager.deleteHistoryUserTaskLog(logNumber);
}
}
public void addHistoryManager(HistoryManager historyManager) {
historyManagers.add(historyManager);
}
} | repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\history\CompositeHistoryManager.java | 1 |
请完成以下Java代码 | public class UserAddDTO {
/**
* 账号
*/
private String username;
/**
* 密码
*/
private String password;
public String getUsername() {
return username;
} | public UserAddDTO setUsername(String username) {
this.username = username;
return this;
}
public String getPassword() {
return password;
}
public UserAddDTO setPassword(String password) {
this.password = password;
return this;
}
} | repos\SpringBoot-Labs-master\lab-23\lab-springmvc-23-01\src\main\java\cn\iocoder\springboot\lab23\springmvc\dto\UserAddDTO.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public void setTaskId(String taskId) {
this.taskId = taskId;
}
public Date getTimeStamp() {
return timeStamp;
}
public void setTimeStamp(Date timeStamp) {
this.timeStamp = timeStamp;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getData() {
return data;
}
public void setData(String data) {
this.data = data;
}
public String getExecutionId() {
return executionId;
}
public void setExecutionId(String executionId) {
this.executionId = executionId;
}
public String getProcessInstanceId() {
return processInstanceId;
}
public void setProcessInstanceId(String processInstanceId) {
this.processInstanceId = processInstanceId;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public void setProcessDefinitionId(String processDefinitionId) {
this.processDefinitionId = processDefinitionId;
}
public String getScopeId() {
return scopeId;
}
public void setScopeId(String scopeId) {
this.scopeId = scopeId;
}
public String getScopeDefinitionId() {
return scopeDefinitionId;
} | public void setScopeDefinitionId(String scopeDefinitionId) {
this.scopeDefinitionId = scopeDefinitionId;
}
public String getSubScopeId() {
return subScopeId;
}
public void setSubScopeId(String subScopeId) {
this.subScopeId = subScopeId;
}
public String getScopeType() {
return scopeType;
}
public void setScopeType(String scopeType) {
this.scopeType = scopeType;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
} | repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskLogEntryResponse.java | 2 |
请完成以下Java代码 | private PPOrderCost createZeroPPOrderCost(
final PPOrderCostCandidate candidate,
final CostElementId costElementId,
final CurrencyId currencyId)
{
final PPOrderCostTrxType trxType = candidate.getTrxType();
final CostSegmentAndElement costSegmentAndElement = candidate.getCostSegment().withCostElementId(costElementId);
final Percent coProductCostDistributionPercent = candidate.getCoProductCostDistributionPercent();
final I_C_UOM uom = uomDAO.getById(candidate.getUomId());
return PPOrderCost.builder()
.trxType(trxType)
.coProductCostDistributionPercent(coProductCostDistributionPercent)
.costSegmentAndElement(costSegmentAndElement)
.price(CostPrice.zero(currencyId, candidate.getUomId()))
.accumulatedQty(Quantity.zero(uom))
.build();
}
private Set<CostingMethod> getCostingMethodsWhichRequiredBOMRollup() | {
return ImmutableSet.of(
CostingMethod.AverageInvoice,
CostingMethod.AveragePO);
}
@Value
@Builder
private static class PPOrderCostCandidate
{
@NonNull
CostSegment costSegment;
@NonNull
PPOrderCostTrxType trxType;
@Nullable
Percent coProductCostDistributionPercent;
@NonNull
UomId uomId;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\impl\CreatePPOrderCostsCommand.java | 1 |
请完成以下Java代码 | public void setPriceStd (java.math.BigDecimal PriceStd)
{
set_ValueNoCheck (COLUMNNAME_PriceStd, PriceStd);
}
/** Get Standardpreis.
@return Standardpreis
*/
@Override
public java.math.BigDecimal getPriceStd ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PriceStd);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Produktname.
@param ProductName
Name des Produktes
*/
@Override
public void setProductName (java.lang.String ProductName)
{
set_ValueNoCheck (COLUMNNAME_ProductName, ProductName);
}
/** Get Produktname.
@return Name des Produktes
*/
@Override
public java.lang.String getProductName ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductName);
}
/** Set Produktschlüssel.
@param ProductValue
Schlüssel des Produktes
*/
@Override
public void setProductValue (java.lang.String ProductValue)
{ | set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue);
}
/** Get Produktschlüssel.
@return Schlüssel des Produktes
*/
@Override
public java.lang.String getProductValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_ProductValue);
}
/** Set Reihenfolge.
@param SeqNo
Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public void setSeqNo (java.lang.String SeqNo)
{
set_ValueNoCheck (COLUMNNAME_SeqNo, SeqNo);
}
/** Get Reihenfolge.
@return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst
*/
@Override
public java.lang.String getSeqNo ()
{
return (java.lang.String)get_Value(COLUMNNAME_SeqNo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java-gen\de\metas\fresh\model\X_M_PriceList_V.java | 1 |
请完成以下Java代码 | public class IteratorGuide {
public static void main(String[] args) {
List<String> items = new ArrayList<>();
items.add("ONE");
items.add("TWO");
items.add("THREE");
Iterator<String> iter = items.iterator();
while (iter.hasNext()) {
String next = iter.next();
System.out.println(next);
iter.remove();
}
ListIterator<String> listIterator = items.listIterator();
while(listIterator.hasNext()) {
String nextWithIndex = items.get(listIterator.nextIndex());
String next = listIterator.next(); | if( "ONE".equals(next)) {
listIterator.set("SWAPPED");
}
}
listIterator.add("FOUR");
while(listIterator.hasPrevious()) {
String previousWithIndex = items.get(listIterator.previousIndex());
String previous = listIterator.previous();
System.out.println(previous);
}
listIterator.forEachRemaining(e -> {
System.out.println(e);
});
}
} | repos\tutorials-master\core-java-modules\core-java-collections-2\src\main\java\com\baeldung\iteratorguide\IteratorGuide.java | 1 |
请完成以下Java代码 | public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context)
{
if (context.isNoSelection())
{
return ProcessPreconditionsResolution.accept();
}
if (!context.isSingleSelection())
{
return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection();
}
return ProcessPreconditionsResolution.accept();
}
// services
private final transient IHUEmptiesService huEmptiesService = Services.get(IHUEmptiesService.class);
private final DocumentCollection documentsRepo = SpringContextHolder.instance.getBean(DocumentCollection.class);
private final String _returnMovementType;
private final AdWindowId _targetWindowId;
public WEBUI_M_ReceiptSchedule_CreateEmptiesReturns_Base(@NonNull final String returnMovementType, @NonNull final AdWindowId targetWindowId)
{
Check.assumeNotEmpty(returnMovementType, "returnMovementType is not empty");
_returnMovementType = returnMovementType;
_targetWindowId = targetWindowId;
}
private String getReturnMovementType()
{
return _returnMovementType;
}
private AdWindowId getTargetWindowId()
{
return _targetWindowId;
}
@Override
protected String doIt() throws Exception | {
final I_M_ReceiptSchedule receiptSchedule = getProcessInfo().getRecordIfApplies(I_M_ReceiptSchedule.class, ITrx.TRXNAME_ThreadInherited).orElse(null);
final int emptiesInOutId;
if (receiptSchedule == null)
{
emptiesInOutId = createDraftEmptiesDocument();
}
else
{
final I_M_InOut emptiesInOut = huEmptiesService.createDraftEmptiesInOutFromReceiptSchedule(receiptSchedule, getReturnMovementType());
emptiesInOutId = emptiesInOut == null ? -1 : emptiesInOut.getM_InOut_ID();
}
//
// Notify frontend that the empties document shall be opened in single document layout (not grid)
if (emptiesInOutId > 0)
{
getResult().setRecordToOpen(TableRecordReference.of(I_M_InOut.Table_Name, emptiesInOutId), getTargetWindowId(), OpenTarget.SingleDocument);
}
return MSG_OK;
}
private int createDraftEmptiesDocument()
{
final DocumentPath documentPath = DocumentPath.builder()
.setDocumentType(WindowId.of(getTargetWindowId()))
.setDocumentId(DocumentId.NEW_ID_STRING)
.allowNewDocumentId()
.build();
final DocumentId documentId = documentsRepo.forDocumentWritable(documentPath, NullDocumentChangesCollector.instance, document -> {
huEmptiesService.newReturnsInOutProducer(getCtx())
.setMovementType(getReturnMovementType())
.setMovementDate(de.metas.common.util.time.SystemTime.asDayTimestamp())
.fillReturnsInOutHeader(InterfaceWrapperHelper.create(document, I_M_InOut.class));
return document.getDocumentId();
});
return documentId.toInt();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_ReceiptSchedule_CreateEmptiesReturns_Base.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public Map<String, Object> convertDataToObjects(Map<String, String> data) {
Map<String, Object> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, String> entry : data.entrySet()) {
results.put(entry.getKey(), entry.getValue());
}
}
return results;
}
/**
* Internal conversion. This method will allow to save additional data.
* By default, it will save the object as string
*
* @param data the data to convert
* @return a map of String, String
*/ | public Map<String, String> convertDataToStrings(Map<String, Object> data) {
Map<String, String> results = new HashMap<>();
if (data != null) {
for (Map.Entry<String, Object> entry : data.entrySet()) {
// Extract the data that will be saved.
if (entry.getValue() instanceof WebAuthenticationDetails) {
WebAuthenticationDetails authenticationDetails = (WebAuthenticationDetails) entry.getValue();
results.put("remoteAddress", authenticationDetails.getRemoteAddress());
results.put("sessionId", authenticationDetails.getSessionId());
} else {
results.put(entry.getKey(), Objects.toString(entry.getValue()));
}
}
}
return results;
}
} | repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\config\audit\AuditEventConverter.java | 2 |
请完成以下Java代码 | public void run() {
running = true;
consume();
}
public void stop() {
running = false;
}
public void consume() {
while (running) {
if (dataQueue.isEmpty()) {
try {
dataQueue.waitIsNotEmpty();
} catch (InterruptedException e) {
log.severe("Error while waiting to Consume messages.");
break;
}
}
// avoid spurious wake-up
if (!running) {
break;
} | Message message = dataQueue.poll();
useMessage(message);
//Sleeping on random time to make it realistic
ThreadUtil.sleep((long) (Math.random() * 100));
}
log.info("Consumer Stopped");
}
private void useMessage(Message message) {
if (message != null) {
log.info(String.format("[%s] Consuming Message. Id: %d, Data: %f%n",
Thread.currentThread().getName(), message.getId(), message.getData()));
}
}
} | repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-7\src\main\java\com\baeldung\producerconsumer\Consumer.java | 1 |
请完成以下Java代码 | private BOMPrices calculateBOMLinePrice(final I_PP_Product_BOMLine bomLine)
{
final ProductId bomLineProductId = ProductId.ofRepoId(bomLine.getM_Product_ID());
final I_M_ProductPrice productPrice = ProductPrices.retrieveMainProductPriceOrNull(priceListVersion, bomLineProductId);
if (productPrice == null)
{
throw ProductNotOnPriceListException.builder()
.productId(bomLineProductId)
.build();
}
final BigDecimal qty = getBOMQty(bomLine);
return BOMPrices.builder()
.priceStd(productPrice.getPriceStd())
.priceList(productPrice.getPriceList())
.priceLimit(productPrice.getPriceLimit())
.build()
.multiply(qty);
}
private BigDecimal getBOMQty(final I_PP_Product_BOMLine bomLine)
{
if (bomLine.getQty_Attribute_ID() > 0)
{
final AttributeId attributeId = AttributeId.ofRepoId(bomLine.getQty_Attribute_ID());
final String attributeCode = attributesRepo.getAttributeCodeById(attributeId);
final BigDecimal qty = getAttributeValueAsBigDecimal(attributeCode, null);
if (qty != null)
{
return qty;
}
}
final BigDecimal qty = bomsBL.computeQtyMultiplier(bomLine, bomProductId);
return qty;
}
private BigDecimal getAttributeValueAsBigDecimal(final String attributeCode, final BigDecimal defaultValue)
{
if (asiAware == null)
{
return defaultValue;
}
final AttributeSetInstanceId asiId = AttributeSetInstanceId.ofRepoIdOrNull(asiAware.getM_AttributeSetInstance_ID());
if (asiId == null)
{
return defaultValue;
}
final ImmutableAttributeSet asi = asiBL.getImmutableAttributeSetById(asiId);
if (!asi.hasAttribute(attributeCode))
{
return defaultValue;
}
final BigDecimal value = asi.getValueAsBigDecimal(attributeCode);
return value != null ? value : defaultValue;
} | private List<I_PP_Product_BOMLine> getBOMLines()
{
final I_PP_Product_BOM bom = getBOMIfEligible();
if (bom == null)
{
return ImmutableList.of();
}
return bomsRepo.retrieveLines(bom);
}
private I_PP_Product_BOM getBOMIfEligible()
{
final I_M_Product bomProduct = productsRepo.getById(bomProductId);
if (!bomProduct.isBOM())
{
return null;
}
return bomsRepo.getDefaultBOMByProductId(bomProductId)
.filter(this::isEligible)
.orElse(null);
}
private boolean isEligible(final I_PP_Product_BOM bom)
{
final BOMType bomType = BOMType.ofNullableCode(bom.getBOMType());
return BOMType.MakeToOrder.equals(bomType);
}
//
//
// ---
//
//
public static class BOMPriceCalculatorBuilder
{
public Optional<BOMPrices> calculate()
{
return build().calculate();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\rules\price_list_version\BOMPriceCalculator.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public CommonResult<CommonPage<PmsBrand>> getList(@RequestParam(value = "keyword", required = false) String keyword,
@RequestParam(value = "showStatus",required = false) Integer showStatus,
@RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
@RequestParam(value = "pageSize", defaultValue = "5") Integer pageSize) {
List<PmsBrand> brandList = brandService.listBrand(keyword,showStatus,pageNum, pageSize);
return CommonResult.success(CommonPage.restPage(brandList));
}
@ApiOperation(value = "根据编号查询品牌信息")
@RequestMapping(value = "/{id}", method = RequestMethod.GET)
@ResponseBody
public CommonResult<PmsBrand> getItem(@PathVariable("id") Long id) {
return CommonResult.success(brandService.getBrand(id));
}
@ApiOperation(value = "批量删除品牌")
@RequestMapping(value = "/delete/batch", method = RequestMethod.POST)
@ResponseBody
public CommonResult deleteBatch(@RequestParam("ids") List<Long> ids) {
int count = brandService.deleteBrand(ids);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
} | @ApiOperation(value = "批量更新显示状态")
@RequestMapping(value = "/update/showStatus", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateShowStatus(@RequestParam("ids") List<Long> ids,
@RequestParam("showStatus") Integer showStatus) {
int count = brandService.updateShowStatus(ids, showStatus);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
@ApiOperation(value = "批量更新厂家制造商状态")
@RequestMapping(value = "/update/factoryStatus", method = RequestMethod.POST)
@ResponseBody
public CommonResult updateFactoryStatus(@RequestParam("ids") List<Long> ids,
@RequestParam("factoryStatus") Integer factoryStatus) {
int count = brandService.updateFactoryStatus(ids, factoryStatus);
if (count > 0) {
return CommonResult.success(count);
} else {
return CommonResult.failed();
}
}
} | repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\PmsBrandController.java | 2 |
请完成以下Java代码 | private Supplier<SecurityContext> defaultWithAnonymous(HttpServletRequest request,
Supplier<SecurityContext> currentDeferredContext) {
return SingletonSupplier.of(() -> {
SecurityContext currentContext = currentDeferredContext.get();
return defaultWithAnonymous(request, currentContext);
});
}
private SecurityContext defaultWithAnonymous(HttpServletRequest request, SecurityContext currentContext) {
Authentication currentAuthentication = currentContext.getAuthentication();
if (currentAuthentication == null) {
Authentication anonymous = createAuthentication(request);
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.of(() -> "Set SecurityContextHolder to " + anonymous));
}
else {
this.logger.debug("Set SecurityContextHolder to anonymous SecurityContext");
}
SecurityContext anonymousContext = this.securityContextHolderStrategy.createEmptyContext();
anonymousContext.setAuthentication(anonymous);
return anonymousContext;
}
else {
if (this.logger.isTraceEnabled()) {
this.logger.trace(LogMessage.of(() -> "Did not set SecurityContextHolder since already authenticated "
+ currentAuthentication));
}
}
return currentContext;
}
protected Authentication createAuthentication(HttpServletRequest request) {
AnonymousAuthenticationToken token = new AnonymousAuthenticationToken(this.key, this.principal,
this.authorities);
token.setDetails(this.authenticationDetailsSource.buildDetails(request));
return token;
} | public void setAuthenticationDetailsSource(
AuthenticationDetailsSource<HttpServletRequest, ?> authenticationDetailsSource) {
Assert.notNull(authenticationDetailsSource, "AuthenticationDetailsSource required");
this.authenticationDetailsSource = authenticationDetailsSource;
}
/**
* Sets the {@link SecurityContextHolderStrategy} to use. The default action is to use
* the {@link SecurityContextHolderStrategy} stored in {@link SecurityContextHolder}.
*
* @since 5.8
*/
public void setSecurityContextHolderStrategy(SecurityContextHolderStrategy securityContextHolderStrategy) {
Assert.notNull(securityContextHolderStrategy, "securityContextHolderStrategy cannot be null");
this.securityContextHolderStrategy = securityContextHolderStrategy;
}
public Object getPrincipal() {
return this.principal;
}
public List<GrantedAuthority> getAuthorities() {
return this.authorities;
}
} | repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\AnonymousAuthenticationFilter.java | 1 |
请完成以下Java代码 | public int getRecord_ID()
{
return get_ValueAsInt(COLUMNNAME_Record_ID);
}
@Override
public void setTextMsg (final java.lang.String TextMsg)
{
set_Value (COLUMNNAME_TextMsg, TextMsg);
}
@Override
public java.lang.String getTextMsg()
{
return get_ValueAsString(COLUMNNAME_TextMsg);
}
@Override
public void setWF_Initial_User_ID (final int WF_Initial_User_ID)
{
if (WF_Initial_User_ID < 1)
set_Value (COLUMNNAME_WF_Initial_User_ID, null);
else
set_Value (COLUMNNAME_WF_Initial_User_ID, WF_Initial_User_ID);
}
@Override
public int getWF_Initial_User_ID()
{
return get_ValueAsInt(COLUMNNAME_WF_Initial_User_ID); | }
/**
* WFState AD_Reference_ID=305
* Reference name: WF_Instance State
*/
public static final int WFSTATE_AD_Reference_ID=305;
/** NotStarted = ON */
public static final String WFSTATE_NotStarted = "ON";
/** Running = OR */
public static final String WFSTATE_Running = "OR";
/** Suspended = OS */
public static final String WFSTATE_Suspended = "OS";
/** Completed = CC */
public static final String WFSTATE_Completed = "CC";
/** Aborted = CA */
public static final String WFSTATE_Aborted = "CA";
/** Terminated = CT */
public static final String WFSTATE_Terminated = "CT";
@Override
public void setWFState (final java.lang.String WFState)
{
set_Value (COLUMNNAME_WFState, WFState);
}
@Override
public java.lang.String getWFState()
{
return get_ValueAsString(COLUMNNAME_WFState);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WF_Process.java | 1 |
请完成以下Java代码 | private static ServiceRegistry configureServiceRegistry() throws IOException {
Properties properties = getHibernateProperties();
return new StandardServiceRegistryBuilder().applySettings(properties).build();
}
private static Properties getHibernateProperties() throws IOException {
Properties properties = new Properties();
URL propertiesURL = Thread.currentThread().getContextClassLoader().getResource("hibernate-lifecycle.properties");
try (FileInputStream inputStream = new FileInputStream(propertiesURL.getFile())) {
properties.load(inputStream);
}
return properties;
}
public static List<EntityEntry> getManagedEntities(Session session) {
Map.Entry<Object, EntityEntry>[] entries = ((SessionImplementor) session).getPersistenceContext().reentrantSafeEntityEntries();
return Arrays.stream(entries).map(e -> e.getValue()).collect(Collectors.toList()); | }
public static Transaction startTransaction(Session s) {
Transaction tx = s.getTransaction();
tx.begin();
return tx;
}
public static int queryCount(String query) throws Exception {
try (ResultSet rs = connection.createStatement().executeQuery(query)) {
rs.next();
return rs.getInt(1);
}
}
} | repos\tutorials-master\persistence-modules\hibernate5\src\main\java\com\baeldung\hibernate\lifecycle\HibernateLifecycleUtil.java | 1 |
请完成以下Java代码 | public String toString()
{
return MoreObjects.toStringHelper(this)
.addValue(callouts)
.toString();
}
@Override
public void stateChange(final StateChangeEvent event)
{
final GridTab gridTab = event.getSource();
final StateChangeEventType eventType = event.getEventType();
switch (eventType)
{
case DATA_REFRESH_ALL:
callouts.onRefreshAll(gridTab);
break;
case DATA_REFRESH:
callouts.onRefresh(gridTab);
break;
case DATA_NEW: | callouts.onNew(gridTab);
break;
case DATA_DELETE:
callouts.onDelete(gridTab);
break;
case DATA_SAVE:
callouts.onSave(gridTab);
break;
case DATA_IGNORE:
callouts.onIgnore(gridTab);
break;
default:
// tolerate all other events, event if they are meaningless for us
// throw new AdempiereException("EventType " + eventType + " is not supported");
break;
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\GridTabCalloutStateChangeListener.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class RedisOtaPackageDataCache implements OtaPackageDataCache {
private final RedisConnectionFactory redisConnectionFactory;
@Override
public byte[] get(String key) {
return get(key, 0, 0);
}
@Override
public byte[] get(String key, int chunkSize, int chunk) {
try (RedisConnection connection = redisConnectionFactory.getConnection()) {
if (chunkSize == 0) {
return connection.get(toOtaPackageCacheKey(key));
}
int startIndex = chunkSize * chunk;
int endIndex = startIndex + chunkSize - 1;
return connection.getRange(toOtaPackageCacheKey(key), startIndex, endIndex);
}
}
@Override | public void put(String key, byte[] value) {
try (RedisConnection connection = redisConnectionFactory.getConnection()) {
connection.set(toOtaPackageCacheKey(key), value);
}
}
@Override
public void evict(String key) {
try (RedisConnection connection = redisConnectionFactory.getConnection()) {
connection.del(toOtaPackageCacheKey(key));
}
}
private byte[] toOtaPackageCacheKey(String key) {
return String.format("%s::%s", OTA_PACKAGE_DATA_CACHE, key).getBytes();
}
} | repos\thingsboard-master\common\cache\src\main\java\org\thingsboard\server\cache\ota\RedisOtaPackageDataCache.java | 2 |
请完成以下Java代码 | public void setUserID (java.lang.String UserID)
{
set_Value (COLUMNNAME_UserID, UserID);
}
/** Get User ID.
@return User ID or account number
*/
@Override
public java.lang.String getUserID ()
{
return (java.lang.String)get_Value(COLUMNNAME_UserID);
}
/** Set Vendor ID.
@param VendorID | Vendor ID for the Payment Processor
*/
@Override
public void setVendorID (java.lang.String VendorID)
{
set_Value (COLUMNNAME_VendorID, VendorID);
}
/** Get Vendor ID.
@return Vendor ID for the Payment Processor
*/
@Override
public java.lang.String getVendorID ()
{
return (java.lang.String)get_Value(COLUMNNAME_VendorID);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentProcessor.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public QRCodePDFResource createPDF(@NonNull final List<PrintableQRCode> qrCodes)
{
return createPDF(qrCodes, null, default_qrCodeProcessId);
}
public QRCodePDFResource createPDF(@NonNull final List<PrintableQRCode> qrCodes,
@Nullable final PInstanceId pInstanceId,
@Nullable final AdProcessId qrCodeProcessId)
{
return CreatePDFCommand.builder()
.qrCodes(qrCodes)
.pInstanceId(pInstanceId)
.qrCodeProcessId(qrCodeProcessId != null ? qrCodeProcessId : default_qrCodeProcessId)
.build()
.execute();
} | public void print(@NonNull final QRCodePDFResource pdf)
{
print(pdf, PrintCopies.ONE);
}
public void print(@NonNull final QRCodePDFResource pdf, @NonNull final PrintCopies copies)
{
final TableRecordReference recordRef = TableRecordReference.of(I_AD_PInstance.Table_Name, pdf.getPinstanceId().getRepoId());
final ArchiveInfo archiveInfo = new ArchiveInfo(pdf.getFilename(), recordRef);
archiveInfo.setProcessId(pdf.getProcessId());
archiveInfo.setPInstanceId(pdf.getPinstanceId());
archiveInfo.setCopies(copies);
massPrintingService.print(pdf, archiveInfo);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.global_qrcode.services\src\main\java\de\metas\global_qrcodes\service\GlobalQRCodeService.java | 2 |
请完成以下Java代码 | public Profile getProfile() {
return this.profile;
}
public List<Post> getPosts() {
return this.posts;
}
public List<Group> getGroups() {
return this.groups;
}
public void setId(Long id) {
this.id = id;
}
public void setUsername(String username) {
this.username = username;
}
public void setEmail(String email) {
this.email = email;
}
public void setProfile(Profile profile) {
this.profile = profile;
}
public void setPosts(List<Post> posts) {
this.posts = posts;
}
public void setGroups(List<Group> groups) {
this.groups = groups;
}
@Override
public boolean equals(Object o) {
if (this == o) {
return true;
} | if (o == null || getClass() != o.getClass()) {
return false;
}
User user = (User) o;
return Objects.equals(id, user.id);
}
@Override
public int hashCode() {
return id != null ? id.hashCode() : 0;
}
public String toString() {
return "User(id=" + this.getId() + ", username=" + this.getUsername() + ", email=" + this.getEmail() + ", profile="
+ this.getProfile() + ", posts=" + this.getPosts() + ", groups=" + this.getGroups() + ")";
}
} | repos\tutorials-master\persistence-modules\spring-boot-persistence-4\src\main\java\com\baeldung\listvsset\eager\list\fulldomain\User.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public @Nullable Map<String, String> getParameters() {
return this.parameters;
}
public void setParameters(@Nullable Map<String, String> parameters) {
this.parameters = parameters;
}
public @Nullable File getRollbackFile() {
return this.rollbackFile;
}
public void setRollbackFile(@Nullable File rollbackFile) {
this.rollbackFile = rollbackFile;
}
public boolean isTestRollbackOnUpdate() {
return this.testRollbackOnUpdate;
}
public void setTestRollbackOnUpdate(boolean testRollbackOnUpdate) {
this.testRollbackOnUpdate = testRollbackOnUpdate;
}
public @Nullable String getTag() {
return this.tag;
}
public void setTag(@Nullable String tag) {
this.tag = tag;
}
public @Nullable ShowSummary getShowSummary() {
return this.showSummary;
}
public void setShowSummary(@Nullable ShowSummary showSummary) {
this.showSummary = showSummary;
}
public @Nullable ShowSummaryOutput getShowSummaryOutput() {
return this.showSummaryOutput;
}
public void setShowSummaryOutput(@Nullable ShowSummaryOutput showSummaryOutput) {
this.showSummaryOutput = showSummaryOutput;
}
public @Nullable UiService getUiService() {
return this.uiService;
}
public void setUiService(@Nullable UiService uiService) {
this.uiService = uiService;
}
public @Nullable Boolean getAnalyticsEnabled() {
return this.analyticsEnabled;
}
public void setAnalyticsEnabled(@Nullable Boolean analyticsEnabled) {
this.analyticsEnabled = analyticsEnabled;
}
public @Nullable String getLicenseKey() {
return this.licenseKey;
}
public void setLicenseKey(@Nullable String licenseKey) {
this.licenseKey = licenseKey;
}
/**
* Enumeration of types of summary to show. Values are the same as those on
* {@link UpdateSummaryEnum}. To maximize backwards compatibility, the Liquibase enum
* is not used directly.
*/
public enum ShowSummary {
/**
* Do not show a summary.
*/
OFF,
/**
* Show a summary.
*/
SUMMARY,
/**
* Show a verbose summary.
*/ | VERBOSE
}
/**
* Enumeration of destinations to which the summary should be output. Values are the
* same as those on {@link UpdateSummaryOutputEnum}. To maximize backwards
* compatibility, the Liquibase enum is not used directly.
*/
public enum ShowSummaryOutput {
/**
* Log the summary.
*/
LOG,
/**
* Output the summary to the console.
*/
CONSOLE,
/**
* Log the summary and output it to the console.
*/
ALL
}
/**
* Enumeration of types of UIService. Values are the same as those on
* {@link UIServiceEnum}. To maximize backwards compatibility, the Liquibase enum is
* not used directly.
*/
public enum UiService {
/**
* Console-based UIService.
*/
CONSOLE,
/**
* Logging-based UIService.
*/
LOGGER
}
} | repos\spring-boot-4.0.1\module\spring-boot-liquibase\src\main\java\org\springframework\boot\liquibase\autoconfigure\LiquibaseProperties.java | 2 |
请完成以下Java代码 | public int getNatureFrequency(String nature)
{
try
{
Nature pos = Nature.create(nature);
return getNatureFrequency(pos);
}
catch (IllegalArgumentException e)
{
return 0;
}
}
/**
* 获取词性的词频
*
* @param nature 词性
* @return 词频
*/
public int getNatureFrequency(final Nature nature)
{
int result = 0;
int i = 0;
for (Nature pos : this.nature)
{
if (nature == pos) | {
return frequency[i];
}
++i;
}
return result;
}
@Override
public String toString()
{
return "Attribute{" +
"nature=" + Arrays.toString(nature) +
", frequency=" + Arrays.toString(frequency) +
'}';
}
}
} | repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\EasyDictionary.java | 1 |
请完成以下Java代码 | public boolean isTransient() {
return isTransient;
}
public String getTenantId() {
return tenantId;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public Set<String> getReferencedEntityIds() {
Set<String> referencedEntityIds = new HashSet<>();
return referencedEntityIds;
}
@Override
public Map<String, Class> getReferencedEntitiesIdAndClass() {
Map<String, Class> referenceIdAndClass = new HashMap<>();
if (processInstanceId != null){
referenceIdAndClass.put(processInstanceId, ExecutionEntity.class);
}
if (executionId != null){
referenceIdAndClass.put(executionId, ExecutionEntity.class);
}
if (caseInstanceId != null){
referenceIdAndClass.put(caseInstanceId, CaseExecutionEntity.class);
}
if (caseExecutionId != null){
referenceIdAndClass.put(caseExecutionId, CaseExecutionEntity.class);
} | if (getByteArrayValueId() != null){
referenceIdAndClass.put(getByteArrayValueId(), ByteArrayEntity.class);
}
return referenceIdAndClass;
}
/**
*
* @return <code>true</code> <code>processDefinitionId</code> is introduced in 7.13,
* the check is used to created missing history at {@link LegacyBehavior#createMissingHistoricVariables(org.camunda.bpm.engine.impl.pvm.runtime.PvmExecutionImpl) LegacyBehavior#createMissingHistoricVariables}
*/
public boolean wasCreatedBefore713() {
return this.getProcessDefinitionId() == null;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\VariableInstanceEntity.java | 1 |
请完成以下Java代码 | public I_C_Invoice_Candidate getC_Invoice_Candidate()
{
return ic;
}
/** @return shipment/receipt line; could be <code>null</code> */
@Nullable
public I_M_InOutLine getM_InOutLine()
{
if (iciol == null)
{
return null;
}
return iciol.getM_InOutLine();
}
public StockQtyAndUOMQty getQtysAlreadyInvoiced()
{
final StockQtyAndUOMQty zero = StockQtyAndUOMQtys.createZero(productId, icUomId);
if (iciol == null)
{
return zero;
}
else
{
final InOutLineId inoutLineId = InOutLineId.ofRepoId(iciol.getM_InOutLine_ID());
return matchInvoiceService.getMaterialQtyMatched(inoutLineId, zero);
}
}
public StockQtyAndUOMQty getQtysAlreadyShipped()
{
final I_M_InOutLine inOutLine = getM_InOutLine();
if (inOutLine == null)
{
return StockQtyAndUOMQtys.createZero(productId, icUomId);
}
final InvoicableQtyBasedOn invoicableQtyBasedOn = InvoicableQtyBasedOn.ofNullableCodeOrNominal(ic.getInvoicableQtyBasedOn());
final BigDecimal uomQty;
if (!isNull(iciol, I_C_InvoiceCandidate_InOutLine.COLUMNNAME_QtyDeliveredInUOM_Override))
{
uomQty = iciol.getQtyDeliveredInUOM_Override();
}
else | {
switch (invoicableQtyBasedOn)
{
case CatchWeight:
uomQty = coalesceNotNull(iciol.getQtyDeliveredInUOM_Catch(), iciol.getQtyDeliveredInUOM_Nominal());
break;
case NominalWeight:
uomQty = iciol.getQtyDeliveredInUOM_Nominal();
break;
default:
throw fail("Unexpected invoicableQtyBasedOn={}", invoicableQtyBasedOn);
}
}
final Quantity shippedUomQuantityInIcUOM = uomConversionBL.convertQuantityTo(Quantitys.of(uomQty, UomId.ofRepoId(iciol.getC_UOM_ID())),
productId,
icUomId);
final BigDecimal stockQty = inOutLine.getMovementQty();
final StockQtyAndUOMQty deliveredQty = StockQtyAndUOMQtys
.create(
stockQty,
productId,
shippedUomQuantityInIcUOM.toBigDecimal(),
shippedUomQuantityInIcUOM.getUomId());
if (inOutBL.isReturnMovementType(inOutLine.getM_InOut().getMovementType()))
{
return deliveredQty.negate();
}
return deliveredQty;
}
public boolean isShipped()
{
return getM_InOutLine() != null;
}
public I_C_InvoiceCandidate_InOutLine getC_InvoiceCandidate_InOutLine()
{
return iciol;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\spi\impl\aggregator\standard\InvoiceCandidateWithInOutLine.java | 1 |
请完成以下Java代码 | public ClearingSystemIdentification2Choice getClrSysId() {
return clrSysId;
}
/**
* Sets the value of the clrSysId property.
*
* @param value
* allowed object is
* {@link ClearingSystemIdentification2Choice }
*
*/
public void setClrSysId(ClearingSystemIdentification2Choice value) {
this.clrSysId = value;
}
/**
* Gets the value of the mmbId property.
*
* @return
* possible object is
* {@link String }
* | */
public String getMmbId() {
return mmbId;
}
/**
* Sets the value of the mmbId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMmbId(String value) {
this.mmbId = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ClearingSystemMemberIdentification2.java | 1 |
请完成以下Java代码 | public ZonedDateTime getPreparationDate()
{
return order.getPreparationDate();
}
public OrgId getOrgId()
{
return orderLine.getOrgId();
}
public WarehouseId getWarehouseId()
{
return orderLine.getWarehouseId();
}
public int getLine()
{
return orderLine.getLine();
}
public ZonedDateTime getDatePromised()
{ | return orderLine.getDatePromised();
}
public ProductId getProductId()
{
return orderLine.getProductId();
}
public AttributeSetInstanceId getAsiId()
{
return orderLine.getAsiId();
}
public Quantity getOrderedQty()
{
return orderLine.getOrderedQty();
}
public ProductPrice getPriceActual()
{
return orderLine.getPriceActual();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\SalesOrderLine.java | 1 |
请完成以下Java代码 | public static <S, T> void addToMapOfLists(Map<S, List<T>> map, S key, T value) {
List<T> list = map.get(key);
if (list == null) {
list = new ArrayList<>();
map.put(key, list);
}
list.add(value);
}
public static <S, T> void mergeMapsOfLists(Map<S, List<T>> map, Map<S, List<T>> toAdd) {
for (Entry<S, List<T>> entry : toAdd.entrySet()) {
for (T listener : entry.getValue()) {
CollectionUtil.addToMapOfLists(map, entry.getKey(), listener);
}
}
}
public static <S, T> void addToMapOfSets(Map<S, Set<T>> map, S key, T value) {
Set<T> set = map.get(key);
if (set == null) {
set = new HashSet<>();
map.put(key, set);
}
set.add(value);
}
public static <S, T> void addCollectionToMapOfSets(Map<S, Set<T>> map, S key, Collection<T> values) {
Set<T> set = map.get(key);
if (set == null) {
set = new HashSet<>();
map.put(key, set);
}
set.addAll(values);
}
/**
* Chops a list into non-view sublists of length partitionSize. Note: the argument list
* may be included in the result.
*/
public static <T> List<List<T>> partition(List<T> list, final int partitionSize) {
List<List<T>> parts = new ArrayList<>(); | final int listSize = list.size();
if (listSize <= partitionSize) {
// no need for partitioning
parts.add(list);
} else {
for (int i = 0; i < listSize; i += partitionSize) {
parts.add(new ArrayList<>(list.subList(i, Math.min(listSize, i + partitionSize))));
}
}
return parts;
}
public static <T> List<T> collectInList(Iterator<T> iterator) {
List<T> result = new ArrayList<>();
while (iterator.hasNext()) {
result.add(iterator.next());
}
return result;
}
public static <T> T getLastElement(final Iterable<T> elements) {
T lastElement = null;
if (elements instanceof List) {
return ((List<T>) elements).get(((List<T>) elements).size() - 1);
}
for (T element : elements) {
lastElement = element;
}
return lastElement;
}
public static boolean isEmpty(Collection<?> collection) {
return collection == null || collection.isEmpty();
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\util\CollectionUtil.java | 1 |
请完成以下Java代码 | public void setPostingType (String PostingType)
{
set_Value (COLUMNNAME_PostingType, PostingType);
}
/** Get PostingType.
@return The type of posted amount for the transaction
*/
public String getPostingType ()
{
return (String)get_Value(COLUMNNAME_PostingType);
}
/** Set Relative Period.
@param RelativePeriod
Period offset (0 is current)
*/
public void setRelativePeriod (BigDecimal RelativePeriod)
{
set_Value (COLUMNNAME_RelativePeriod, RelativePeriod);
}
/** Get Relative Period.
@return Period offset (0 is current)
*/
public BigDecimal getRelativePeriod ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RelativePeriod);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 1.
@param UserElement1_ID
User defined accounting Element
*/
public void setUserElement1_ID (int UserElement1_ID)
{
if (UserElement1_ID < 1)
set_Value (COLUMNNAME_UserElement1_ID, null);
else
set_Value (COLUMNNAME_UserElement1_ID, Integer.valueOf(UserElement1_ID));
} | /** Get User Element 1.
@return User defined accounting Element
*/
public int getUserElement1_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement1_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set User Element 2.
@param UserElement2_ID
User defined accounting Element
*/
public void setUserElement2_ID (int UserElement2_ID)
{
if (UserElement2_ID < 1)
set_Value (COLUMNNAME_UserElement2_ID, null);
else
set_Value (COLUMNNAME_UserElement2_ID, Integer.valueOf(UserElement2_ID));
}
/** Get User Element 2.
@return User defined accounting Element
*/
public int getUserElement2_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_UserElement2_ID);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_ReportColumn.java | 1 |
请完成以下Java代码 | private static int forks(Map<String, String> parameters) {
String forks = parameters.remove("forks");
return parseOrDefault(forks, DEFAULT_FORKS);
}
private static int warmupIterations(Map<String, String> parameters) {
String warmups = parameters.remove("warmupIterations");
return parseOrDefault(warmups, DEFAULT_WARMUP_ITERATIONS);
}
private static int measurementIterations(Map<String, String> parameters) {
String measurements = parameters.remove("measurementIterations");
return parseOrDefault(measurements, DEFAULT_MEASUREMENT_ITERATIONS);
}
private static int parseOrDefault(String parameter, int defaultValue) {
return parameter != null ? Integer.parseInt(parameter) : defaultValue;
}
@Benchmark
public Object homemadeMatrixMultiplication(BigMatrixProvider matrixProvider) {
return HomemadeMatrix.multiplyMatrices(matrixProvider.getFirstMatrix(), matrixProvider.getSecondMatrix());
}
@Benchmark
public Object ejmlMatrixMultiplication(BigMatrixProvider matrixProvider) {
SimpleMatrix firstMatrix = new SimpleMatrix(matrixProvider.getFirstMatrix());
SimpleMatrix secondMatrix = new SimpleMatrix(matrixProvider.getSecondMatrix());
return firstMatrix.mult(secondMatrix);
}
@Benchmark
public Object apacheCommonsMatrixMultiplication(BigMatrixProvider matrixProvider) {
RealMatrix firstMatrix = new Array2DRowRealMatrix(matrixProvider.getFirstMatrix());
RealMatrix secondMatrix = new Array2DRowRealMatrix(matrixProvider.getSecondMatrix());
return firstMatrix.multiply(secondMatrix);
}
@Benchmark
public Object la4jMatrixMultiplication(BigMatrixProvider matrixProvider) {
Matrix firstMatrix = new Basic2DMatrix(matrixProvider.getFirstMatrix());
Matrix secondMatrix = new Basic2DMatrix(matrixProvider.getSecondMatrix()); | return firstMatrix.multiply(secondMatrix);
}
@Benchmark
public Object nd4jMatrixMultiplication(BigMatrixProvider matrixProvider) {
INDArray firstMatrix = Nd4j.create(matrixProvider.getFirstMatrix());
INDArray secondMatrix = Nd4j.create(matrixProvider.getSecondMatrix());
return firstMatrix.mmul(secondMatrix);
}
@Benchmark
public Object coltMatrixMultiplication(BigMatrixProvider matrixProvider) {
DoubleFactory2D doubleFactory2D = DoubleFactory2D.dense;
DoubleMatrix2D firstMatrix = doubleFactory2D.make(matrixProvider.getFirstMatrix());
DoubleMatrix2D secondMatrix = doubleFactory2D.make(matrixProvider.getSecondMatrix());
Algebra algebra = new Algebra();
return algebra.mult(firstMatrix, secondMatrix);
}
} | repos\tutorials-master\core-java-modules\core-java-lang-math-2\src\main\java\com\baeldung\matrices\benchmark\BigMatrixMultiplicationBenchmarking.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class SampleMapperApplication implements CommandLineRunner {
@Autowired
private UserMapper userMapper;
public static void main(String[] args) {
SpringApplication.run(SampleMapperApplication.class, args);
}
@Override
public void run(String... args) throws Exception {
PageHelper.startPage(1, 20).disableAsyncCount();
List<User> users = userMapper.findAll();
System.out.println("Total: " + ((Page) users).getTotal());
for (User user : users) {
System.out.println("Name: " + user.getName());
}
PageHelper.orderBy("id desc"); | users = userMapper.findAll();
System.out.println("Total: " + ((Page) users).getTotal());
for (User user : users) {
System.out.println("Name: " + user.getName());
}
PageRowBounds rowBounds = new PageRowBounds(3, 5);
users = userMapper.findAll(rowBounds);
System.out.println("Total: " + rowBounds.getTotal());
for (User user : users) {
System.out.println("Name: " + user.getName());
}
}
} | repos\pagehelper-spring-boot-master\pagehelper-spring-boot-samples\pagehelper-spring-boot-sample-annotation\src\main\java\tk\mybatis\pagehelper\SampleMapperApplication.java | 2 |
请完成以下Java代码 | private void notifyUserGroupAboutSupplierApprovalExpiration(@NonNull final I_C_BP_SupplierApproval supplierApprovalRecord)
{
final UserNotificationRequest.TargetRecordAction targetRecordAction = UserNotificationRequest
.TargetRecordAction
.of(I_C_BPartner.Table_Name, supplierApprovalRecord.getC_BPartner_ID());
final UserGroupId userGroupId = orgDAO.getSupplierApprovalExpirationNotifyUserGroupID(OrgId.ofRepoId(supplierApprovalRecord.getAD_Org_ID()));
if (userGroupId == null)
{
// nobody to notify
return;
}
final String partnerName = bpartnerDAO.getBPartnerNameById(BPartnerId.ofRepoId(supplierApprovalRecord.getC_BPartner_ID()));
final String supplierApprovalNorm = supplierApprovalRecord.getSupplierApproval_Norm();
final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(supplierApprovalRecord.getAD_Org_ID()));
final LocalDate expirationDate = TimeUtil.asLocalDate(supplierApprovalRecord.getSupplierApproval_Date(), timeZone)
.plusYears(getNumberOfYearsForApproval(supplierApprovalRecord)); | userGroupRepository
.getByUserGroupId(userGroupId)
.streamAssignmentsFor(userGroupId, Instant.now())
.map(UserGroupUserAssignment::getUserId)
.map(userId -> UserNotificationRequest.builder()
.recipientUserId(userId)
.contentADMessage(MSG_Partner_SupplierApproval_ExpirationDate)
.contentADMessageParam(partnerName)
.contentADMessageParam(supplierApprovalNorm)
.contentADMessageParam(expirationDate)
.targetAction(targetRecordAction)
.build())
.forEach(notificationBL::send);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\BPartnerSupplierApprovalService.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public String getMerchantOrderNo() {
return merchantOrderNo;
}
public void setMerchantOrderNo(String merchantOrderNo) {
this.merchantOrderNo = merchantOrderNo;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
} | public String getOrderDateBegin() {
return orderDateBegin;
}
public void setOrderDateBegin(String orderDateBegin) {
this.orderDateBegin = orderDateBegin;
}
public String getOrderDateEnd() {
return orderDateEnd;
}
public void setOrderDateEnd(String orderDateEnd) {
this.orderDateEnd = orderDateEnd;
}
} | repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\PaymentOrderQueryParam.java | 2 |
请完成以下Java代码 | public void deleteHistoricTaskInstanceById(String taskId) {
if (getHistoryManager().isHistoryEnabled()) {
HistoricTaskInstanceEntity historicTaskInstance = findHistoricTaskInstanceById(taskId);
if (historicTaskInstance != null) {
CommandContext commandContext = Context.getCommandContext();
List<HistoricTaskInstance> subTasks = findHistoricTasksByParentTaskId(taskId);
for (HistoricTaskInstance subTask : subTasks) {
deleteHistoricTaskInstanceById(subTask.getId());
}
commandContext
.getHistoricDetailEntityManager()
.deleteHistoricDetailsByTaskId(taskId);
commandContext
.getHistoricVariableInstanceEntityManager()
.deleteHistoricVariableInstancesByTaskId(taskId);
commandContext
.getCommentEntityManager()
.deleteCommentsByTaskId(taskId);
commandContext
.getAttachmentEntityManager()
.deleteAttachmentsByTaskId(taskId); | commandContext.getHistoricIdentityLinkEntityManager()
.deleteHistoricIdentityLinksByTaskId(taskId);
getDbSqlSession().delete(historicTaskInstance);
}
}
}
@SuppressWarnings("unchecked")
public List<HistoricTaskInstance> findHistoricTaskInstancesByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbSqlSession().selectListWithRawParameter("selectHistoricTaskInstanceByNativeQuery", parameterMap, firstResult, maxResults);
}
public long findHistoricTaskInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbSqlSession().selectOne("selectHistoricTaskInstanceCountByNativeQuery", parameterMap);
}
} | repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\HistoricTaskInstanceEntityManager.java | 1 |
请完成以下Java代码 | private static long getExpiresIn(Map<String, Object> tokenResponseParameters) {
return getParameterValue(tokenResponseParameters, OAuth2ParameterNames.EXPIRES_IN, 0L);
}
private static Set<String> getScopes(Map<String, Object> tokenResponseParameters) {
if (tokenResponseParameters.containsKey(OAuth2ParameterNames.SCOPE)) {
String scope = getParameterValue(tokenResponseParameters, OAuth2ParameterNames.SCOPE);
return new HashSet<>(Arrays.asList(StringUtils.delimitedListToStringArray(scope, " ")));
}
return Collections.emptySet();
}
private static String getParameterValue(Map<String, Object> tokenResponseParameters, String parameterName) {
Object obj = tokenResponseParameters.get(parameterName);
return (obj != null) ? obj.toString() : null;
}
private static long getParameterValue(Map<String, Object> tokenResponseParameters, String parameterName,
long defaultValue) {
long parameterValue = defaultValue;
Object obj = tokenResponseParameters.get(parameterName);
if (obj != null) {
// Final classes Long and Integer do not need to be coerced | if (obj.getClass() == Long.class) {
parameterValue = (Long) obj;
}
else if (obj.getClass() == Integer.class) {
parameterValue = (Integer) obj;
}
else {
// Attempt to coerce to a long (typically from a String)
try {
parameterValue = Long.parseLong(obj.toString());
}
catch (NumberFormatException ignored) {
}
}
}
return parameterValue;
}
} | repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\endpoint\DefaultMapOAuth2AccessTokenResponseConverter.java | 1 |
请完成以下Java代码 | public String getPlainContent() {
return plainContent;
}
public void setPlainContent(String plainContent) {
this.plainContent = plainContent;
}
public String getHtmlContent() {
return htmlContent;
}
public void setHtmlContent(String htmlContent) {
this.htmlContent = htmlContent;
}
public Charset getCharset() {
return charset;
}
public void setCharset(Charset charset) {
this.charset = charset;
}
public Collection<DataSource> getAttachments() {
return attachments;
}
public void setAttachments(Collection<DataSource> attachments) {
this.attachments = attachments;
} | public void addAttachment(DataSource attachment) {
if (attachments == null) {
attachments = new ArrayList<>();
}
attachments.add(attachment);
}
public Map<String, String> getHeaders() {
return headers;
}
public void setHeaders(Map<String, String> headers) {
this.headers = headers;
}
public void addHeader(String name, String value) {
if (headers == null) {
headers = new LinkedHashMap<>();
}
headers.put(name, value);
}
} | repos\flowable-engine-main\modules\flowable-mail\src\main\java\org\flowable\mail\common\api\MailMessage.java | 1 |
请完成以下Java代码 | public class MockedMinimalColumnInfoMap implements MinimalColumnInfoMap
{
private final HashMap<AdColumnId, MinimalColumnInfo> byId = new HashMap<>();
private final HashMap<AdTableIdAndColumnName, MinimalColumnInfo> byColumnName = new HashMap<>();
private final AtomicInteger nextAD_Column_ID = new AtomicInteger(801);
@Override
public @NonNull MinimalColumnInfo getById(@NonNull final AdColumnId adColumnId)
{
Adempiere.assertUnitTestMode();
final MinimalColumnInfo column = byId.get(adColumnId);
if (column == null)
{
throw new AdempiereException("No column found for " + adColumnId);
}
return column;
}
@Override
public ImmutableList<MinimalColumnInfo> getByIds(final Collection<AdColumnId> adColumnIds)
{
Adempiere.assertUnitTestMode();
if (adColumnIds.isEmpty())
{
return ImmutableList.of();
}
return adColumnIds.stream()
.distinct()
.map(byId::get)
.filter(Objects::nonNull)
.collect(ImmutableList.toImmutableList());
}
@Override
public ImmutableList<MinimalColumnInfo> getByColumnName(@NonNull final String columnName)
{
return byId.values()
.stream()
.filter(columnInfo -> columnInfo.isColumnNameMatching(columnName))
.collect(ImmutableList.toImmutableList());
} | @Nullable
@Override
public MinimalColumnInfo getByColumnNameOrNull(final AdTableId adTableId, final String columnName)
{
Adempiere.assertUnitTestMode();
final AdTableIdAndColumnName key = new AdTableIdAndColumnName(adTableId, columnName);
MinimalColumnInfo column = byColumnName.get(key);
if (column == null)
{
column = MinimalColumnInfo.builder()
.columnName(columnName)
.adColumnId(AdColumnId.ofRepoId(nextAD_Column_ID.getAndIncrement()))
.adTableId(adTableId)
.isActive(true)
.isParent(false)
.isGenericZoomOrigin(false)
.displayType(0) // unknown
.adReferenceValueId(null)
.adValRuleId(null)
.entityType("U")
.build();
byColumnName.put(key, column);
byId.put(column.getAdColumnId(), column);
}
return column;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\api\impl\MockedMinimalColumnInfoMap.java | 1 |
请完成以下Java代码 | public String getMsgId() {
return msgId;
}
/**
* Sets the value of the msgId property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setMsgId(String value) {
this.msgId = value;
}
/**
* Gets the value of the creDtTm property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getCreDtTm() {
return creDtTm;
}
/**
* Sets the value of the creDtTm property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setCreDtTm(XMLGregorianCalendar value) {
this.creDtTm = value;
}
/**
* Gets the value of the nbOfTxs property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getNbOfTxs() {
return nbOfTxs;
}
/**
* Sets the value of the nbOfTxs property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setNbOfTxs(String value) {
this.nbOfTxs = value;
}
/**
* Gets the value of the ctrlSum property.
*
* @return
* possible object is
* {@link BigDecimal }
*
*/
public BigDecimal getCtrlSum() {
return ctrlSum;
}
/**
* Sets the value of the ctrlSum property.
*
* @param value
* allowed object is
* {@link BigDecimal }
*
*/
public void setCtrlSum(BigDecimal value) { | this.ctrlSum = value;
}
/**
* Gets the value of the initgPty property.
*
* @return
* possible object is
* {@link PartyIdentification32CHNameAndId }
*
*/
public PartyIdentification32CHNameAndId getInitgPty() {
return initgPty;
}
/**
* Sets the value of the initgPty property.
*
* @param value
* allowed object is
* {@link PartyIdentification32CHNameAndId }
*
*/
public void setInitgPty(PartyIdentification32CHNameAndId value) {
this.initgPty = value;
}
/**
* Gets the value of the fwdgAgt property.
*
* @return
* possible object is
* {@link BranchAndFinancialInstitutionIdentification4 }
*
*/
public BranchAndFinancialInstitutionIdentification4 getFwdgAgt() {
return fwdgAgt;
}
/**
* Sets the value of the fwdgAgt property.
*
* @param value
* allowed object is
* {@link BranchAndFinancialInstitutionIdentification4 }
*
*/
public void setFwdgAgt(BranchAndFinancialInstitutionIdentification4 value) {
this.fwdgAgt = value;
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_001_01_03_ch_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_001_001_03_ch_02\GroupHeader32CH.java | 1 |
请完成以下Java代码 | private void executePointcut(@NonNull final ICalloutMethodPointcut pointcut, @NonNull final ICalloutExecutor executor, @NonNull final ICalloutField field)
{
// Skip executing this callout if we were asked to skip when record copying mode is active
if (pointcut.isSkipIfCopying() && field.isRecordCopyingMode())
{
logger.info("Skip invoking callout because we are in copying mode: {}", pointcut.getMethod());
return;
}
if (pointcut.isSkipIfIndirectlyCalled() && executor.getActiveCalloutInstancesCount() > 1)
{
logger.info("Skip invoking callout because it is called via another callout: {}", pointcut.getMethod());
return;
}
try
{
final Method method = pointcut.getMethod();
final Object model = field.getModel(pointcut.getModelClass());
// make sure the method can be executed
if (!method.isAccessible())
{
method.setAccessible(true);
} | if (pointcut.isParamCalloutFieldRequired())
{
method.invoke(annotatedObject, model, field);
}
else
{
method.invoke(annotatedObject, model);
}
}
catch (final CalloutExecutionException e)
{
throw e;
}
catch (final Exception e)
{
throw CalloutExecutionException.wrapIfNeeded(e)
.setCalloutExecutor(executor)
.setCalloutInstance(this)
.setField(field);
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\annotations\api\impl\AnnotatedCalloutInstance.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public class PostmanUploadController {
@PostMapping("/uploadFile")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file) {
return ResponseEntity.ok()
.body("file received successfully");
}
@PostMapping("/uploadJson")
public ResponseEntity<String> handleJsonInput(@RequestBody JsonRequest json) {
return ResponseEntity.ok()
.body(json.getId() + json.getName());
}
@PostMapping("/uploadJsonAndMultipartData") | public ResponseEntity<String> handleJsonAndMultipartInput(@RequestPart("data") JsonRequest json, @RequestPart("file") MultipartFile file) {
return ResponseEntity.ok()
.body(json.getId() + json.getName());
}
@PostMapping(value = "/uploadSingleFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> handleSingleFileUpload(@RequestParam("file") MultipartFile file) {
return ResponseEntity.ok("file received successfully");
}
@PostMapping(value = "/uploadJsonAndMultipartInput", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> handleUploadJsonAndMultipartInput(@RequestPart("data") JsonRequest json, @RequestPart("file") MultipartFile file) {
return ResponseEntity.ok(json.getId() + json.getName());
}
} | repos\tutorials-master\spring-boot-modules\spring-boot-mvc-2\src\main\java\com\baeldung\postman\controller\PostmanUploadController.java | 2 |
请完成以下Java代码 | public class ForecastLineHUPackingAware implements IHUPackingAware
{
public static final ForecastLineHUPackingAware of(final org.compiere.model.I_M_ForecastLine forecastLine)
{
return new ForecastLineHUPackingAware(InterfaceWrapperHelper.create(forecastLine, I_M_ForecastLine.class));
}
private final I_M_ForecastLine forecastLine;
private final PlainHUPackingAware values = new PlainHUPackingAware();
public ForecastLineHUPackingAware(final I_M_ForecastLine forecastLine)
{
super();
Check.assumeNotNull(forecastLine, "orderLine not null");
this.forecastLine = forecastLine;
}
@Override
public int getM_Product_ID()
{
return forecastLine.getM_Product_ID();
}
@Override
public void setM_Product_ID(final int productId)
{
forecastLine.setM_Product_ID(productId);
}
@Override
public int getM_AttributeSetInstance_ID()
{
return forecastLine.getM_AttributeSetInstance_ID();
}
@Override
public void setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID)
{
forecastLine.setM_AttributeSetInstance_ID(M_AttributeSetInstance_ID);
}
@Override
public int getC_UOM_ID()
{
return forecastLine.getC_UOM_ID();
}
@Override
public void setC_UOM_ID(final int uomId)
{
forecastLine.setC_UOM_ID(uomId);
}
@Override
public void setQty(final BigDecimal qty)
{
forecastLine.setQty(qty);
final ProductId productId = ProductId.ofRepoIdOrNull(getM_Product_ID());
final I_C_UOM uom = Services.get(IUOMDAO.class).getById(getC_UOM_ID());
final BigDecimal qtyCalculated = Services.get(IUOMConversionBL.class).convertToProductUOM(productId, uom, qty);
forecastLine.setQtyCalculated(qtyCalculated);
}
@Override
public BigDecimal getQty()
{
return forecastLine.getQty();
}
@Override
public int getM_HU_PI_Item_Product_ID()
{
final int forecastLine_PIItemProductId = forecastLine.getM_HU_PI_Item_Product_ID();
if (forecastLine_PIItemProductId > 0)
{
return forecastLine_PIItemProductId;
}
return -1; | }
@Override
public void setM_HU_PI_Item_Product_ID(final int huPiItemProductId)
{
forecastLine.setM_HU_PI_Item_Product_ID(huPiItemProductId);
}
@Override
public BigDecimal getQtyTU()
{
return forecastLine.getQtyEnteredTU();
}
@Override
public void setQtyTU(final BigDecimal qtyPacks)
{
forecastLine.setQtyEnteredTU(qtyPacks);
}
@Override
public void setC_BPartner_ID(final int partnerId)
{
values.setC_BPartner_ID(partnerId);
}
@Override
public int getC_BPartner_ID()
{
return values.getC_BPartner_ID();
}
@Override
public boolean isInDispute()
{
return values.isInDispute();
}
@Override
public void setInDispute(final boolean inDispute)
{
values.setInDispute(inDispute);
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\adempiere\gui\search\impl\ForecastLineHUPackingAware.java | 1 |
请在Spring Boot框架中完成以下Java代码 | public final ResponseEntity<ErrorDetails> handleAllExceptions(Exception ex, WebRequest request) throws Exception {
ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(),
ex.getMessage(), request.getDescription(false));
return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR);
}
@ExceptionHandler(UserNotFoundException.class)
public final ResponseEntity<ErrorDetails> handleUserNotFoundException(Exception ex, WebRequest request) throws Exception {
ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(),
ex.getMessage(), request.getDescription(false));
return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.NOT_FOUND); | }
@Override
protected ResponseEntity<Object> handleMethodArgumentNotValid(
MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) {
ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(),
"Total Errors:" + ex.getErrorCount() + " First Error:" + ex.getFieldError().getDefaultMessage(), request.getDescription(false));
return new ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST);
}
} | repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\exception\CustomizedResponseEntityExceptionHandler.java | 2 |
请完成以下Java代码 | public BigDecimal toBigDecimal()
{
return toMoney().toBigDecimal();
}
public int signum() {return toMoney().signum();}
/**
* @return absolute balance, negated if reversal
*/
public Money getPostBalance()
{
Money balanceAbs = toMoney().abs();
if (isReversal())
{
return balanceAbs.negate();
}
return balanceAbs;
}
/**
* @return true if the balance (debit - credit) is zero
*/
public boolean isBalanced() {return signum() == 0;}
/**
* @return true if both DR/CR are negative or zero
*/
public boolean isReversal() {return debit.signum() <= 0 && credit.signum() <= 0;}
public boolean isDebit()
{
if (isReversal())
{
return toMoney().signum() <= 0;
}
else
{
return toMoney().signum() >= 0;
}
}
public CurrencyId getCurrencyId() {return Money.getCommonCurrencyIdOfAll(debit, credit);}
public Balance negateAndInvert()
{
return new Balance(this.credit.negate(), this.debit.negate());
}
public Balance negateAndInvertIf(final boolean condition)
{
return condition ? negateAndInvert() : this;
}
public Balance toSingleSide()
{
final Money min = debit.min(credit);
if (min.isZero())
{
return this;
}
return new Balance(this.debit.subtract(min), this.credit.subtract(min));
}
public Balance computeDiffToBalance()
{
final Money diff = toMoney();
if (isReversal())
{
return diff.signum() < 0 ? ofCredit(diff) : ofDebit(diff.negate());
}
else
{
return diff.signum() < 0 ? ofDebit(diff.negate()) : ofCredit(diff);
}
}
public Balance invert()
{
return new Balance(this.credit, this.debit);
} | //
//
//
//
//
@ToString
private static class BalanceBuilder
{
private Money debit;
private Money credit;
public void add(@NonNull Balance balance)
{
add(balance.getDebit(), balance.getCredit());
}
public BalanceBuilder combine(@NonNull BalanceBuilder balanceBuilder)
{
add(balanceBuilder.debit, balanceBuilder.credit);
return this;
}
public void add(@Nullable Money debitToAdd, @Nullable Money creditToAdd)
{
if (debitToAdd != null)
{
this.debit = this.debit != null ? this.debit.add(debitToAdd) : debitToAdd;
}
if (creditToAdd != null)
{
this.credit = this.credit != null ? this.credit.add(creditToAdd) : creditToAdd;
}
}
public Optional<Balance> build()
{
return debit != null || credit != null
? Optional.of(new Balance(debit, credit))
: Optional.empty();
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\Balance.java | 1 |
请完成以下Java代码 | private AdTreeId getOrgTreeId()
{
return orgTreeId;
}
/**
* Load Org Access Add Tree to List
*/
public Builder addPermissionRecursively(final OrgPermission oa)
{
if (hasPermission(oa))
{
return this;
}
addPermission(oa, CollisionPolicy.Override);
// Do we look for trees?
final AdTreeId adTreeOrgId = getOrgTreeId();
if (adTreeOrgId == null)
{
return this;
}
final OrgResource orgResource = oa.getResource();
if (!orgResource.isGroupingOrg())
{
return this;
}
// Summary Org - Get Dependents
final MTree_Base tree = MTree_Base.getById(adTreeOrgId);
final String sql = "SELECT "
+ " AD_Client_ID"
+ ", AD_Org_ID"
+ ", " + I_AD_Org.COLUMNNAME_IsSummary
+ " FROM AD_Org "
+ " WHERE IsActive='Y' AND AD_Org_ID IN (SELECT Node_ID FROM " + tree.getNodeTableName()
+ " WHERE AD_Tree_ID=? AND Parent_ID=? AND IsActive='Y')";
final Object[] sqlParams = new Object[] { tree.getAD_Tree_ID(), orgResource.getOrgId() };
PreparedStatement pstmt = null;
ResultSet rs = null;
try
{ | pstmt = DB.prepareStatement(sql, ITrx.TRXNAME_None);
DB.setParameters(pstmt, sqlParams);
rs = pstmt.executeQuery();
while (rs.next())
{
final ClientId clientId = ClientId.ofRepoId(rs.getInt(1));
final OrgId orgId = OrgId.ofRepoId(rs.getInt(2));
final boolean isGroupingOrg = StringUtils.toBoolean(rs.getString(3));
final OrgResource resource = OrgResource.of(clientId, orgId, isGroupingOrg);
final OrgPermission childOrgPermission = oa.copyWithResource(resource);
addPermissionRecursively(childOrgPermission);
}
return this;
}
catch (final SQLException e)
{
throw new DBException(e, sql, sqlParams);
}
finally
{
DB.close(rs, pstmt);
}
}
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\permissions\OrgPermissions.java | 1 |
请完成以下Java代码 | public UserOperationLogContextEntryBuilder deploymentId(String deploymentId) {
entry.setDeploymentId(deploymentId);
return this;
}
public UserOperationLogContextEntryBuilder batchId(String batchId) {
entry.setBatchId(batchId);
return this;
}
public UserOperationLogContextEntryBuilder taskId(String taskId) {
entry.setTaskId(taskId);
return this;
}
public UserOperationLogContextEntryBuilder caseInstanceId(String caseInstanceId) {
entry.setCaseInstanceId(caseInstanceId);
return this;
} | public UserOperationLogContextEntryBuilder category(String category) {
entry.setCategory(category);
return this;
}
public UserOperationLogContextEntryBuilder annotation(String annotation) {
entry.setAnnotation(annotation);
return this;
}
public UserOperationLogContextEntryBuilder tenantId(String tenantId) {
entry.setTenantId(tenantId);
return this;
}
} | repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\oplog\UserOperationLogContextEntryBuilder.java | 1 |
请完成以下Java代码 | public void increaseActiveChildren() {
activeChildren++;
}
public void addChildPlanItemInstance(PlanItemInstanceEntity planItemInstanceEntity) {
if (newChildPlanItemInstances == null) {
newChildPlanItemInstances = new ArrayList<>();
}
newChildPlanItemInstances.add(planItemInstanceEntity);
}
public void markCriteriaChanged() {
criteriaChanged = true;
}
public int getActiveChildren() {
return activeChildren;
}
public boolean isCriteriaChanged() {
return criteriaChanged;
}
public boolean hasNewChildPlanItemInstances() {
return newChildPlanItemInstances != null && newChildPlanItemInstances.size() > 0;
}
public List<PlanItemInstanceEntity> getNewChildPlanItemInstances() {
return newChildPlanItemInstances;
}
public boolean criteriaChangedOrNewActiveChildren() {
return criteriaChanged || activeChildren > 0;
}
public List<PlanItemInstanceEntity> getAllChildPlanItemInstances() {
return allChildPlanItemInstances;
} | /**
* Returns true, if the given plan item instance has at least one instance in completed state (only possible of course for repetition based plan items).
*
* @param planItemInstance the plan item instance to check for a completed instance of the same plan item
* @return true, if a completed instance was found, false otherwise
*/
public boolean hasCompletedPlanItemInstance(PlanItemInstanceEntity planItemInstance) {
if (allChildPlanItemInstances == null || allChildPlanItemInstances.size() == 0) {
return false;
}
for (PlanItemInstanceEntity childPlanItemInstance : allChildPlanItemInstances) {
if (childPlanItemInstance.getPlanItemDefinitionId().equals(planItemInstance.getPlanItemDefinitionId()) && PlanItemInstanceState.COMPLETED
.equals(childPlanItemInstance.getState())) {
return true;
}
}
return false;
}
} | repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\PlanItemEvaluationResult.java | 1 |
请完成以下Java代码 | public void onCR_TaxTotalAmt(final I_GL_JournalLine glJournalLine)
{
final ITaxAccountable taxAccountable = asTaxAccountable(glJournalLine, ACCTSIGN_Credit);
taxAccountableCallout.onTaxTotalAmt(taxAccountable);
}
private void setAutoTaxType(final I_GL_JournalLine glJournalLine)
{
final boolean drAutoTax = isAutoTaxAccount(glJournalLine.getAccount_DR());
final boolean crAutoTax = isAutoTaxAccount(glJournalLine.getAccount_CR());
//
// We can activate tax accounting only for one side
if (drAutoTax && crAutoTax)
{
throw new AdempiereException("@" + MSG_AutoTaxAccountDrCrNotAllowed + "@");
}
final boolean taxRecord = drAutoTax || crAutoTax;
//
// Tax accounting can be allowed only if in a new transaction
final boolean isPartialTrx = !glJournalLine.isAllowAccountDR() || !glJournalLine.isAllowAccountCR();
if (taxRecord && isPartialTrx)
{
throw new AdempiereException("@" + MSG_AutoTaxNotAllowedOnPartialTrx + "@");
}
//
// Set AutoTaxaAcount flags
glJournalLine.setDR_AutoTaxAccount(drAutoTax);
glJournalLine.setCR_AutoTaxAccount(crAutoTax);
//
// Update journal line type
final String type = taxRecord ? X_GL_JournalLine.TYPE_Tax : X_GL_JournalLine.TYPE_Normal;
glJournalLine.setType(type);
}
private ITaxAccountable asTaxAccountable(final I_GL_JournalLine glJournalLine, final boolean accountSignDR)
{
final IGLJournalLineBL glJournalLineBL = Services.get(IGLJournalLineBL.class);
return glJournalLineBL.asTaxAccountable(glJournalLine, accountSignDR);
}
private boolean isAutoTaxAccount(final I_C_ValidCombination accountVC)
{ | if (accountVC == null)
{
return false;
}
final I_C_ElementValue account = accountVC.getAccount();
if (account == null)
{
return false;
}
return account.isAutoTaxAccount();
}
private boolean isAutoTax(final I_GL_JournalLine glJournalLine)
{
return glJournalLine.isDR_AutoTaxAccount() || glJournalLine.isCR_AutoTaxAccount();
}
@Nullable
private AccountConceptualName suggestAccountConceptualName(@NonNull final AccountId accountId)
{
final ElementValueId elementValueId = accountDAO.getElementValueIdByAccountId(accountId);
final ElementValue elementValue = elementValueRepository.getById(elementValueId);
return elementValue.getAccountConceptualName();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\callout\GL_JournalLine.java | 1 |
请完成以下Java代码 | public KeyNamePair getKeyNamePair()
{
return new KeyNamePair(get_ID(), getName());
}
/** Set Sequence.
@param SeqNo
Method of ordering records; lowest number comes first
*/
public void setSeqNo (int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo));
}
/** Get Sequence.
@return Method of ordering records; lowest number comes first
*/
public int getSeqNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set Record Sort No.
@param SortNo
Determines in what order the records are displayed | */
public void setSortNo (int SortNo)
{
set_Value (COLUMNNAME_SortNo, Integer.valueOf(SortNo));
}
/** Get Record Sort No.
@return Determines in what order the records are displayed
*/
public int getSortNo ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SortNo);
if (ii == null)
return 0;
return ii.intValue();
}
} | repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_UserDef_Field.java | 1 |
请完成以下Java代码 | public String infixToPostfix(String infix) {
StringBuilder result = new StringBuilder();
Stack<Character> stack = new Stack<>();
for (int i = 0; i < infix.length(); i++) {
char ch = infix.charAt(i);
if (isOperand(ch)) {
result.append(ch);
} else if (ch == '(') {
stack.push(ch);
} else if (ch == ')') {
while (!stack.isEmpty() && stack.peek() != '(') {
result.append(stack.pop());
}
stack.pop();
} else {
while (!stack.isEmpty() && (operatorPrecedenceCondition(infix, i, stack))) { | result.append(stack.pop());
}
stack.push(ch);
}
}
while (!stack.isEmpty()) {
result.append(stack.pop());
}
return result.toString();
}
private boolean operatorPrecedenceCondition(String infix, int i, Stack<Character> stack) {
return getPrecedenceScore(infix.charAt(i)) < getPrecedenceScore(stack.peek()) || getPrecedenceScore(infix.charAt(i)) == getPrecedenceScore(stack.peek()) && associativity(infix.charAt(i)) == 'L';
}
} | repos\tutorials-master\core-java-modules\core-java-lang-operators-3\src\main\java\com\baeldung\infixpostfix\InfixToPostFixExpressionConversion.java | 1 |
请完成以下Java代码 | public void shutdown() {
if (!bufferPadExecutors.isShutdown()) {
bufferPadExecutors.shutdownNow();
}
if (bufferPadSchedule != null && !bufferPadSchedule.isShutdown()) {
bufferPadSchedule.shutdownNow();
}
}
/**
* Whether is padding
*
* @return
*/
public boolean isRunning() {
return running.get();
}
/**
* Padding buffer in the thread pool
*/
public void asyncPadding() {
bufferPadExecutors.submit(this::paddingBuffer);
}
/**
* Padding buffer fill the slots until to catch the cursor
*/
public void paddingBuffer() {
LOGGER.info("Ready to padding buffer lastSecond:{}. {}", lastSecond.get(), ringBuffer); | // is still running
if (!running.compareAndSet(false, true)) {
LOGGER.info("Padding buffer is still running. {}", ringBuffer);
return;
}
// fill the rest slots until to catch the cursor
boolean isFullRingBuffer = false;
while (!isFullRingBuffer) {
List<Long> uidList = uidProvider.provide(lastSecond.incrementAndGet());
for (Long uid : uidList) {
isFullRingBuffer = !ringBuffer.put(uid);
if (isFullRingBuffer) {
break;
}
}
}
// not running now
running.compareAndSet(true, false);
LOGGER.info("End to padding buffer lastSecond:{}. {}", lastSecond.get(), ringBuffer);
}
/**
* Setters
*/
public void setScheduleInterval(long scheduleInterval) {
Assert.isTrue(scheduleInterval > 0, "Schedule interval must positive!");
this.scheduleInterval = scheduleInterval;
}
} | repos\Spring-Boot-In-Action-master\id-spring-boot-starter\src\main\java\com\baidu\fsg\uid\buffer\BufferPaddingExecutor.java | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.