instruction
string | input
string | output
string | source_file
string | priority
int64 |
|---|---|---|---|---|
请完成以下Java代码
|
public void setOperationType(String operationType) {
this.operationType = operationType;
}
@CamundaQueryParam("entityType")
public void setEntityType(String entityType) {
this.entityType = entityType;
}
@CamundaQueryParam(value = "entityTypeIn", converter = StringArrayConverter.class)
public void setEntityTypeIn(String[] entityTypes) {
this.entityTypes = entityTypes;
}
@CamundaQueryParam("category")
public void setcategory(String category) {
this.category = category;
}
@CamundaQueryParam(value = "categoryIn", converter = StringArrayConverter.class)
public void setCategoryIn(String[] categories) {
|
this.categories = categories;
}
@CamundaQueryParam("property")
public void setProperty(String property) {
this.property = property;
}
@CamundaQueryParam(value = "afterTimestamp", converter = DateConverter.class)
public void setAfterTimestamp(Date after) {
this.afterTimestamp = after;
}
@CamundaQueryParam(value = "beforeTimestamp", converter = DateConverter.class)
public void setBeforeTimestamp(Date before) {
this.beforeTimestamp = before;
}
}
|
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\UserOperationLogQueryDto.java
| 1
|
请完成以下Java代码
|
public class QualityInspectionLinesCollection implements IQualityInspectionLinesCollection
{
private final List<IQualityInspectionLine> lines;
private final IQualityInspectionOrder qiOrder;
/* package */ QualityInspectionLinesCollection(final List<IQualityInspectionLine> lines, final IQualityInspectionOrder qiOrder)
{
super();
Check.assumeNotNull(lines, "lines not null");
this.lines = new ArrayList<>(lines);
this.qiOrder = qiOrder;
}
@Override
public String toString()
{
final StringBuilder sb = new StringBuilder();
sb.append("QualityInspectionLinesCollection[");
if (!lines.isEmpty())
{
for (final IQualityInspectionLine line : lines)
{
sb.append("\n\t").append(line);
}
sb.append("\n"); // new line after last one
}
else
{
sb.append("empty");
}
sb.append("]");
return sb.toString();
}
@Override
public IQualityInspectionLine getByType(final QualityInspectionLineType type)
{
final List<IQualityInspectionLine> linesFound = getAllByType(type);
if (linesFound.isEmpty())
{
throw new AdempiereException("No line found for type: " + type);
}
else if (linesFound.size() > 1)
{
throw new AdempiereException("More then one line found for type " + type + ": " + linesFound);
}
return linesFound.get(0);
}
|
@Override
public List<IQualityInspectionLine> getAllByType(final QualityInspectionLineType... types)
{
Check.assumeNotEmpty(types, "types not empty");
final List<QualityInspectionLineType> typesList = Arrays.asList(types);
final List<IQualityInspectionLine> linesFound = new ArrayList<>();
for (final IQualityInspectionLine line : lines)
{
final QualityInspectionLineType lineType = line.getQualityInspectionLineType();
if (typesList.contains(lineType))
{
linesFound.add(line);
}
}
return linesFound;
}
@Override
public IQualityInspectionOrder getQualityInspectionOrder()
{
return this.qiOrder;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\QualityInspectionLinesCollection.java
| 1
|
请完成以下Java代码
|
public Currency getCurrency()
{
return currencyDAO.getByCurrencyCode(CURRENCY_ISO);
}
public static void setOverallNumberOfInvoicings(final int overallNumberOfInvoicings)
{
HardCodedQualityBasedConfig.overallNumberOfInvoicings = overallNumberOfInvoicings;
}
@Override
public int getOverallNumberOfInvoicings()
{
return overallNumberOfInvoicings;
}
public static void setQualityAdjustmentActive(final boolean qualityAdjustmentOn)
{
HardCodedQualityBasedConfig.qualityAdjustmentsActive = qualityAdjustmentOn;
}
@Override
public I_M_Product getRegularPPOrderProduct()
{
final IContextAware ctxAware = getContext();
return productPA.retrieveProduct(ctxAware.getCtx(),
M_PRODUCT_REGULAR_PP_ORDER_VALUE,
|
true, // throwExIfProductNotFound
ctxAware.getTrxName());
}
/**
* @return the date that was set with {@link #setValidToDate(Timestamp)}, or falls back to "now plus 2 months". Never returns <code>null</code>.
*/
@Override
public Timestamp getValidToDate()
{
if (validToDate == null)
{
return TimeUtil.addMonths(SystemTime.asDate(), 2);
}
return validToDate;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\ch\lagerkonf\impl\HardCodedQualityBasedConfig.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class EventDeploymentResponse {
protected String id;
protected String name;
@JsonSerialize(using = DateToStringSerializer.class, as = Date.class)
protected Date deploymentTime;
protected String category;
protected String parentDeploymentId;
protected String url;
protected String tenantId;
public EventDeploymentResponse(EventDeployment deployment, String url) {
setId(deployment.getId());
setName(deployment.getName());
setDeploymentTime(deployment.getDeploymentTime());
setCategory(deployment.getCategory());
setParentDeploymentId(deployment.getParentDeploymentId());
setTenantId(deployment.getTenantId());
setUrl(url);
}
@ApiModelProperty(example = "10")
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
@ApiModelProperty(example = "flowable-examples.bar")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@ApiModelProperty(example = "2010-10-13T14:54:26.750+02:00")
public Date getDeploymentTime() {
return deploymentTime;
}
public void setDeploymentTime(Date deploymentTime) {
this.deploymentTime = deploymentTime;
}
@ApiModelProperty(example = "examples")
public String getCategory() {
|
return category;
}
public void setCategory(String category) {
this.category = category;
}
@ApiModelProperty(example = "12")
public String getParentDeploymentId() {
return parentDeploymentId;
}
public void setParentDeploymentId(String parentDeploymentId) {
this.parentDeploymentId = parentDeploymentId;
}
public void setUrl(String url) {
this.url = url;
}
@ApiModelProperty(example = "http://localhost:8081/flowable-rest/service/event-registry-repository/deployments/10")
public String getUrl() {
return url;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@ApiModelProperty(example = "")
public String getTenantId() {
return tenantId;
}
}
|
repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\EventDeploymentResponse.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class PushMsgUtil {
@Autowired
private ISysMessageService sysMessageService;
@Autowired
private ISysMessageTemplateService sysMessageTemplateService;
@Autowired
private Configuration freemarkerConfig;
/**
* @param msgType 消息类型 1短信 2邮件 3微信
* @param templateCode 消息模板码
* @param map 消息参数
* @param sentTo 接收消息方
*/
public boolean sendMessage(String msgType, String templateCode, Map<String, String> map, String sentTo) {
List<SysMessageTemplate> sysSmsTemplates = sysMessageTemplateService.selectByCode(templateCode);
SysMessage sysMessage = new SysMessage();
if (sysSmsTemplates.size() > 0) {
SysMessageTemplate sysSmsTemplate = sysSmsTemplates.get(0);
sysMessage.setEsType(msgType);
sysMessage.setEsReceiver(sentTo);
//模板标题
String title = sysSmsTemplate.getTemplateName();
//模板内容
String content = sysSmsTemplate.getTemplateContent();
StringWriter stringWriter = new StringWriter();
Template template = null;
try {
template = new Template("SysMessageTemplate", content, freemarkerConfig);
template.process(map, stringWriter);
|
} catch (IOException e) {
e.printStackTrace();
return false;
} catch (TemplateException e) {
e.printStackTrace();
return false;
}
content = stringWriter.toString();
sysMessage.setEsTitle(title);
sysMessage.setEsContent(content);
sysMessage.setEsParam(JSONObject.toJSONString(map));
sysMessage.setEsSendTime(new Date());
sysMessage.setEsSendStatus(SendMsgStatusEnum.WAIT.getCode());
sysMessage.setEsSendNum(0);
if(sysMessageService.save(sysMessage)) {
return true;
}
}
return false;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\message\util\PushMsgUtil.java
| 2
|
请完成以下Java代码
|
public OrderAttachmentRow withChanges(@NonNull final Boolean updatedIsAttachPurchaseOrderFlag)
{
final OrderAttachmentRow.OrderAttachmentRowBuilder rowBuilder = toBuilder();
rowBuilder.isAttachToPurchaseOrder(updatedIsAttachPurchaseOrderFlag);
return rowBuilder.build();
}
Optional<AttachmentLinksRequest> toAttachmentLinksRequest()
{
final Map<String, String> emailAttachmentTagAsMap = new HashMap<>();
emailAttachmentTagAsMap.put(TAGNAME_SEND_VIA_EMAIL, Boolean.TRUE.toString());
final AttachmentTags emailAttachmentTag = AttachmentTags.ofMap(emailAttachmentTagAsMap);
final TableRecordReference purchaseOrderRecordRef = getPurchaseOrderRecordRef();
if (isAttachToPurchaseOrder)
{
return Optional.of(AttachmentLinksRequest.builder()
.attachmentEntryId(attachmentEntry.getId())
.linksToAdd(ImmutableList.of(purchaseOrderRecordRef))
.tagsToAdd(emailAttachmentTag)
.build());
}
else if (isDirectlyAttachToPurchaseOrder)
{
return isAttachmentLinkedOnlyToPO()
? Optional.of(AttachmentLinksRequest.builder()
.attachmentEntryId(attachmentEntry.getId())
.tagsToRemove(emailAttachmentTag)
.build())
: Optional.of(AttachmentLinksRequest.builder()
.attachmentEntryId(attachmentEntry.getId())
|
.linksToRemove(ImmutableList.of(purchaseOrderRecordRef))
.tagsToRemove(emailAttachmentTag)
.build());
}
return Optional.empty();
}
private boolean isAttachmentLinkedOnlyToPO()
{
return attachmentEntry.getLinkedRecords().size() == 1
&& attachmentEntry.getLinkedRecords().contains(getPurchaseOrderRecordRef());
}
private TableRecordReference getPurchaseOrderRecordRef()
{
return TableRecordReference.of(I_C_Order.Table_Name, selectedPurchaseOrder.getC_Order_ID());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\attachmenteditor\OrderAttachmentRow.java
| 1
|
请完成以下Java代码
|
private static String normalizedTokenEntry(final String token)
{
if (token == null || token.isEmpty())
{
return ANY;
}
return token;
}
/**
* Gets Password for given configuration.
*
* @return password or null if configuration was not found
*/
public String getPassword(final String hostname, final String port, final String dbName, final String username)
{
final PgPassEntry entryLookup = new PgPassEntry(hostname, port, dbName, username, null); // password=null
for (final PgPassEntry entry : getEntries())
{
if (matches(entry, entryLookup))
{
return entry.getPassword();
}
}
return null;
}
private boolean matches(final PgPassEntry entry, final PgPassEntry entryLookup)
{
return matchesToken(entry.getHost(), entryLookup.getHost())
&& matchesToken(entry.getPort(), entryLookup.getPort())
&& matchesToken(entry.getDbName(), entryLookup.getDbName())
&& matchesToken(entry.getUser(), entryLookup.getUser());
}
private static boolean matchesToken(final String token, final String tokenLookup)
{
if (token == null)
{
// shall not happen, development error
throw new IllegalStateException("token shall not be null");
}
|
if (ANY.equals(tokenLookup))
{
throw new IllegalStateException("token lookup shall not be ANY");
}
//
if (token == tokenLookup)
{
return true;
}
if (ANY.equals(token))
{
return true;
}
if (token.equals(tokenLookup))
{
return true;
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\sql\postgresql\PgPassFile.java
| 1
|
请完成以下Java代码
|
private String getJgAuthRequsetPath(HttpServletRequest request) {
String queryString = request.getQueryString();
String requestPath = request.getRequestURI();
if(oConvertUtils.isNotEmpty(queryString)){
requestPath += "?" + queryString;
}
// 去掉其他参数(保留一个参数) 例如:loginController.do?login
if (requestPath.indexOf(SymbolConstant.AND) > -1) {
requestPath = requestPath.substring(0, requestPath.indexOf("&"));
}
if(requestPath.indexOf(QueryRuleEnum.EQ.getValue())!=-1){
if(requestPath.indexOf(SPOT_DO)!=-1){
requestPath = requestPath.substring(0,requestPath.indexOf(".do")+3);
}else{
requestPath = requestPath.substring(0,requestPath.indexOf("?"));
}
}
// 去掉项目路径
|
requestPath = requestPath.substring(request.getContextPath().length() + 1);
return filterUrl(requestPath);
}
@Deprecated
private boolean moHuContain(List<String> list,String key){
for(String str : list){
if(key.contains(str)){
return true;
}
}
return false;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\aspect\PermissionDataAspect.java
| 1
|
请完成以下Spring Boot application配置
|
server:
port: 8096
servlet:
session:
timeout: 30
spring:
application:
name: roncoo-pay-app-order-polling
logging:
config: classpath:logbac
|
k.xml
mybatis:
mapper-locations: classpath*:mybatis/mapper/**/*.xml
|
repos\roncoo-pay-master\roncoo-pay-app-order-polling\src\main\resources\application.yml
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public String getOutcomeReason()
{
return outcomeReason;
}
public void setOutcomeReason(String outcomeReason)
{
this.outcomeReason = outcomeReason;
}
public PostSaleAuthenticationProgram status(String status)
{
this.status = status;
return this;
}
/**
* The value in this field indicates whether the order line item has passed or failed the authenticity verification inspection, or if the inspection and/or results are still pending. The possible values returned here are PENDING, PASSED, FAILED, or PASSED_WITH_EXCEPTION. For implementation help, refer to <a
* href='https://developer.ebay.com/api-docs/sell/fulfillment/types/sel:AuthenticityVerificationStatusEnum'>eBay API documentation</a>
*
* @return status
**/
@javax.annotation.Nullable
@ApiModelProperty(value = "The value in this field indicates whether the order line item has passed or failed the authenticity verification inspection, or if the inspection and/or results are still pending. The possible values returned here are PENDING, PASSED, FAILED, or PASSED_WITH_EXCEPTION. For implementation help, refer to <a href='https://developer.ebay.com/api-docs/sell/fulfillment/types/sel:AuthenticityVerificationStatusEnum'>eBay API documentation</a>")
public String getStatus()
{
return status;
}
public void setStatus(String status)
{
this.status = status;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
PostSaleAuthenticationProgram postSaleAuthenticationProgram = (PostSaleAuthenticationProgram)o;
return Objects.equals(this.outcomeReason, postSaleAuthenticationProgram.outcomeReason) &&
Objects.equals(this.status, postSaleAuthenticationProgram.status);
}
@Override
|
public int hashCode()
{
return Objects.hash(outcomeReason, status);
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append("class PostSaleAuthenticationProgram {\n");
sb.append(" outcomeReason: ").append(toIndentedString(outcomeReason)).append("\n");
sb.append(" status: ").append(toIndentedString(status)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(Object o)
{
if (o == null)
{
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\PostSaleAuthenticationProgram.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public class SecurityConfig {
@Bean
public MapReactiveUserDetailsService userDetailsService() {
// 创建一个用户
UserDetails user = User.withDefaultPasswordEncoder()
.username("user")
.password("user")
.roles("USER")
.build();
// 如果胖友有更多用户的诉求,这里可以继续创建
// 创建 MapReactiveUserDetailsService
return new MapReactiveUserDetailsService(user);
}
|
@Bean
public SecurityWebFilterChain springSecurityFilterChain(ServerHttpSecurity http) {
http.authorizeExchange(exchanges -> // 设置权限配置
exchanges
.pathMatchers("/assets/**").permitAll() // 静态资源,允许匿名访问
.pathMatchers("/login").permitAll() // 登陆接口,允许匿名访问
.anyExchange().authenticated() //
)
.formLogin().loginPage("/login") // 登陆页面
.and().logout().logoutUrl("/logout") // 登出界面
.and().httpBasic() // HTTP Basic 认证方式
.and().csrf().disable(); // csrf 禁用
return http.build();
}
}
|
repos\SpringBoot-Labs-master\lab-35\lab-35-admin-03-adminserver\src\main\java\cn\iocoder\springboot\lab35\adminserver\config\SecurityConfig.java
| 2
|
请完成以下Java代码
|
public int getRepeatDistance ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_RepeatDistance);
if (ii == null)
return 0;
return ii.intValue();
}
/** StartPoint AD_Reference_ID=248 */
public static final int STARTPOINT_AD_Reference_ID=248;
/** North = 1 */
public static final String STARTPOINT_North = "1";
/** North East = 2 */
public static final String STARTPOINT_NorthEast = "2";
/** East = 3 */
public static final String STARTPOINT_East = "3";
/** South East = 4 */
public static final String STARTPOINT_SouthEast = "4";
/** South = 5 */
public static final String STARTPOINT_South = "5";
/** South West = 6 */
public static final String STARTPOINT_SouthWest = "6";
/** West = 7 */
public static final String STARTPOINT_West = "7";
/** North West = 8 */
public static final String STARTPOINT_NorthWest = "8";
/** Set Start Point.
@param StartPoint
Start point of the gradient colors
|
*/
public void setStartPoint (String StartPoint)
{
set_Value (COLUMNNAME_StartPoint, StartPoint);
}
/** Get Start Point.
@return Start point of the gradient colors
*/
public String getStartPoint ()
{
return (String)get_Value(COLUMNNAME_StartPoint);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Color.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getMaintenanceInterval() {
return maintenanceInterval;
}
public void setMaintenanceInterval(String maintenanceInterval) {
this.maintenanceInterval = maintenanceInterval;
}
public DeviceToCreateMaintenances lastServiceDate(String lastServiceDate) {
this.lastServiceDate = lastServiceDate;
return this;
}
/**
* Letzte Prüfung
* @return lastServiceDate
**/
@Schema(example = "01.06.2020", description = "Letzte Prüfung")
public String getLastServiceDate() {
return lastServiceDate;
}
public void setLastServiceDate(String lastServiceDate) {
this.lastServiceDate = lastServiceDate;
}
public DeviceToCreateMaintenances nextServiceDate(String nextServiceDate) {
this.nextServiceDate = nextServiceDate;
return this;
}
/**
* Nächste Prüfung
* @return nextServiceDate
**/
@Schema(example = "01.12.2020", description = "Nächste Prüfung")
public String getNextServiceDate() {
return nextServiceDate;
}
public void setNextServiceDate(String nextServiceDate) {
this.nextServiceDate = nextServiceDate;
}
@Override
public boolean equals(java.lang.Object o) {
|
if (this == o) {
return true;
}
if (o == null || getClass() != o.getClass()) {
return false;
}
DeviceToCreateMaintenances deviceToCreateMaintenances = (DeviceToCreateMaintenances) o;
return Objects.equals(this.maintenanceCode, deviceToCreateMaintenances.maintenanceCode) &&
Objects.equals(this.maintenanceInterval, deviceToCreateMaintenances.maintenanceInterval) &&
Objects.equals(this.lastServiceDate, deviceToCreateMaintenances.lastServiceDate) &&
Objects.equals(this.nextServiceDate, deviceToCreateMaintenances.nextServiceDate);
}
@Override
public int hashCode() {
return Objects.hash(maintenanceCode, maintenanceInterval, lastServiceDate, nextServiceDate);
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("class DeviceToCreateMaintenances {\n");
sb.append(" maintenanceCode: ").append(toIndentedString(maintenanceCode)).append("\n");
sb.append(" maintenanceInterval: ").append(toIndentedString(maintenanceInterval)).append("\n");
sb.append(" lastServiceDate: ").append(toIndentedString(lastServiceDate)).append("\n");
sb.append(" nextServiceDate: ").append(toIndentedString(nextServiceDate)).append("\n");
sb.append("}");
return sb.toString();
}
/**
* Convert the given object to string with each line indented by 4 spaces
* (except the first line).
*/
private String toIndentedString(java.lang.Object o) {
if (o == null) {
return "null";
}
return o.toString().replace("\n", "\n ");
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\DeviceToCreateMaintenances.java
| 2
|
请完成以下Java代码
|
public IHUContext getHUContext()
{
return huContext;
}
@Override
public ProductId getProductId()
{
return productId;
}
@Override
public BigDecimal getQty()
{
return qty;
}
@Override
public I_C_UOM getC_UOM()
{
return uom;
}
@Override
public IAttributeSet getAttributesFrom()
{
return attributeStorageFrom;
}
@Override
public IAttributeStorage getAttributesTo()
{
return attributeStorageTo;
}
@Override
public IHUStorage getHUStorageFrom()
{
return huStorageFrom;
}
|
@Override
public IHUStorage getHUStorageTo()
{
return huStorageTo;
}
@Override
public BigDecimal getQtyUnloaded()
{
return qtyUnloaded;
}
@Override
public boolean isVHUTransfer()
{
return vhuTransfer;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\HUAttributeTransferRequest.java
| 1
|
请完成以下Java代码
|
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代码
|
class ConditionEvaluationReportLogger {
private final Log logger = LogFactory.getLog(getClass());
private final Supplier<ConditionEvaluationReport> reportSupplier;
private final LogLevel logLevel;
ConditionEvaluationReportLogger(LogLevel logLevel, Supplier<ConditionEvaluationReport> reportSupplier) {
Assert.isTrue(isInfoOrDebug(logLevel), "'logLevel' must be INFO or DEBUG");
this.logLevel = logLevel;
this.reportSupplier = reportSupplier;
}
private boolean isInfoOrDebug(LogLevel logLevel) {
return LogLevel.INFO.equals(logLevel) || LogLevel.DEBUG.equals(logLevel);
}
void logReport(boolean isCrashReport) {
ConditionEvaluationReport report = this.reportSupplier.get();
if (report == null) {
this.logger.info("Unable to provide the condition evaluation report");
return;
}
if (!report.getConditionAndOutcomesBySource().isEmpty()) {
if (this.logLevel.equals(LogLevel.INFO)) {
if (this.logger.isInfoEnabled()) {
this.logger.info(new ConditionEvaluationReportMessage(report));
}
else if (isCrashReport) {
logMessage("info");
}
}
|
else {
if (this.logger.isDebugEnabled()) {
this.logger.debug(new ConditionEvaluationReportMessage(report));
}
else if (isCrashReport) {
logMessage("debug");
}
}
}
}
private void logMessage(String logLevel) {
this.logger.info(String.format("%n%nError starting ApplicationContext. To display the "
+ "condition evaluation report re-run your application with '%s' enabled.", logLevel));
}
}
|
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\logging\ConditionEvaluationReportLogger.java
| 2
|
请完成以下Java代码
|
public void setQueryVariables(List<VariableInstanceEntity> queryVariables) {
this.queryVariables = queryVariables;
}
public Date getClaimTime() {
return claimTime;
}
public void setClaimTime(Date claimTime) {
this.claimTime = claimTime;
}
public Integer getAppVersion() {
return this.appVersion;
}
|
public void setAppVersion(Integer appVersion) {
this.appVersion = appVersion;
}
public String toString() {
return "Task[id=" + id + ", name=" + name + "]";
}
private String truncate(String string, int maxLength) {
if (string != null) {
return string.length() > maxLength ? string.substring(0, maxLength) : string;
}
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\TaskEntityImpl.java
| 1
|
请完成以下Java代码
|
public void onChildAttributeStorageRemoved(final IAttributeStorage childAttributeStorageRemoved)
{
throw new HUException("Null storage cannot have children");
}
@Override
public boolean isReadonlyUI(final IAttributeValueContext ctx, final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
@Override
public boolean isDisplayedUI(final I_M_Attribute attribute, final Set<ProductId> productIds)
{
return false;
}
@Override
public boolean isMandatory(final @NonNull I_M_Attribute attribute, final Set<ProductId> productIds, final boolean isMaterialReceipt)
{
return false;
}
@Override
public void pushUp()
{
// nothing
}
@Override
public void pushUpRollback()
{
// nothing
}
@Override
public void pushDown()
{
// nothing
}
@Override
public void saveChangesIfNeeded()
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public void setSaveOnChange(final boolean saveOnChange)
{
// nothing
// NOTE: not throwing UnsupportedOperationException because this storage contains no attributes so it will never have something to change
}
@Override
public IAttributeStorageFactory getAttributeStorageFactory()
{
throw new UnsupportedOperationException();
}
@Nullable
@Override
public UOMType getQtyUOMTypeOrNull()
{
// no UOMType available
return null;
}
@Override
public String toString()
{
return "NullAttributeStorage []";
}
|
@Override
public BigDecimal getStorageQtyOrZERO()
{
// no storage quantity available; assume ZERO
return BigDecimal.ZERO;
}
/**
* @return <code>false</code>.
*/
@Override
public boolean isVirtual()
{
return false;
}
@Override
public boolean isNew(final I_M_Attribute attribute)
{
throw new AttributeNotFoundException(attribute, this);
}
/**
* @return true, i.e. never disposed
*/
@Override
public boolean assertNotDisposed()
{
return true; // not disposed
}
@Override
public boolean assertNotDisposedTree()
{
return true; // not disposed
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\NullAttributeStorage.java
| 1
|
请完成以下Java代码
|
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 meta addElement (Element element)
{
addElementToRegistry (element);
return (this);
}
/**
* Adds an Element to the element.
*
* @param element
* Adds an Element to the element.
*/
public meta addElement (String element)
{
addElementToRegistry (element);
|
return (this);
}
/**
* Removes an Element from the element.
*
* @param hashcode
* the name of the element to be removed.
*/
public meta removeElement (String hashcode)
{
removeElementFromRegistry (hashcode);
return (this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\meta.java
| 1
|
请完成以下Java代码
|
public void transformCase(Case element, CmmnCaseDefinition caseDefinition) {
}
public void transformCasePlanModel(org.camunda.bpm.model.cmmn.impl.instance.CasePlanModel casePlanModel, CmmnActivity activity) {
transformCasePlanModel((org.camunda.bpm.model.cmmn.instance.CasePlanModel) casePlanModel, activity);
}
public void transformCasePlanModel(CasePlanModel casePlanModel, CmmnActivity activity) {
}
public void transformHumanTask(PlanItem planItem, HumanTask humanTask, CmmnActivity activity) {
}
public void transformProcessTask(PlanItem planItem, ProcessTask processTask, CmmnActivity activity) {
}
public void transformCaseTask(PlanItem planItem, CaseTask caseTask, CmmnActivity activity) {
}
public void transformDecisionTask(PlanItem planItem, DecisionTask decisionTask, CmmnActivity activity) {
}
|
public void transformTask(PlanItem planItem, Task task, CmmnActivity activity) {
}
public void transformStage(PlanItem planItem, Stage stage, CmmnActivity activity) {
}
public void transformMilestone(PlanItem planItem, Milestone milestone, CmmnActivity activity) {
}
public void transformEventListener(PlanItem planItem, EventListener eventListener, CmmnActivity activity) {
}
public void transformSentry(Sentry sentry, CmmnSentryDeclaration sentryDeclaration) {
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\transformer\AbstractCmmnTransformListener.java
| 1
|
请完成以下Java代码
|
public BigDecimal getA_Period_8 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Period_8);
if (bd == null)
return Env.ZERO;
return bd;
}
/** Set A_Period_9.
@param A_Period_9 A_Period_9 */
public void setA_Period_9 (BigDecimal A_Period_9)
{
set_Value (COLUMNNAME_A_Period_9, A_Period_9);
}
/** Get A_Period_9.
@return A_Period_9 */
public BigDecimal getA_Period_9 ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Period_9);
if (bd == null)
return Env.ZERO;
return bd;
}
|
/** Set Description.
@param Description
Optional short description of the record
*/
public void setDescription (String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Description.
@return Optional short description of the record
*/
public String getDescription ()
{
return (String)get_Value(COLUMNNAME_Description);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Spread.java
| 1
|
请完成以下Java代码
|
public class DistributionFacetsCollection implements Iterable<DistributionFacet>
{
private static final DistributionFacetsCollection EMPTY = new DistributionFacetsCollection(ImmutableSet.of());
private final ImmutableSet<DistributionFacet> set;
private DistributionFacetsCollection(@NonNull final ImmutableSet<DistributionFacet> set)
{
this.set = set;
}
public static DistributionFacetsCollection ofCollection(final Collection<DistributionFacet> collection)
{
return !collection.isEmpty() ? new DistributionFacetsCollection(ImmutableSet.copyOf(collection)) : EMPTY;
}
@Override
@NonNull
public Iterator<DistributionFacet> iterator() {return set.iterator();}
public boolean isEmpty() {return set.isEmpty();}
public WorkflowLaunchersFacetGroupList toWorkflowLaunchersFacetGroupList(@Nullable ImmutableSet<WorkflowLaunchersFacetId> activeFacetIds)
{
if (isEmpty())
{
return WorkflowLaunchersFacetGroupList.EMPTY;
}
final HashMap<WorkflowLaunchersFacetGroupId, WorkflowLaunchersFacetGroupBuilder> groupBuilders = new HashMap<>();
for (final DistributionFacet distributionFacet : set)
{
final WorkflowLaunchersFacet facet = distributionFacet.toWorkflowLaunchersFacet(activeFacetIds);
|
groupBuilders.computeIfAbsent(facet.getGroupId(), k -> distributionFacet.newWorkflowLaunchersFacetGroupBuilder())
.facet(facet);
}
final ImmutableList<WorkflowLaunchersFacetGroup> groups = groupBuilders.values()
.stream()
.map(WorkflowLaunchersFacetGroupBuilder::build)
.sorted(orderByGroupSeqNo())
.collect(ImmutableList.toImmutableList());
return WorkflowLaunchersFacetGroupList.ofList(groups);
}
private static Comparator<? super WorkflowLaunchersFacetGroup> orderByGroupSeqNo()
{
return Comparator.comparingInt(DistributionFacetsCollection::getGroupSeqNo);
}
private static int getGroupSeqNo(final WorkflowLaunchersFacetGroup group)
{
return DistributionFacetGroupType.ofWorkflowLaunchersFacetGroupId(group.getId()).getSeqNo();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetsCollection.java
| 1
|
请完成以下Java代码
|
public class RestartProcessInstancesJobHandler extends AbstractBatchJobHandler<RestartProcessInstancesBatchConfiguration>{
public static final BatchJobDeclaration JOB_DECLARATION = new BatchJobDeclaration(Batch.TYPE_PROCESS_INSTANCE_RESTART);
@Override
public String getType() {
return Batch.TYPE_PROCESS_INSTANCE_RESTART;
}
@Override
protected void postProcessJob(RestartProcessInstancesBatchConfiguration configuration, JobEntity job, RestartProcessInstancesBatchConfiguration jobConfiguration) {
if (job.getDeploymentId() == null) {
CommandContext commandContext = Context.getCommandContext();
ProcessDefinitionEntity processDefinitionEntity = commandContext.getProcessEngineConfiguration().getDeploymentCache()
.findDeployedProcessDefinitionById(configuration.getProcessDefinitionId());
job.setDeploymentId(processDefinitionEntity.getDeploymentId());
}
}
@Override
public void executeHandler(RestartProcessInstancesBatchConfiguration batchConfiguration,
ExecutionEntity execution,
CommandContext commandContext,
String tenantId) {
String processDefinitionId = batchConfiguration.getProcessDefinitionId();
RestartProcessInstanceBuilderImpl builder =
new RestartProcessInstanceBuilderImpl(processDefinitionId);
builder.processInstanceIds(batchConfiguration.getIds());
builder.setInstructions(batchConfiguration.getInstructions());
if (batchConfiguration.isInitialVariables()) {
builder.initialSetOfVariables();
}
if (batchConfiguration.isSkipCustomListeners()) {
builder.skipCustomListeners();
}
if (batchConfiguration.isWithoutBusinessKey()) {
builder.withoutBusinessKey();
}
if (batchConfiguration.isSkipIoMappings()) {
builder.skipIoMappings();
|
}
CommandExecutor commandExecutor = commandContext.getProcessEngineConfiguration()
.getCommandExecutorTxRequired();
commandContext.executeWithOperationLogPrevented(
new RestartProcessInstancesCmd(commandExecutor, builder));
}
@Override
public JobDeclaration<BatchJobContext, MessageEntity> getJobDeclaration() {
return JOB_DECLARATION;
}
@Override
protected RestartProcessInstancesBatchConfiguration createJobConfiguration(RestartProcessInstancesBatchConfiguration configuration,
List<String> processIdsForJob) {
return new RestartProcessInstancesBatchConfiguration(processIdsForJob, configuration.getInstructions(), configuration.getProcessDefinitionId(),
configuration.isInitialVariables(), configuration.isSkipCustomListeners(), configuration.isSkipIoMappings(), configuration.isWithoutBusinessKey());
}
@Override
protected RestartProcessInstancesBatchConfigurationJsonConverter getJsonConverterInstance() {
return RestartProcessInstancesBatchConfigurationJsonConverter.INSTANCE;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RestartProcessInstancesJobHandler.java
| 1
|
请完成以下Java代码
|
public String getAnchorValue() {
return null;
}
@Override
public String getFillValue() {
return "#585858";
}
@Override
public String getStyleValue() {
return "stroke-width:1.4;stroke-miterlimit:4;stroke-dasharray:none";
}
@Override
public String getDValue() {
return " M7.7124971 20.247342 L22.333334 20.247342 L15.022915000000001 7.575951200000001 L7.7124971 20.247342 z";
}
@Override
public void drawIcon(int imageX, int imageY, int iconPadding, ProcessDiagramSVGGraphics2D svgGenerator) {
Element gTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_G_TAG);
gTag.setAttributeNS(null, "transform", "translate(" + (imageX - 7) + "," + (imageY - 7) + ")");
Element pathTag = svgGenerator.getDOMFactory().createElementNS(null, SVGGraphics2D.SVG_PATH_TAG);
pathTag.setAttributeNS(null, "d", this.getDValue());
pathTag.setAttributeNS(null, "style", this.getStyleValue());
pathTag.setAttributeNS(null, "fill", this.getFillValue());
|
pathTag.setAttributeNS(null, "stroke", this.getStrokeValue());
gTag.appendChild(pathTag);
svgGenerator.getExtendDOMGroupManager().addElement(gTag);
}
@Override
public String getStrokeValue() {
return "#585858";
}
@Override
public String getStrokeWidth() {
return null;
}
}
|
repos\Activiti-develop\activiti-core\activiti-image-generator\src\main\java\org\activiti\image\impl\icon\SignalThrowIconType.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getElementId() {
return elementId;
}
public void setElementId(String elementId) {
this.elementId = elementId;
}
public String getElementName() {
return elementName;
}
public void setElementName(String elementName) {
this.elementName = elementName;
}
public Integer getRetries() {
return retries;
}
public void setRetries(Integer retries) {
this.retries = retries;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public void setExceptionMessage(String exceptionMessage) {
this.exceptionMessage = exceptionMessage;
}
public Date getDueDate() {
return dueDate;
}
public void setDueDate(Date dueDate) {
this.dueDate = dueDate;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
|
}
public String getTenantId() {
return tenantId;
}
public String getLockOwner() {
return lockOwner;
}
public void setLockOwner(String lockOwner) {
this.lockOwner = lockOwner;
}
public Date getLockExpirationTime() {
return lockExpirationTime;
}
public void setLockExpirationTime(Date lockExpirationTime) {
this.lockExpirationTime = lockExpirationTime;
}
}
|
repos\flowable-engine-main\modules\flowable-external-job-rest\src\main\java\org\flowable\external\job\rest\service\api\query\ExternalWorkerJobResponse.java
| 2
|
请完成以下Java代码
|
public static long distance(CommonSynonymDictionary.SynonymItem itemA, CommonSynonymDictionary.SynonymItem itemB)
{
return itemA.distance(itemB);
}
/**
* 将分词结果转换为同义词列表
* @param sentence 句子
* @param withUndefinedItem 是否保留词典中没有的词语
* @return
*/
public static List<Long[]> convert(List<Term> sentence, boolean withUndefinedItem)
{
List<Long[]> synonymItemList = new ArrayList<Long[]>(sentence.size());
for (Term term : sentence)
{
// 除掉停用词
if (term.nature == null) continue;
String nature = term.nature.toString();
char firstChar = nature.charAt(0);
switch (firstChar)
{
case 'm':
{
if (!TextUtility.isAllChinese(term.word)) continue;
}break;
case 'w':
{
continue;
}
}
// 停用词
if (CoreStopWordDictionary.contains(term.word)) continue;
Long[] item = get(term.word);
// logger.trace("{} {}", wordResult.word, Arrays.toString(item));
if (item == null)
{
if (withUndefinedItem)
{
item = new Long[]{Long.MAX_VALUE / 3};
synonymItemList.add(item);
}
}
else
{
synonymItemList.add(item);
|
}
}
return synonymItemList;
}
/**
* 获取语义标签
* @return
*/
public static long[] getLexemeArray(List<CommonSynonymDictionary.SynonymItem> synonymItemList)
{
long[] array = new long[synonymItemList.size()];
int i = 0;
for (CommonSynonymDictionary.SynonymItem item : synonymItemList)
{
array[i++] = item.entry.id;
}
return array;
}
public long distance(List<CommonSynonymDictionary.SynonymItem> synonymItemListA, List<CommonSynonymDictionary.SynonymItem> synonymItemListB)
{
return EditDistance.compute(synonymItemListA, synonymItemListB);
}
public long distance(long[] arrayA, long[] arrayB)
{
return EditDistance.compute(arrayA, arrayB);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\dictionary\CoreSynonymDictionaryEx.java
| 1
|
请完成以下Java代码
|
public class ConsistentHashCircle<T> {
private final ConcurrentNavigableMap<Long, T> circle = new ConcurrentSkipListMap<>();
public void put(long hash, T instance) {
circle.put(hash, instance);
}
public void remove(long hash) {
circle.remove(hash);
}
public boolean isEmpty() {
return circle.isEmpty();
}
public boolean containsKey(Long hash) {
return circle.containsKey(hash);
}
public ConcurrentNavigableMap<Long, T> tailMap(Long hash) {
|
return circle.tailMap(hash);
}
public Long firstKey() {
return circle.firstKey();
}
public T get(Long hash) {
return circle.get(hash);
}
public void log() {
circle.forEach((key, value) -> log.debug("{} -> {}", key, value));
}
}
|
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\discovery\ConsistentHashCircle.java
| 1
|
请完成以下Java代码
|
public java.lang.String getTypeMRP ()
{
return (java.lang.String)get_Value(COLUMNNAME_TypeMRP);
}
/** Set Suchschlüssel.
@param Value
Search key for the record in the format required - must be unique
*/
@Override
public void setValue (java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
/** Get Suchschlüssel.
@return Search key for the record in the format required - must be unique
*/
@Override
public java.lang.String getValue ()
{
return (java.lang.String)get_Value(COLUMNNAME_Value);
}
/** Set Version.
@param Version
Version of the table definition
*/
@Override
public void setVersion (java.math.BigDecimal Version)
{
|
set_Value (COLUMNNAME_Version, Version);
}
/** Get Version.
@return Version of the table definition
*/
@Override
public java.math.BigDecimal getVersion ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Version);
if (bd == null)
return Env.ZERO;
return bd;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_PP_MRP.java
| 1
|
请完成以下Java代码
|
public class User {
private Integer id;
private String name;
private String address;
private String mobile;
private String email;
private Date createTime;
private Integer role;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getEmail() {
|
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getCreateTime() {
return createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
public Integer getRole() {
return role;
}
public void setRole(Integer role) {
this.role = role;
}
}
|
repos\springBoot-master\springboot-dynamicDataSource\src\main\java\cn\abel\bean\User.java
| 1
|
请完成以下Java代码
|
private static Map<String, String> computeNewParametersIfChanged(
@NonNull final Map<CtxName, String> usedParameters,
@NonNull final IUserRolePermissions userRolePermissions)
{
if (usedParameters.isEmpty())
{
return null;
}
HashMap<String, String> newParameters = null; // lazy, instantiated only if needed
for (final Map.Entry<CtxName, String> usedParameterEntry : usedParameters.entrySet())
{
final CtxName usedParameterName = usedParameterEntry.getKey();
if (CTXNAME_AD_Role_Group.equalsByName(usedParameterName))
{
final String usedValue = normalizeRoleGroupValue(usedParameterEntry.getValue());
final String newValue = normalizeRoleGroupValue(userRolePermissions.getRoleGroup() != null ? userRolePermissions.getRoleGroup().getName() : null);
if (!Objects.equals(usedValue, newValue))
{
newParameters = newParameters == null ? copyToNewParameters(usedParameters) : newParameters;
newParameters.put(CTXNAME_AD_Role_Group.getName(), newValue);
}
}
}
return newParameters;
}
private static String normalizeRoleGroupValue(String roleGroupValue)
{
String result = LogicExpressionEvaluator.stripQuotes(roleGroupValue);
result = StringUtils.trimBlankToNull(result);
return result != null ? result : "";
}
@NonNull
private static HashMap<String, String> copyToNewParameters(final @NonNull Map<CtxName, String> usedParameters)
{
final HashMap<String, String> newParameters = new HashMap<>(usedParameters.size());
|
for (Map.Entry<CtxName, String> entry : usedParameters.entrySet())
{
newParameters.put(entry.getKey().getName(), entry.getValue());
}
return newParameters;
}
private static LogicExpressionResult revaluate(
@NonNull final LogicExpressionResult result,
@NonNull final Map<String, String> newParameters)
{
try
{
return result.getExpression().evaluateToResult(Evaluatees.ofMap(newParameters), IExpressionEvaluator.OnVariableNotFound.Fail);
}
catch (final Exception ex)
{
// shall not happen
logger.warn("Failed evaluating expression using `{}`. Returning previous result: {}", newParameters, result, ex);
return result;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\model\DocumentFieldLogicExpressionResultRevaluator.java
| 1
|
请完成以下Java代码
|
public int getPrice_UOM_ID()
{
return get_ValueAsInt(COLUMNNAME_Price_UOM_ID);
}
@Override
public void setQty (final @Nullable BigDecimal Qty)
{
set_Value (COLUMNNAME_Qty, Qty);
}
@Override
public BigDecimal getQty()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setQtyEnteredInPriceUOM (final @Nullable BigDecimal QtyEnteredInPriceUOM)
{
|
set_Value (COLUMNNAME_QtyEnteredInPriceUOM, QtyEnteredInPriceUOM);
}
@Override
public BigDecimal getQtyEnteredInPriceUOM()
{
final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyEnteredInPriceUOM);
return bd != null ? bd : BigDecimal.ZERO;
}
@Override
public void setSeqNo (final int SeqNo)
{
set_Value (COLUMNNAME_SeqNo, SeqNo);
}
@Override
public int getSeqNo()
{
return get_ValueAsInt(COLUMNNAME_SeqNo);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Invoice_Detail.java
| 1
|
请完成以下Java代码
|
public class SpinValues {
public static JsonValueBuilder jsonValue(SpinJsonNode value) {
return jsonValue(value, false);
}
public static JsonValueBuilder jsonValue(String value) {
return jsonValue(value, false);
}
public static JsonValueBuilder jsonValue(SpinJsonNode value, boolean isTransient) {
return (JsonValueBuilder) new JsonValueBuilderImpl(value).setTransient(isTransient);
}
public static JsonValueBuilder jsonValue(String value, boolean isTransient) {
return (JsonValueBuilder) new JsonValueBuilderImpl(value).setTransient(isTransient);
}
public static XmlValueBuilder xmlValue(SpinXmlElement value) {
|
return xmlValue(value, false);
}
public static XmlValueBuilder xmlValue(String value) {
return xmlValue(value, false);
}
public static XmlValueBuilder xmlValue(SpinXmlElement value, boolean isTransient) {
return (XmlValueBuilder) new XmlValueBuilderImpl(value).setTransient(isTransient);
}
public static XmlValueBuilder xmlValue(String value, boolean isTransient) {
return (XmlValueBuilder) new XmlValueBuilderImpl(value).setTransient(isTransient);
}
}
|
repos\camunda-bpm-platform-master\engine-plugins\spin-plugin\src\main\java\org\camunda\spin\plugin\variable\SpinValues.java
| 1
|
请完成以下Java代码
|
public Void execute(CommandContext commandContext) {
if (processInstanceId == null) {
throw new ActivitiIllegalArgumentException("processInstanceId is null");
}
ExecutionEntity execution = commandContext
.getExecutionEntityManager()
.findExecutionById(processInstanceId);
if (execution == null) {
throw new ActivitiObjectNotFoundException("process instance " + processInstanceId + " doesn't exist", ProcessInstance.class);
}
if (!execution.isProcessInstanceType()) {
throw new ActivitiObjectNotFoundException("process instance " + processInstanceId +
" doesn't exist, the given ID references an execution, though", ProcessInstance.class);
}
|
if (execution.isSuspended()) {
throw new ActivitiException("process instance " + processInstanceId + " is suspended, cannot set name");
}
// Actually set the name
execution.setName(name);
// Record the change in history
commandContext.getHistoryManager().recordProcessInstanceNameChange(processInstanceId, name);
return null;
}
}
|
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\cmd\SetProcessInstanceNameCmd.java
| 1
|
请完成以下Java代码
|
public void exceptionWhileRollingBackOperation(Exception e) {
logError(
"042",
"Exception while rolling back operation",
e);
}
public ProcessEngineException exceptionWhilePerformingOperationStep(String opName, String stepName, Exception e) {
return new ProcessEngineException(exceptionMessage(
"043",
"Exception while performing '{}' => '{}': {}", opName, stepName, e.getMessage()), e);
}
public void exceptionWhilePerformingOperationStep(String name, Exception e) {
logError(
"044",
"Exception while performing '{}': {}", name, e.getMessage(), e);
}
public void debugRejectedExecutionException(RejectedExecutionException e) {
logDebug(
"045",
"RejectedExecutionException while scheduling work", e);
}
public void foundTomcatDeploymentDescriptor(String bpmPlatformFileLocation, String fileLocation) {
logInfo(
"046",
"Found Camunda Platform configuration in CATALINA_BASE/CATALINA_HOME conf directory [{}] at '{}'", bpmPlatformFileLocation, fileLocation);
}
|
public ProcessEngineException invalidDeploymentDescriptorLocation(String bpmPlatformFileLocation, MalformedURLException e) {
throw new ProcessEngineException(exceptionMessage(
"047",
"'{} is not a valid Camunda Platform configuration resource location.", bpmPlatformFileLocation), e);
}
public void camundaBpmPlatformSuccessfullyStarted(String serverInfo) {
logInfo(
"048",
"Camunda Platform sucessfully started at '{}'.", serverInfo);
}
public void camundaBpmPlatformStopped(String serverInfo) {
logInfo(
"049",
"Camunda Platform stopped at '{}'", serverInfo);
}
public void paDeployed(String name) {
logInfo(
"050",
"Process application {} successfully deployed", name);
}
public void paUndeployed(String name) {
logInfo(
"051",
"Process application {} undeployed", name);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\ContainerIntegrationLogger.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OrderController {
private final OrderService orderService;
@Autowired
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
@PostMapping(produces = MediaType.APPLICATION_JSON_VALUE, consumes = MediaType.APPLICATION_JSON_VALUE)
CreateOrderResponse createOrder(@RequestBody final CreateOrderRequest createOrderRequest) {
final UUID id = orderService.createOrder(createOrderRequest.getProduct());
return new CreateOrderResponse(id);
}
|
@PostMapping(value = "/{id}/products", consumes = MediaType.APPLICATION_JSON_VALUE)
void addProduct(@PathVariable final UUID id, @RequestBody final AddProductRequest addProductRequest) {
orderService.addProduct(id, addProductRequest.getProduct());
}
@DeleteMapping(value = "/{id}/products", consumes = MediaType.APPLICATION_JSON_VALUE)
void deleteProduct(@PathVariable final UUID id, @RequestParam final UUID productId) {
orderService.deleteProduct(id, productId);
}
@PostMapping("/{id}/complete")
void completeOrder(@PathVariable final UUID id) {
orderService.completeOrder(id);
}
}
|
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddhexagonalspring\application\rest\OrderController.java
| 2
|
请完成以下Java代码
|
public void save(I_M_Inventory inventory)
{
saveRecord(inventory);
}
@Override
public void save(I_M_InventoryLine inventoryLine)
{
saveRecord(inventoryLine);
}
@Override
public List<I_M_Inventory> list(@NonNull InventoryQuery query)
{
return toSqlQuery(query).list();
}
@Override
|
public Stream<I_M_Inventory> stream(@NonNull InventoryQuery query)
{
return toSqlQuery(query).stream();
}
private IQuery<I_M_Inventory> toSqlQuery(@NonNull InventoryQuery query)
{
return queryBL.createQueryBuilder(I_M_Inventory.class)
.orderBy(I_M_Inventory.COLUMN_MovementDate)
.orderBy(I_M_Inventory.COLUMN_M_Inventory_ID)
.setLimit(query.getLimit())
.addOnlyActiveRecordsFilter()
.addInArrayFilter(I_M_Inventory.COLUMNNAME_AD_User_Responsible_ID, query.getOnlyResponsibleIds())
.addInArrayFilter(I_M_Inventory.COLUMNNAME_M_Warehouse_ID, query.getOnlyWarehouseIds())
.addInArrayFilter(I_M_Inventory.COLUMNNAME_DocStatus, query.getOnlyDocStatuses())
.create();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\impl\InventoryDAO.java
| 1
|
请完成以下Java代码
|
public R apply(final T input)
{
return values.computeIfAbsent(keyFunction.apply(input), k -> delegate.apply(input));
}
@Override
public R peek(final T input)
{
return values.get(keyFunction.apply(input));
}
@Override
public void forget()
{
values.clear();
}
}
private static class MemoizingLastCallFunction<T, R, K> implements MemoizingFunction<T, R>
{
private final Function<T, R> delegate;
private final Function<T, K> keyFunction;
private final ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private transient volatile K lastKey;
private transient R lastValue;
private MemoizingLastCallFunction(final Function<T, R> delegate, final Function<T, K> keyFunction)
{
Check.assumeNotNull(delegate, "Parameter function is not null");
Check.assumeNotNull(keyFunction, "Parameter keyFunction is not null");
this.delegate = delegate;
this.keyFunction = keyFunction;
}
@Override
public String toString()
{
return MoreObjects.toStringHelper("memoizing-last-call")
.addValue(delegate)
.toString();
}
@Override
public R apply(final T input)
{
final K key = keyFunction.apply(input);
lock.readLock().lock();
boolean readLockAcquired = true;
boolean writeLockAcquired = false;
try
{
if (Objects.equals(lastKey, key))
{
return lastValue;
}
// Upgrade to write lock
lock.readLock().unlock(); // must release read lock before acquiring write lock
readLockAcquired = false;
lock.writeLock().lock();
writeLockAcquired = true;
try
{
lastValue = delegate.apply(input);
lastKey = key;
return lastValue;
}
finally
{
// Downgrade to read lock
lock.readLock().lock(); // acquire read lock before releasing write lock
readLockAcquired = true;
lock.writeLock().unlock(); // unlock write, still hold read
writeLockAcquired = false;
}
|
}
finally
{
if (writeLockAcquired)
{
lock.writeLock().unlock();
}
if (readLockAcquired)
{
lock.readLock().unlock();
}
}
}
@Override
public R peek(final T input)
{
final ReadLock readLock = lock.readLock();
readLock.lock();
try
{
return lastValue;
}
finally
{
readLock.unlock();
}
}
@Override
public void forget()
{
final WriteLock writeLock = lock.writeLock();
writeLock.lock();
try
{
lastKey = null;
lastValue = null;
}
finally
{
writeLock.unlock();
}
}
}
private static final class SimpleMemoizingFunction<T, R> extends MemoizingFunctionWithKeyExtractor<T, R, T>
{
private SimpleMemoizingFunction(final Function<T, R> delegate)
{
super(delegate, input -> input);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\Functions.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class OrderCostTypeRepository
{
private final IQueryBL queryBL = Services.get(IQueryBL.class);
private final CCache<Integer, OrderCostTypeMap> cache = CCache.<Integer, OrderCostTypeMap>builder()
.tableName(I_C_Cost_Type.Table_Name)
.initialCapacity(1)
.build();
public OrderCostType getById(@NonNull OrderCostTypeId id)
{
return getMap().getById(id);
}
private OrderCostTypeMap getMap()
{
return cache.getOrLoad(0, this::retrieveMap);
}
private OrderCostTypeMap retrieveMap()
{
final ImmutableList<OrderCostType> list = queryBL.createQueryBuilder(I_C_Cost_Type.class)
.addOnlyActiveRecordsFilter()
.create()
.stream()
.map(OrderCostTypeRepository::fromRecord)
.collect(ImmutableList.toImmutableList());
return new OrderCostTypeMap(list);
}
private static OrderCostType fromRecord(@NonNull final I_C_Cost_Type record)
|
{
return OrderCostType.builder()
.id(OrderCostTypeId.ofRepoId(record.getC_Cost_Type_ID()))
.code(record.getValue())
.name(record.getName())
.distributionMethod(CostDistributionMethod.ofCode(record.getCostDistributionMethod()))
.calculationMethod(CostCalculationMethod.ofCode(record.getCostCalculationMethod()))
.costElementId(CostElementId.ofRepoId(record.getM_CostElement_ID()))
.invoiceableProductId(record.isAllowInvoicing() ? ProductId.ofRepoId(record.getM_Product_ID()) : null)
.build();
}
//
//
//
private static class OrderCostTypeMap
{
private final ImmutableMap<OrderCostTypeId, OrderCostType> byId;
public OrderCostTypeMap(final ImmutableList<OrderCostType> list)
{
this.byId = Maps.uniqueIndex(list, OrderCostType::getId);
}
public OrderCostType getById(@NonNull final OrderCostTypeId id)
{
return Check.assumeNotNull(byId.get(id), "No cost type found for {}", id);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\costs\OrderCostTypeRepository.java
| 2
|
请完成以下Java代码
|
public class TbAzureIotHubNode extends TbMqttNode {
private Clock clock = Clock.systemUTC();
@Override
public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException {
super.init(ctx);
this.mqttNodeConfiguration = TbNodeUtils.convert(configuration, TbMqttNodeConfiguration.class);
try {
mqttNodeConfiguration.setPort(8883);
mqttNodeConfiguration.setCleanSession(true);
ClientCredentials credentials = mqttNodeConfiguration.getCredentials();
if (CredentialsType.CERT_PEM == credentials.getType()) {
CertPemCredentials pemCredentials = (CertPemCredentials) credentials;
if (pemCredentials.getCaCert() == null || pemCredentials.getCaCert().isEmpty()) {
pemCredentials.setCaCert(AzureIotHubUtil.getDefaultCaCert());
}
}
this.mqttClient = initAzureClient(ctx);
} catch (Exception e) {
throw new TbNodeException(e);
}
}
protected void prepareMqttClientConfig(MqttClientConfig config) {
config.setUsername(AzureIotHubUtil.buildUsername(mqttNodeConfiguration.getHost(), config.getClientId()));
ClientCredentials credentials = mqttNodeConfiguration.getCredentials();
if (CredentialsType.SAS == credentials.getType()) {
config.setPassword(AzureIotHubUtil.buildSasToken(mqttNodeConfiguration.getHost(), ((AzureIotHubSasCredentials) credentials).getSasKey(), clock));
}
}
|
MqttClient initAzureClient(TbContext ctx) throws Exception {
return initClient(ctx);
}
@VisibleForTesting
void setClock(Clock clock) {
this.clock = clock;
}
@Override
public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
boolean hasChanges = false;
switch (fromVersion) {
case 0:
String protocolVersion = "protocolVersion";
if (!oldConfiguration.has(protocolVersion)) {
hasChanges = true;
((ObjectNode) oldConfiguration).put(protocolVersion, MqttVersion.MQTT_3_1_1.name());
}
break;
default:
break;
}
return new TbPair<>(hasChanges, oldConfiguration);
}
}
|
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\mqtt\azure\TbAzureIotHubNode.java
| 1
|
请完成以下Java代码
|
public Integer getId() {
return id;
}
/**
* 设置 主键ID.
*
* @param id 主键ID.
*/
public void setId(Integer id) {
this.id = id;
}
/**
* 获取 管理用户ID.
*
* @return 管理用户ID.
*/
public Integer getManagerId() {
return managerId;
}
/**
* 设置 管理用户ID.
*
* @param managerId 管理用户ID.
*/
public void setManagerId(Integer managerId) {
this.managerId = managerId;
}
/**
* 获取 角色ID.
*
* @return 角色ID.
*/
public Integer getRoleId() {
return roleId;
}
/**
* 设置 角色ID.
*
* @param roleId 角色ID.
*/
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
/**
* 获取 创建时间.
*
* @return 创建时间.
|
*/
public Date getCreatedTime() {
return createdTime;
}
/**
* 设置 创建时间.
*
* @param createdTime 创建时间.
*/
public void setCreatedTime(Date createdTime) {
this.createdTime = createdTime;
}
/**
* 获取 更新时间.
*
* @return 更新时间.
*/
public Date getUpdatedTime() {
return updatedTime;
}
/**
* 设置 更新时间.
*
* @param updatedTime 更新时间.
*/
public void setUpdatedTime(Date updatedTime) {
this.updatedTime = updatedTime;
}
protected Serializable pkVal() {
return this.id;
}
}
|
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\ManagerRole.java
| 1
|
请完成以下Java代码
|
public void setModel(final ISideActionsGroupModel model)
{
if (this.model == model)
{
return;
}
//
// Un-bind listeners from old model
if (this.model != null)
{
this.model.getActions().removeListDataListener(modelListener);
}
//
// Set new model and refresh
this.model = model;
renderAll();
//
// Bind listeners to new model
if (this.model != null)
{
setTitle(this.model.getTitle());
setCollapsed(this.model.isDefaultCollapsed());
this.model.getActions().addListDataListener(modelListener);
}
}
public ISideActionsGroupModel getModel()
{
return model;
}
private Container getActionsPanel()
{
if (_actionsPanel == null)
{
final Container contentPane = getContentPane();
contentPane.setLayout(new MigLayout("fill, flowy"));
_actionsPanel = contentPane;
}
return _actionsPanel;
}
private void renderAll()
{
final Container actionsPanel = getActionsPanel();
actionsPanel.removeAll();
if (model != null)
{
final ListModel<ISideAction> actionsList = model.getActions();
for (int i = 0; i < actionsList.getSize(); i++)
{
final ISideAction action = actionsList.getElementAt(i);
final Component actionComp = createActionComponent(action);
actionsPanel.add(actionComp);
}
}
refreshUI();
}
|
private Component createActionComponent(final ISideAction action)
{
final SideActionType type = action.getType();
if (type == SideActionType.Toggle)
{
return new CheckableSideActionComponent(action);
}
else if (type == SideActionType.ExecutableAction)
{
return new HyperlinkSideActionComponent(action);
}
else if (type == SideActionType.Label)
{
return new LabelSideActionComponent(action);
}
else
{
throw new IllegalArgumentException("Unknown action type: " + type);
}
}
protected void updateActionComponent(final Component actionComp, final ISideAction action)
{
// TODO Auto-generated method stub
}
private final boolean hasActions()
{
return model != null && model.getActions().getSize() > 0;
}
private final void refreshUI()
{
// Auto-hide if no actions
setVisible(hasActions());
final Container actionsPanel = getActionsPanel();
actionsPanel.revalidate();
}
@Override
public void setVisible(final boolean visible)
{
final boolean visibleOld = isVisible();
super.setVisible(visible);
firePropertyChange(PROPERTY_Visible, visibleOld, isVisible());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\sideactions\swing\SideActionsGroupPanel.java
| 1
|
请完成以下Java代码
|
public void focusGained(FocusEvent e)
{
}
/**
* Mostly copied from {@link VLookup}, can't claim I really understand it.
*/
@Override
public void focusLost(FocusEvent e)
{
if (e.isTemporary())
{
return;
}
if (m_button == null // guarding against NPE (i.e. component was disposed in meantime)
|| !m_button.isEnabled()) // set by actionButton
{
return;
}
if (m_mAccount == null)
{
return;
}
// metas: begin: 02029: nerviges verhalten wenn man eine Maskeneingabe abbrechen will (2011082210000084)
// Check if toolbar Ignore button was pressed
if (e.getOppositeComponent() instanceof AbstractButton)
{
final AbstractButton b = (AbstractButton)e.getOppositeComponent();
if (APanel.CMD_Ignore.equals(b.getActionCommand()))
{
return;
}
}
// metas: end
if (m_text == null)
return; // arhipac: teo_sarca: already disposed
// Test Case: Open a window, click on account field that is mandatory but not filled, close the window and you will get an NPE
// TODO: integrate to trunk
// New text
String newText = m_text.getText();
if (newText == null)
newText = "";
// Actual text
|
String actualText = m_mAccount.getDisplay(m_value);
if (actualText == null)
actualText = "";
// If text was modified, try to resolve the valid combination
if (!newText.equals(actualText))
{
cmd_text();
}
}
@Override
public boolean isAutoCommit()
{
return true;
}
@Override
public ICopyPasteSupportEditor getCopyPasteSupport()
{
return m_text == null ? NullCopyPasteSupportEditor.instance : m_text.getCopyPasteSupport();
}
} // VAccount
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VAccount.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class AuthenticationManagerFactoryBean implements FactoryBean<AuthenticationManager>, BeanFactoryAware {
private BeanFactory bf;
private ObservationRegistry observationRegistry = ObservationRegistry.NOOP;
public static final String MISSING_BEAN_ERROR_MESSAGE = "Did you forget to add a global <authentication-manager> element "
+ "to your configuration (with child <authentication-provider> elements)? Alternatively you can use the "
+ "authentication-manager-ref attribute on your <http> and <global-method-security> elements.";
@Override
public AuthenticationManager getObject() throws Exception {
try {
return (AuthenticationManager) this.bf.getBean(BeanIds.AUTHENTICATION_MANAGER);
}
catch (NoSuchBeanDefinitionException ex) {
if (!BeanIds.AUTHENTICATION_MANAGER.equals(ex.getBeanName())) {
throw ex;
}
UserDetailsService uds = this.bf.getBeanProvider(UserDetailsService.class).getIfUnique();
if (uds == null) {
throw new NoSuchBeanDefinitionException(BeanIds.AUTHENTICATION_MANAGER, MISSING_BEAN_ERROR_MESSAGE);
}
DaoAuthenticationProvider provider = new DaoAuthenticationProvider(uds);
PasswordEncoder passwordEncoder = this.bf.getBeanProvider(PasswordEncoder.class).getIfUnique();
if (passwordEncoder != null) {
provider.setPasswordEncoder(passwordEncoder);
}
provider.afterPropertiesSet();
ProviderManager manager = new ProviderManager(Arrays.asList(provider));
if (this.observationRegistry.isNoop()) {
|
return manager;
}
return new ObservationAuthenticationManager(this.observationRegistry, manager);
}
}
@Override
public Class<? extends AuthenticationManager> getObjectType() {
return ProviderManager.class;
}
@Override
public boolean isSingleton() {
return true;
}
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.bf = beanFactory;
}
public void setObservationRegistry(ObservationRegistry observationRegistry) {
this.observationRegistry = observationRegistry;
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\authentication\AuthenticationManagerFactoryBean.java
| 2
|
请完成以下Java代码
|
public class CustomURLConnection extends URLConnection {
private final String simulatedData = "This is the simulated data from the resource.";
private URL url;
private boolean connected = false;
private String headerValue = "SimulatedHeaderValue";
protected CustomURLConnection(URL url) {
super(url);
this.url = url;
}
@Override
public void connect() throws IOException {
connected = true;
System.out.println("Connection established to: " + url);
}
@Override
public InputStream getInputStream() throws IOException {
if (!connected) {
connect();
}
return new ByteArrayInputStream(simulatedData.getBytes());
}
|
@Override
public OutputStream getOutputStream() throws IOException {
ByteArrayOutputStream simulatedOutput = new ByteArrayOutputStream();
return simulatedOutput;
}
@Override
public int getContentLength() {
return simulatedData.length();
}
@Override
public String getHeaderField(String name) {
if ("SimulatedHeader".equalsIgnoreCase(name)) { // Example header name
return headerValue;
} else {
return null; // Header not found
}
}
}
|
repos\tutorials-master\core-java-modules\core-java-networking-4\src\main\java\com\baeldung\customurlconnection\CustomURLConnection.java
| 1
|
请完成以下Java代码
|
private static String dateToCsvString(@Nullable final LocalDate date)
{
if (date == null)
{
return "";
}
return date.format(DATE_FORMATTER);
}
private static String timeToString(@Nullable final LocalTime time)
{
if (time == null)
{
return "";
}
return time.format(TIME_FORMATTER);
}
private static String intToString(@NonNull final Optional<Integer> integer)
{
if (integer.isPresent())
{
return Integer.toString(integer.get());
}
return "";
}
private static String intToString(@Nullable final Integer integer)
{
if (integer == null)
{
return "";
}
return Integer.toString(integer);
}
|
private static String bigDecimalToString(@Nullable final BigDecimal bigDecimal)
{
if (bigDecimal == null)
{
return "";
}
return bigDecimal.toString();
}
private static String stringToString(@NonNull final Optional<String> string)
{
if (string.isPresent())
{
return string.get();
}
return "";
}
private String truncateCheckDigitFromParcelNo(@NonNull final String parcelNumber)
{
return StringUtils.trunc(parcelNumber, 11, TruncateAt.STRING_END);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\misc\Converters.java
| 1
|
请完成以下Java代码
|
public class DelegateExpressionHttpHandler implements HttpRequestHandler, HttpResponseHandler {
private static final long serialVersionUID = 1L;
protected Expression expression;
protected final List<FieldExtension> fieldExtensions;
public DelegateExpressionHttpHandler(Expression expression, List<FieldExtension> fieldDeclarations) {
this.expression = expression;
this.fieldExtensions = fieldDeclarations;
}
@Override
public void handleHttpRequest(VariableContainer execution, HttpRequest httpRequest, FlowableHttpClient client) {
Object delegate = DelegateExpressionUtil.resolveDelegateExpression(expression, execution, fieldExtensions);
if (delegate instanceof HttpRequestHandler) {
((HttpRequestHandler) delegate).handleHttpRequest(execution, httpRequest, client);
} else {
throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did not resolve to an implementation of " + HttpRequestHandler.class);
}
}
@Override
public void handleHttpResponse(VariableContainer execution, HttpResponse httpResponse) {
Object delegate = resolveDelegateExpression(expression, execution, fieldExtensions);
if (delegate instanceof HttpResponseHandler) {
((HttpResponseHandler) delegate).handleHttpResponse(execution, httpResponse);
} else {
throw new FlowableIllegalArgumentException("Delegate expression " + expression + " did not resolve to an implementation of " + HttpResponseHandler.class);
}
}
/**
* returns the expression text for this execution listener. Comes in handy if you want to check which listeners you already have.
*/
public String getExpressionText() {
return expression.getExpressionText();
|
}
public static Object resolveDelegateExpression(Expression expression,
VariableContainer variableScope, List<FieldExtension> fieldExtensions) {
// Note: we can't cache the result of the expression, because the
// execution can change: eg. delegateExpression='${mySpringBeanFactory.randomSpringBean()}'
Object delegate = expression.getValue(variableScope);
if (fieldExtensions != null && fieldExtensions.size() > 0) {
DelegateExpressionFieldInjectionMode injectionMode = CommandContextUtil.getCmmnEngineConfiguration().getDelegateExpressionFieldInjectionMode();
if (injectionMode == DelegateExpressionFieldInjectionMode.COMPATIBILITY) {
CmmnClassDelegate.applyFieldExtensions(fieldExtensions, delegate, true);
} else if (injectionMode == DelegateExpressionFieldInjectionMode.MIXED) {
CmmnClassDelegate.applyFieldExtensions(fieldExtensions, delegate, false);
}
}
return delegate;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\behavior\impl\http\handler\DelegateExpressionHttpHandler.java
| 1
|
请完成以下Java代码
|
public void setA_Split_Percent (BigDecimal A_Split_Percent)
{
set_Value (COLUMNNAME_A_Split_Percent, A_Split_Percent);
}
/** Get Split Percentage.
@return Split Percentage */
public BigDecimal getA_Split_Percent ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Split_Percent);
if (bd == null)
return Env.ZERO;
return bd;
}
public I_C_AcctSchema getC_AcctSchema() throws RuntimeException
{
return (I_C_AcctSchema)MTable.get(getCtx(), I_C_AcctSchema.Table_Name)
.getPO(getC_AcctSchema_ID(), get_TrxName()); }
/** Set Accounting Schema.
@param C_AcctSchema_ID
Rules for accounting
*/
public void setC_AcctSchema_ID (int C_AcctSchema_ID)
{
if (C_AcctSchema_ID < 1)
set_Value (COLUMNNAME_C_AcctSchema_ID, null);
else
set_Value (COLUMNNAME_C_AcctSchema_ID, Integer.valueOf(C_AcctSchema_ID));
}
/** Get Accounting Schema.
@return Rules for accounting
*/
public int getC_AcctSchema_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_C_AcctSchema_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** PostingType AD_Reference_ID=125 */
public static final int POSTINGTYPE_AD_Reference_ID=125;
/** Actual = A */
public static final String POSTINGTYPE_Actual = "A";
/** Budget = B */
public static final String POSTINGTYPE_Budget = "B";
/** Commitment = E */
public static final String POSTINGTYPE_Commitment = "E";
/** Statistical = S */
public static final String POSTINGTYPE_Statistical = "S";
/** Reservation = R */
|
public static final String POSTINGTYPE_Reservation = "R";
/** Set PostingType.
@param PostingType
The type of posted amount for the transaction
*/
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 Process Now.
@param Processing Process Now */
public void setProcessing (boolean Processing)
{
set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
}
/** Get Process Now.
@return Process Now */
public boolean isProcessing ()
{
Object oo = get_Value(COLUMNNAME_Processing);
if (oo != null)
{
if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue();
return "Y".equals(oo);
}
return false;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Acct.java
| 1
|
请完成以下Java代码
|
public UOMConversionRate invert()
{
if (fromUomId.equals(toUomId))
{
return this;
}
return UOMConversionRate.builder()
.fromUomId(toUomId)
.toUomId(fromUomId)
.fromToMultiplier(toFromMultiplier)
.toFromMultiplier(fromToMultiplier)
.build();
}
public boolean isOne()
{
return (fromToMultiplier == null || fromToMultiplier.compareTo(BigDecimal.ONE) == 0)
&& (toFromMultiplier == null || toFromMultiplier.compareTo(BigDecimal.ONE) == 0);
}
public BigDecimal getFromToMultiplier()
{
if (fromToMultiplier != null)
{
return fromToMultiplier;
}
else
{
return computeInvertedMultiplier(toFromMultiplier);
}
}
|
public static BigDecimal computeInvertedMultiplier(@NonNull final BigDecimal multiplier)
{
if (multiplier.signum() == 0)
{
throw new AdempiereException("Multiplier shall not be ZERO");
}
return NumberUtils.stripTrailingDecimalZeros(BigDecimal.ONE.divide(multiplier, 12, RoundingMode.HALF_UP));
}
public BigDecimal convert(@NonNull final BigDecimal qty, @NonNull final UOMPrecision precision)
{
if (qty.signum() == 0)
{
return qty;
}
if (fromToMultiplier != null)
{
return precision.round(qty.multiply(fromToMultiplier));
}
else
{
return qty.divide(toFromMultiplier, precision.toInt(), precision.getRoundingMode());
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\uom\UOMConversionRate.java
| 1
|
请完成以下Java代码
|
public class JaxbUtil
{
public static <T> JAXBElement<T> unmarshalToJaxbElement(
@NonNull final InputStream xmlInput,
@NonNull final Class<T> jaxbType)
{
try
{
final JAXBContext jaxbContext = JAXBContext.newInstance(jaxbType.getPackage().getName());
return unmarshal(jaxbContext, xmlInput);
}
catch (final JAXBException e)
{
throw new RuntimeException(e);
}
}
private static <T> JAXBElement<T> unmarshal(
@NonNull final JAXBContext jaxbContext,
@NonNull final InputStream xmlInput) throws JAXBException
{
final Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
@SuppressWarnings("unchecked")
final JAXBElement<T> jaxbElement = (JAXBElement<T>)unmarshaller.unmarshal(xmlInput);
return jaxbElement;
}
public static <T> void marshal(
@NonNull final JAXBElement<T> jaxbElement,
@NonNull final Class<T> jaxbType,
|
@NonNull final String xsdName,
@NonNull final OutputStream outputStream,
final boolean prettyPrint
)
{
try
{
final JAXBContext jaxbContext = JAXBContext.newInstance(jaxbType.getPackage().getName());
final Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_ENCODING, StandardCharsets.UTF_8.name());
marshaller.setProperty(Marshaller.JAXB_SCHEMA_LOCATION, xsdName); // important; for us, finding the correct converter depends on the schema location
if (prettyPrint)
{
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
}
// we want the XML header to have " (just like all the rest of the XML) and not '
// background: some systems that shall be able to work with our XML have issues with the single quote in the XML header
// https://stackoverflow.com/questions/18451870/altering-the-xml-header-produced-by-the-jaxb-marshaller/32892565
marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true); // let the marshaler *not* provide stupid single-quote header
marshaller.setProperty("com.sun.xml.internal.bind.xmlHeaders", "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"); // let the marshaller provide our header
marshaller.marshal(jaxbElement, outputStream);
}
catch (final JAXBException | FactoryConfigurationError e)
{
throw new RuntimeException(e);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_xversion\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_xversion\JaxbUtil.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the dateFunctionCodeQualifier property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDateFunctionCodeQualifier() {
return dateFunctionCodeQualifier;
}
/**
* Sets the value of the dateFunctionCodeQualifier property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDateFunctionCodeQualifier(String value) {
this.dateFunctionCodeQualifier = value;
}
/**
* Gets the value of the dateFormatCode property.
*
* @return
|
* possible object is
* {@link String }
*
*/
public String getDateFormatCode() {
return dateFormatCode;
}
/**
* Sets the value of the dateFormatCode property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDateFormatCode(String value) {
this.dateFormatCode = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ExtendedDateType.java
| 2
|
请完成以下Java代码
|
public void setTenantId(String tenantId) {
this.tenantId = tenantId;
}
@Override
public List<ProcessDefinition> getDeployedProcessDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(ProcessDefinitionEntity.class);
}
@Override
public List<CaseDefinition> getDeployedCaseDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(CaseDefinitionEntity.class);
}
@Override
public List<DecisionDefinition> getDeployedDecisionDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionDefinitionEntity.class);
}
@Override
public List<DecisionRequirementsDefinition> getDeployedDecisionRequirementsDefinitions() {
return deployedArtifacts == null ? null : deployedArtifacts.get(DecisionRequirementsDefinitionEntity.class);
}
|
@Override
public String toString() {
return this.getClass().getSimpleName()
+ "[id=" + id
+ ", name=" + name
+ ", resources=" + resources
+ ", deploymentTime=" + deploymentTime
+ ", validatingSchema=" + validatingSchema
+ ", isNew=" + isNew
+ ", source=" + source
+ ", tenantId=" + tenantId
+ "]";
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\DeploymentEntity.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class ObjectFactory {
/**
* Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: com.in28minutes.students
*
*/
public ObjectFactory() {
}
/**
* Create an instance of {@link GetStudentDetailsRequest }
*
*/
public GetStudentDetailsRequest createGetStudentDetailsRequest() {
return new GetStudentDetailsRequest();
}
|
/**
* Create an instance of {@link GetStudentDetailsResponse }
*
*/
public GetStudentDetailsResponse createGetStudentDetailsResponse() {
return new GetStudentDetailsResponse();
}
/**
* Create an instance of {@link StudentDetails }
*
*/
public StudentDetails createStudentDetails() {
return new StudentDetails();
}
}
|
repos\spring-boot-examples-master\spring-boot-tutorial-soap-web-services\src\main\java\com\in28minutes\students\ObjectFactory.java
| 2
|
请完成以下Java代码
|
public String getDisplay (final IValidationContext evalCtx, final Object value)
{
if (value == null)
return null;
MLocation loc = getLocation (value, ITrx.TRXNAME_None);
if (loc == null)
return "<" + value.toString() + ">";
return loc.toString();
} // getDisplay
/**
* Get Object of Key Value
* @param value value
* @return Object or null
*/
@Override
public NamePair get (final IValidationContext evalCtx, Object value)
{
if (value == null)
return null;
MLocation loc = getLocation (value, null);
if (loc == null)
return null;
return new KeyNamePair (loc.getC_Location_ID(), loc.toString());
} // get
/**
* The Lookup contains the key
* @param key Location_ID
* @return true if key known
*/
@Override
public boolean containsKey (final IValidationContext evalCtx, final Object key)
{
return getLocation(key, ITrx.TRXNAME_None) != null;
} // containsKey
/**************************************************************************
* Get Location
* @param key ID as string or integer
* @param trxName transaction
* @return Location
*/
public MLocation getLocation (Object key, String trxName)
{
if (key == null)
return null;
int C_Location_ID = 0;
if (key instanceof Integer)
C_Location_ID = ((Integer)key).intValue();
else if (key != null)
C_Location_ID = Integer.parseInt(key.toString());
//
return getLocation(C_Location_ID, trxName);
} // getLocation
/**
* Get Location
* @param C_Location_ID id
|
* @param trxName transaction
* @return Location
*/
public MLocation getLocation (int C_Location_ID, String trxName)
{
return MLocation.get(m_ctx, C_Location_ID, trxName);
} // getC_Location_ID
@Override
public String getTableName()
{
return I_C_Location.Table_Name;
}
@Override
public String getColumnName()
{
return I_C_Location.Table_Name + "." + I_C_Location.COLUMNNAME_C_Location_ID;
} // getColumnName
@Override
public String getColumnNameNotFQ()
{
return I_C_Location.COLUMNNAME_C_Location_ID;
}
/**
* Return data as sorted Array - not implemented
* @param mandatory mandatory
* @param onlyValidated only validated
* @param onlyActive only active
* @param temporary force load for temporary display
* @return null
*/
@Override
public List<Object> getData (boolean mandatory, boolean onlyValidated, boolean onlyActive, boolean temporary)
{
log.error("not implemented");
return null;
} // getArray
} // MLocation
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MLocationLookup.java
| 1
|
请完成以下Java代码
|
public void setAD_ReplicationStrategy(final org.compiere.model.I_AD_ReplicationStrategy AD_ReplicationStrategy)
{
set_ValueFromPO(COLUMNNAME_AD_ReplicationStrategy_ID, org.compiere.model.I_AD_ReplicationStrategy.class, AD_ReplicationStrategy);
}
@Override
public void setAD_ReplicationStrategy_ID (final int AD_ReplicationStrategy_ID)
{
if (AD_ReplicationStrategy_ID < 1)
set_Value (COLUMNNAME_AD_ReplicationStrategy_ID, null);
else
set_Value (COLUMNNAME_AD_ReplicationStrategy_ID, AD_ReplicationStrategy_ID);
}
@Override
public int getAD_ReplicationStrategy_ID()
{
return get_ValueAsInt(COLUMNNAME_AD_ReplicationStrategy_ID);
}
@Override
public void setDescription (final @Nullable java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
@Override
public java.lang.String getDescription()
{
return get_ValueAsString(COLUMNNAME_Description);
}
@Override
public void setIsEUOneStopShop (final boolean IsEUOneStopShop)
{
set_Value (COLUMNNAME_IsEUOneStopShop, IsEUOneStopShop);
}
@Override
public boolean isEUOneStopShop()
{
return get_ValueAsBoolean(COLUMNNAME_IsEUOneStopShop);
}
@Override
public void setIsSummary (final boolean IsSummary)
{
set_Value (COLUMNNAME_IsSummary, IsSummary);
}
@Override
|
public boolean isSummary()
{
return get_ValueAsBoolean(COLUMNNAME_IsSummary);
}
@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 java.lang.String Value)
{
set_Value (COLUMNNAME_Value, Value);
}
@Override
public java.lang.String getValue()
{
return get_ValueAsString(COLUMNNAME_Value);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Org.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void onOpen(@PathParam("key") String key, Session session) {
SESSION_POOLS.put(key, session);
log.info("[WebSocket] 连接成功,当前连接人数为:={}", SESSION_POOLS.size());
try {
session.getBasicRemote().sendText("Web socket 消息");
} catch (Exception e) {
log.error(e.getMessage(), e);
}
}
/**
* WebSocket请求关闭
*/
@OnClose
public void onClose(@PathParam("key") String key) {
SESSION_POOLS.remove(key);
log.info("WebSocket请求关闭");
}
@OnError
|
public void onError(Throwable thr) {
log.info("WebSocket 异常");
}
/**
* 收到客户端信息
*/
@OnMessage
public void onMessage(@PathParam("key") String key, String message, Session session) throws IOException {
message = "客户端:" + message + ",已收到";
session.getBasicRemote().sendText("Web socket 消息::" + message);
log.info(message);
}
}
|
repos\spring-boot-student-master\spring-boot-student-websocket\src\main\java\com\xiaolyuh\controller\WebSocketServerEndpoint.java
| 2
|
请完成以下Java代码
|
public java.sql.Timestamp getDateTo ()
{
return (java.sql.Timestamp)get_Value(COLUMNNAME_DateTo);
}
/** Set Beschreibung.
@param Description Beschreibung */
@Override
public void setDescription (java.lang.String Description)
{
set_Value (COLUMNNAME_Description, Description);
}
/** Get Beschreibung.
@return Beschreibung */
@Override
public java.lang.String getDescription ()
{
return (java.lang.String)get_Value(COLUMNNAME_Description);
}
/** Set Frequency.
@param Frequency
Frequency of events
*/
@Override
public void setFrequency (int Frequency)
{
set_Value (COLUMNNAME_Frequency, Integer.valueOf(Frequency));
}
/** Get Frequency.
@return Frequency of events
*/
@Override
public int getFrequency ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_Frequency);
if (ii == null)
return 0;
return ii.intValue();
}
/**
* FrequencyType AD_Reference_ID=540067
* Reference name: Recurrent Payment Frequency Type
*/
public static final int FREQUENCYTYPE_AD_Reference_ID=540067;
/** Day = D */
public static final String FREQUENCYTYPE_Day = "D";
/** Month = M */
public static final String FREQUENCYTYPE_Month = "M";
/** Set Frequency Type.
@param FrequencyType
Frequency of event
*/
@Override
public void setFrequencyType (java.lang.String FrequencyType)
{
set_Value (COLUMNNAME_FrequencyType, FrequencyType);
}
/** Get Frequency Type.
@return Frequency of event
*/
@Override
public java.lang.String getFrequencyType ()
{
return (java.lang.String)get_Value(COLUMNNAME_FrequencyType);
}
/** Set Next Payment Date.
@param NextPaymentDate Next Payment Date */
@Override
public void setNextPaymentDate (java.sql.Timestamp NextPaymentDate)
{
set_ValueNoCheck (COLUMNNAME_NextPaymentDate, NextPaymentDate);
}
/** Get Next Payment Date.
@return Next Payment Date */
@Override
public java.sql.Timestamp getNextPaymentDate ()
{
|
return (java.sql.Timestamp)get_Value(COLUMNNAME_NextPaymentDate);
}
/** Set Payment amount.
@param PayAmt
Amount being paid
*/
@Override
public void setPayAmt (java.math.BigDecimal PayAmt)
{
set_Value (COLUMNNAME_PayAmt, PayAmt);
}
/** Get Payment amount.
@return Amount being paid
*/
@Override
public java.math.BigDecimal getPayAmt ()
{
BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PayAmt);
if (bd == null)
return BigDecimal.ZERO;
return bd;
}
/** Set Aussendienst.
@param SalesRep_ID Aussendienst */
@Override
public void setSalesRep_ID (int SalesRep_ID)
{
if (SalesRep_ID < 1)
set_Value (COLUMNNAME_SalesRep_ID, null);
else
set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID));
}
/** Get Aussendienst.
@return Aussendienst */
@Override
public int getSalesRep_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID);
if (ii == null)
return 0;
return ii.intValue();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPaymentLine.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class HUProcessDescriptor
{
AdProcessId processId;
String internalName;
boolean provideAsUserAction;
boolean acceptOnlyTopLevelHUs;
@Getter(AccessLevel.NONE) ImmutableSet<HuUnitType> acceptHUUnitTypes;
@Builder
private HUProcessDescriptor(
@NonNull final AdProcessId processId,
@NonNull final String internalName,
final Boolean provideAsUserAction,
final Boolean acceptOnlyTopLevelHUs,
@Singular final Set<HuUnitType> acceptHUUnitTypes)
{
Check.assumeNotEmpty(acceptHUUnitTypes, "acceptHUUnitTypes is not empty");
this.processId = processId;
|
this.internalName = Check.assumeNotEmpty(internalName, "internalName is not empty");
this.acceptHUUnitTypes = ImmutableSet.copyOf(acceptHUUnitTypes);
this.provideAsUserAction = CoalesceUtil.coalesceNotNull(provideAsUserAction, true);
this.acceptOnlyTopLevelHUs = CoalesceUtil.coalesceNotNull(acceptOnlyTopLevelHUs, false);
}
public boolean appliesToHUUnitType(@NonNull final HuUnitType huUnitType)
{
return acceptHUUnitTypes.contains(huUnitType);
}
public boolean isMatching(@NonNull final HUToReport huToReport)
{
return (!acceptOnlyTopLevelHUs || huToReport.isTopLevel())
&& appliesToHUUnitType(huToReport.getHUUnitType());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\process\api\HUProcessDescriptor.java
| 2
|
请完成以下Java代码
|
public void fireRegisteredCustomizers(@NonNull final Connection c)
{
getRegisteredCustomizers().forEach(
customizer ->
{
invokeIfNotYetInvoked(customizer, c);
});
}
@Override
public String toString()
{
return "ConnectionCustomizerService [permanentCustomizers=" + permanentCustomizers + ", (thread-local-)temporaryCustomizers=" + temporaryCustomizers.get() + ", (thread-local-)currentlyInvokedCustomizers=" + currentlyInvokedCustomizers + "]";
}
private List<IConnectionCustomizer> getRegisteredCustomizers()
{
return new ImmutableList.Builder<IConnectionCustomizer>()
.addAll(permanentCustomizers)
.addAll(temporaryCustomizers.get())
.build();
}
|
/**
* Invoke {@link IConnectionCustomizer#customizeConnection(Connection)} with the given parameters, unless the customizer was already invoked within this thread and that invocation did not yet finish.
* So the goal is to avoid recursive invocations on the same customizer. Also see {@link IConnectionCustomizerService#fireRegisteredCustomizers(Connection)}.
*
* @param customizer
* @param connection
*/
private void invokeIfNotYetInvoked(@NonNull final IConnectionCustomizer customizer, @NonNull final Connection connection)
{
try
{
if (currentlyInvokedCustomizers.get().add(customizer))
{
customizer.customizeConnection(connection);
currentlyInvokedCustomizers.get().remove(customizer);
}
}
finally
{
currentlyInvokedCustomizers.get().remove(customizer);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\connection\impl\ConnectionCustomizerService.java
| 1
|
请完成以下Java代码
|
public void setMobilePhone(final String mobilePhone)
{
this.mobilePhone = mobilePhone;
this.mobilePhoneSet = true;
}
public void setDefaultContact(final Boolean defaultContact)
{
this.defaultContact = defaultContact;
this.defaultContactSet = true;
}
public void setShipToDefault(final Boolean shipToDefault)
{
this.shipToDefault = shipToDefault;
this.shipToDefaultSet = true;
}
public void setBillToDefault(final Boolean billToDefault)
{
this.billToDefault = billToDefault;
this.billToDefaultSet = true;
}
public void setNewsletter(final Boolean newsletter)
{
this.newsletter = newsletter;
this.newsletterSet = true;
}
public void setDescription(final String description)
{
this.description = description;
this.descriptionSet = true;
}
public void setSales(final Boolean sales)
|
{
this.sales = sales;
this.salesSet = true;
}
public void setSalesDefault(final Boolean salesDefault)
{
this.salesDefault = salesDefault;
this.salesDefaultSet = true;
}
public void setPurchase(final Boolean purchase)
{
this.purchase = purchase;
this.purchaseSet = true;
}
public void setPurchaseDefault(final Boolean purchaseDefault)
{
this.purchaseDefault = purchaseDefault;
this.purchaseDefaultSet = true;
}
public void setSubjectMatter(final Boolean subjectMatter)
{
this.subjectMatter = subjectMatter;
this.subjectMatterSet = true;
}
public void setSyncAdvise(final SyncAdvise syncAdvise)
{
this.syncAdvise = syncAdvise;
this.syncAdviseSet = true;
}
}
|
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-bpartner\src\main\java\de\metas\common\bpartner\v1\request\JsonRequestContact.java
| 1
|
请完成以下Java代码
|
public static MOrg get (Properties ctx, int AD_Org_ID)
{
if (AD_Org_ID < 0)
{
return null;
}
final I_AD_Org org = Services.get(IOrgDAO.class).retrieveOrg(ctx, AD_Org_ID);
return LegacyAdapters.convertToPO(org);
} // get
/**************************************************************************
* Standard Constructor
* @param ctx context
* @param AD_Org_ID id
* @param trxName transaction
*/
public MOrg (Properties ctx, int AD_Org_ID, String trxName)
{
super(ctx, AD_Org_ID, trxName);
if (is_new())
{
// setValue (null);
// setName (null);
setIsSummary (false);
}
} // MOrg
/**
* Load Constructor
* @param ctx context
* @param rs result set
* @param trxName transaction
*/
public MOrg (Properties ctx, ResultSet rs, String trxName)
{
super(ctx, rs, trxName);
} // MOrg
/**
* Parent Constructor
* @param client client
* @param name name
*/
public MOrg (MClient client, String name)
{
this (client.getCtx(), -1, client.get_TrxName());
setAD_Client_ID (client.getAD_Client_ID());
setValue (name);
setName (name);
} // MOrg
/** Linked Business Partner */
private Integer m_linkedBPartner = null;
@Override
protected boolean afterSave (boolean newRecord, boolean success)
{
if (!success)
{
return success;
}
if (newRecord)
{
// Info
|
Services.get(IOrgDAO.class).createOrUpdateOrgInfo(OrgInfoUpdateRequest.builder()
.orgId(OrgId.ofRepoId(getAD_Org_ID()))
.build());
// TreeNode
// insert_Tree(MTree_Base.TREETYPE_Organization);
}
// Value/Name change
if (!newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name")))
{
MAccount.updateValueDescription(getCtx(), "AD_Org_ID=" + getAD_Org_ID(), get_TrxName());
final String elementOrgTrx = Env.CTXNAME_AcctSchemaElementPrefix + X_C_AcctSchema_Element.ELEMENTTYPE_OrgTrx;
if ("Y".equals(Env.getContext(getCtx(), elementOrgTrx)))
{
MAccount.updateValueDescription(getCtx(), "AD_OrgTrx_ID=" + getAD_Org_ID(), get_TrxName());
}
}
return true;
} // afterSave
/**
* Get Linked BPartner
* @return C_BPartner_ID
*/
public int getLinkedC_BPartner_ID(String trxName)
{
if (m_linkedBPartner == null)
{
int C_BPartner_ID = DB.getSQLValue(trxName,
"SELECT C_BPartner_ID FROM C_BPartner WHERE AD_OrgBP_ID=?",
getAD_Org_ID());
if (C_BPartner_ID < 0)
{
C_BPartner_ID = 0;
}
m_linkedBPartner = new Integer (C_BPartner_ID);
}
return m_linkedBPartner.intValue();
} // getLinkedC_BPartner_ID
} // MOrg
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MOrg.java
| 1
|
请完成以下Java代码
|
public class SimpleProducerConsumerDemonstrator {
private static final Logger log = Logger.getLogger(SimpleProducerConsumerDemonstrator.class.getCanonicalName());
BlockingQueue<Double> blockingQueue = new LinkedBlockingDeque<>(5);
private void produce() {
while (true) {
double value = generateValue();
try {
blockingQueue.put(value);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
log.info(String.format("[%s] Value produced: %f%n", Thread.currentThread().getName(), value));
}
}
private void consume() {
while (true) {
Double value;
try {
value = blockingQueue.take();
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
// Consume value
|
log.info(String.format("[%s] Value consumed: %f%n", Thread.currentThread().getName(), value));
}
}
private double generateValue() {
return Math.random();
}
private void runProducerConsumer() {
for (int i = 0; i < 2; i++) {
Thread producerThread = new Thread(this::produce);
producerThread.start();
}
for (int i = 0; i < 3; i++) {
Thread consumerThread = new Thread(this::consume);
consumerThread.start();
}
}
public static void main(String[] args) {
SimpleProducerConsumerDemonstrator simpleProducerConsumerDemonstrator = new SimpleProducerConsumerDemonstrator();
simpleProducerConsumerDemonstrator.runProducerConsumer();
sleep(2000);
System.exit(0);
}
}
|
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-7\src\main\java\com\baeldung\producerconsumer\SimpleProducerConsumerDemonstrator.java
| 1
|
请完成以下Java代码
|
public final class ConfigurationProperty implements OriginProvider, Comparable<ConfigurationProperty> {
private final ConfigurationPropertyName name;
private final Object value;
private final @Nullable ConfigurationPropertySource source;
private final @Nullable Origin origin;
public ConfigurationProperty(ConfigurationPropertyName name, Object value, @Nullable Origin origin) {
this(null, name, value, origin);
}
private ConfigurationProperty(@Nullable ConfigurationPropertySource source, ConfigurationPropertyName name,
Object value, @Nullable Origin origin) {
Assert.notNull(name, "'name' must not be null");
Assert.notNull(value, "'value' must not be null");
this.source = source;
this.name = name;
this.value = value;
this.origin = origin;
}
/**
* Return the {@link ConfigurationPropertySource} that provided the property or
* {@code null} if the source is unknown.
* @return the configuration property source
* @since 2.6.0
*/
public @Nullable ConfigurationPropertySource getSource() {
return this.source;
}
/**
* Return the name of the configuration property.
* @return the configuration property name
*/
public ConfigurationPropertyName getName() {
return this.name;
}
/**
* Return the value of the configuration property.
* @return the configuration property value
*/
public Object getValue() {
return this.value;
}
@Override
public @Nullable Origin getOrigin() {
return this.origin;
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
ConfigurationProperty other = (ConfigurationProperty) obj;
boolean result = true;
result = result && ObjectUtils.nullSafeEquals(this.name, other.name);
result = result && ObjectUtils.nullSafeEquals(this.value, other.value);
return result;
}
@Override
|
public int hashCode() {
int result = ObjectUtils.nullSafeHashCode(this.name);
result = 31 * result + ObjectUtils.nullSafeHashCode(this.value);
return result;
}
@Override
public String toString() {
return new ToStringCreator(this).append("name", this.name)
.append("value", this.value)
.append("origin", this.origin)
.toString();
}
@Override
public int compareTo(ConfigurationProperty other) {
return this.name.compareTo(other.name);
}
@Contract("_, !null -> !null")
static @Nullable ConfigurationProperty of(ConfigurationPropertyName name, @Nullable OriginTrackedValue value) {
if (value == null) {
return null;
}
return new ConfigurationProperty(name, value.getValue(), value.getOrigin());
}
@Contract("_, _, !null, _ -> !null")
static @Nullable ConfigurationProperty of(@Nullable ConfigurationPropertySource source,
ConfigurationPropertyName name, @Nullable Object value, @Nullable Origin origin) {
if (value == null) {
return null;
}
return new ConfigurationProperty(source, name, value, origin);
}
}
|
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\properties\source\ConfigurationProperty.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public Mono<Integer> run(Integer id) {
return lookup(id) //
.flatMap(process -> start(template, process)) //
.flatMap(this::verify) //
.flatMap(process -> finish(template, process)) //
.map(Process::id);
}
private Mono<Process> finish(ReactiveMongoOperations operations, Process process) {
return operations.update(Process.class).matching(Query.query(Criteria.where("id").is(process.id())))
.apply(Update.update("state", State.DONE).inc("transitionCount", 1)).first() //
.then(Mono.just(process));
}
Mono<Process> start(ReactiveMongoOperations operations, Process process) {
|
return operations.update(Process.class).matching(Query.query(Criteria.where("id").is(process.id())))
.apply(Update.update("state", State.ACTIVE).inc("transitionCount", 1)).first() //
.then(Mono.just(process));
}
Mono<Process> lookup(Integer id) {
return repository.findById(id);
}
Mono<Process> verify(Process process) {
Assert.state(process.id() % 3 != 0, "We're sorry but we needed to drop that one");
return Mono.just(process);
}
}
|
repos\spring-data-examples-main\mongodb\transactions\src\main\java\example\springdata\mongodb\reactive\ReactiveManagedTransitionService.java
| 2
|
请完成以下Java代码
|
public int getAD_Client_ID()
{
return inoutLine.getAD_Client_ID();
}
@Override
public int getAD_Org_ID()
{
return inoutLine.getAD_Org_ID();
}
@Override
public boolean isSOTrx()
{
final I_M_InOut inout = getM_InOut();
return inout.isSOTrx();
}
@Override
public I_C_BPartner getC_BPartner()
{
final I_M_InOut inout = getM_InOut();
final I_C_BPartner partner = InterfaceWrapperHelper.load(inout.getC_BPartner_ID(), I_C_BPartner.class);
|
if (partner == null)
{
return null;
}
return partner;
}
private I_M_InOut getM_InOut()
{
final I_M_InOut inout = inoutLine.getM_InOut();
if (inout == null)
{
throw new AdempiereException("M_InOut_ID was not set in " + inoutLine);
}
return inout;
}
@Override
public String toString()
{
return String.format("InOutLineBPartnerAware [inoutLine=%s, isSOTrx()=%s, getC_BPartner()=%s, getM_InOut()=%s]", inoutLine, isSOTrx(), getC_BPartner(), getM_InOut());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.fresh\de.metas.fresh.base\src\main\java\org\adempiere\mm\attributes\api\impl\InOutLineBPartnerAware.java
| 1
|
请完成以下Java代码
|
public Builder setFilterId(final String filterId)
{
this.filterId = filterId;
return this;
}
public Builder setSortNo(final int sortNo)
{
this.sortNo = sortNo;
return this;
}
public Builder setDisplayName(final Map<String, String> displayNameTrls)
{
this.displayNameTrls = TranslatableStrings.ofMap(displayNameTrls);
return this;
}
public Builder setDisplayName(final ITranslatableString displayNameTrls)
{
this.displayNameTrls = displayNameTrls;
return this;
}
public Builder setDisplayName(final String displayName)
{
displayNameTrls = TranslatableStrings.constant(displayName);
return this;
}
public Builder setDisplayName(final AdMessageKey displayName)
{
return setDisplayName(TranslatableStrings.adMessage(displayName));
}
@Nullable
public ITranslatableString getDisplayNameTrls()
{
if (displayNameTrls != null)
{
return displayNameTrls;
}
if (parameters.size() == 1)
{
return parameters.get(0).getDisplayName();
}
return null;
}
public Builder setFrequentUsed(final boolean frequentUsed)
{
this.frequentUsed = frequentUsed;
return this;
}
public Builder setInlineRenderMode(final DocumentFilterInlineRenderMode inlineRenderMode)
{
|
this.inlineRenderMode = inlineRenderMode;
return this;
}
private DocumentFilterInlineRenderMode getInlineRenderMode()
{
return inlineRenderMode != null ? inlineRenderMode : DocumentFilterInlineRenderMode.BUTTON;
}
public Builder setParametersLayoutType(final PanelLayoutType parametersLayoutType)
{
this.parametersLayoutType = parametersLayoutType;
return this;
}
private PanelLayoutType getParametersLayoutType()
{
return parametersLayoutType != null ? parametersLayoutType : PanelLayoutType.Panel;
}
public Builder setFacetFilter(final boolean facetFilter)
{
this.facetFilter = facetFilter;
return this;
}
public boolean hasParameters()
{
return !parameters.isEmpty();
}
public Builder addParameter(final DocumentFilterParamDescriptor.Builder parameter)
{
parameters.add(parameter);
return this;
}
public Builder addInternalParameter(final String parameterName, final Object constantValue)
{
return addInternalParameter(DocumentFilterParam.ofNameEqualsValue(parameterName, constantValue));
}
public Builder addInternalParameter(final DocumentFilterParam parameter)
{
internalParameters.add(parameter);
return this;
}
public Builder putDebugProperty(final String name, final Object value)
{
Check.assumeNotEmpty(name, "name is not empty");
if (debugProperties == null)
{
debugProperties = new LinkedHashMap<>();
}
debugProperties.put("debug-" + name, value);
return this;
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterDescriptor.java
| 1
|
请完成以下Java代码
|
public void setMSV3_AuftragsSupportID (int MSV3_AuftragsSupportID)
{
set_Value (COLUMNNAME_MSV3_AuftragsSupportID, Integer.valueOf(MSV3_AuftragsSupportID));
}
/** Get AuftragsSupportID.
@return AuftragsSupportID */
@Override
public int getMSV3_AuftragsSupportID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_AuftragsSupportID);
if (ii == null)
return 0;
return ii.intValue();
}
@Override
public de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_Bestellung getMSV3_Bestellung() throws RuntimeException
{
return get_ValueAsPO(COLUMNNAME_MSV3_Bestellung_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_Bestellung.class);
}
@Override
public void setMSV3_Bestellung(de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_Bestellung MSV3_Bestellung)
{
set_ValueFromPO(COLUMNNAME_MSV3_Bestellung_ID, de.metas.vertical.pharma.vendor.gateway.msv3.model.I_MSV3_Bestellung.class, MSV3_Bestellung);
}
/** Set MSV3_Bestellung.
@param MSV3_Bestellung_ID MSV3_Bestellung */
@Override
public void setMSV3_Bestellung_ID (int MSV3_Bestellung_ID)
{
if (MSV3_Bestellung_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_Bestellung_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_Bestellung_ID, Integer.valueOf(MSV3_Bestellung_ID));
}
/** Get MSV3_Bestellung.
@return MSV3_Bestellung */
@Override
public int getMSV3_Bestellung_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Bestellung_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set MSV3_BestellungAuftrag.
@param MSV3_BestellungAuftrag_ID MSV3_BestellungAuftrag */
@Override
public void setMSV3_BestellungAuftrag_ID (int MSV3_BestellungAuftrag_ID)
{
if (MSV3_BestellungAuftrag_ID < 1)
set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAuftrag_ID, null);
else
set_ValueNoCheck (COLUMNNAME_MSV3_BestellungAuftrag_ID, Integer.valueOf(MSV3_BestellungAuftrag_ID));
}
|
/** Get MSV3_BestellungAuftrag.
@return MSV3_BestellungAuftrag */
@Override
public int getMSV3_BestellungAuftrag_ID ()
{
Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_BestellungAuftrag_ID);
if (ii == null)
return 0;
return ii.intValue();
}
/** Set GebindeId.
@param MSV3_GebindeId GebindeId */
@Override
public void setMSV3_GebindeId (java.lang.String MSV3_GebindeId)
{
set_Value (COLUMNNAME_MSV3_GebindeId, MSV3_GebindeId);
}
/** Get GebindeId.
@return GebindeId */
@Override
public java.lang.String getMSV3_GebindeId ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_GebindeId);
}
/** Set Id.
@param MSV3_Id Id */
@Override
public void setMSV3_Id (java.lang.String MSV3_Id)
{
set_Value (COLUMNNAME_MSV3_Id, MSV3_Id);
}
/** Get Id.
@return Id */
@Override
public java.lang.String getMSV3_Id ()
{
return (java.lang.String)get_Value(COLUMNNAME_MSV3_Id);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungAuftrag.java
| 1
|
请完成以下Java代码
|
private static boolean isEligibleChildWhenAutoDiscovering(
@NonNull String parentTableName,
@NonNull POInfo childPOInfo,
@NonNull String linkColumnName)
{
if (childPOInfo.isView())
{
return false;
}
if (!childPOInfo.isParentLinkColumn(linkColumnName))
{
return false;
}
final boolean isLine = (parentTableName + "Line").equals(childPOInfo.getTableName());
if (!isLine && childPOInfo.hasColumnName(COLUMNNAME_Processed))
{
return false;
}
return !isSkipChildTableNameWhenAutodiscovering(childPOInfo.getTableName());
}
private static boolean isSkipChildTableNameWhenAutodiscovering(final String childTableName)
{
final String childTableNameUC = childTableName.toUpperCase();
return childTableNameUC.endsWith("_ACCT") // acct table
|| childTableNameUC.startsWith("I_") // import tables
|| childTableNameUC.endsWith("_TRL") // translation tables
|| childTableNameUC.startsWith("M_COST") // cost tables
|| childTableNameUC.startsWith("T_") // temporary tables
|| childTableNameUC.equals("M_PRODUCT_COSTING") // product costing
|| childTableNameUC.equals("M_STORAGE") // storage table
|| childTableNameUC.equals("C_BP_WITHHOLDING") // at Patrick's request, this was removed, because is not used
|| childTableNameUC.startsWith("M_") && childTableNameUC.endsWith("MA") // material allocation table
;
}
@NonNull
private static ImmutableList<String> extractChildPOInfoOrderBys(final POInfo childPOInfo)
{
|
final ImmutableList.Builder<String> orderByColumnNames = ImmutableList.builder();
if (childPOInfo.hasColumnName(COLUMNNAME_Line))
{
orderByColumnNames.add(COLUMNNAME_Line);
}
if (childPOInfo.hasColumnName(COLUMNNAME_SeqNo))
{
orderByColumnNames.add(COLUMNNAME_SeqNo);
}
if (childPOInfo.getKeyColumnName() != null)
{
orderByColumnNames.add(childPOInfo.getKeyColumnName());
}
return orderByColumnNames.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\copy_with_details\template\CopyTemplateService.java
| 1
|
请完成以下Java代码
|
Decoder<?> getDecoder() {
return this.decoder;
}
@Override
public ClientResponseField field(String path) {
return new DefaultClientResponseField(this, super.field(path));
}
@Override
public <D> D toEntity(Class<D> type) {
ClientResponseField field = field("");
D entity = field.toEntity(type);
// should never happen because toEntity checks response.isValid
if (entity == null) {
throw new FieldAccessException(getRequest(), this, field);
}
return entity;
}
|
@Override
public <D> D toEntity(ParameterizedTypeReference<D> type) {
ClientResponseField field = field("");
D entity = field.toEntity(type);
// should never happen because toEntity checks response.isValid
if (entity == null) {
throw new FieldAccessException(getRequest(), this, field);
}
return entity;
}
}
|
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultClientGraphQlResponse.java
| 1
|
请完成以下Java代码
|
public class BeanUtils {
// NB : this method lists only beans created via factory methods
public static List<String> getBeansWithAnnotation(GenericApplicationContext applicationContext, Class<?> annotationClass) {
List<String> result = new ArrayList<String>();
ConfigurableListableBeanFactory factory = applicationContext.getBeanFactory();
for(String name : factory.getBeanDefinitionNames()) {
BeanDefinition bd = factory.getBeanDefinition(name);
if(bd.getSource() instanceof AnnotatedTypeMetadata) {
AnnotatedTypeMetadata metadata = (AnnotatedTypeMetadata) bd.getSource();
if (metadata.getAnnotationAttributes(annotationClass.getName()) != null) {
result.add(name);
}
}
}
return result;
}
// NB : list beans created via factory methods using streams (same method as before, written differently)
public static List<String> getBeansWithAnnotation_StreamVersion(GenericApplicationContext applicationContext, Class<?> annotationClass) {
|
ConfigurableListableBeanFactory factory = applicationContext.getBeanFactory();
return Arrays.stream(factory.getBeanDefinitionNames())
.filter(name -> isAnnotated(factory, name, annotationClass))
.collect(Collectors.toList());
}
private static boolean isAnnotated(ConfigurableListableBeanFactory factory, String beanName, Class<?> clazz) {
BeanDefinition beanDefinition = factory.getBeanDefinition(beanName);
if(beanDefinition.getSource() instanceof AnnotatedTypeMetadata) {
AnnotatedTypeMetadata metadata = (AnnotatedTypeMetadata) beanDefinition.getSource();
return metadata.getAnnotationAttributes(clazz.getName()) != null;
}
return false;
}
}
|
repos\tutorials-master\spring-di-3\src\main\java\com\baeldung\countingbeans\olderspring\factorybeans\BeanUtils.java
| 1
|
请完成以下Java代码
|
public static List<int[]> getAllPairsStream(List<Integer> list1, List<Integer> list2) {
return list1.stream()
.flatMap(num1 -> list2.stream().map(num2 -> new int[] { num1, num2 }))
.collect(Collectors.toList());
}
public static List<int[]> getFilteredPairsImperative(List<Integer> list1, List<Integer> list2) {
List<int[]> pairs = new ArrayList<>();
for (Integer num1 : list1) {
for (Integer num2 : list2) {
if (num1 + num2 > 7) {
pairs.add(new int[] { num1, num2 });
}
}
}
return pairs;
}
public static List<int[]> getFilteredPairsStream(List<Integer> list1, List<Integer> list2) {
return list1.stream()
.flatMap(num1 -> list2.stream().map(num2 -> new int[] { num1, num2 }))
.filter(pair -> pair[0] + pair[1] > 7)
.collect(Collectors.toList());
|
}
public static Optional<int[]> getFirstMatchingPairImperative(List<Integer> list1, List<Integer> list2) {
for (Integer num1 : list1) {
for (Integer num2 : list2) {
if (num1 + num2 > 7) {
return Optional.of(new int[] { num1, num2 });
}
}
}
return Optional.empty();
}
public static Optional<int[]> getFirstMatchingPairStream(List<Integer> list1, List<Integer> list2) {
return list1.stream()
.flatMap(num1 -> list2.stream().map(num2 -> new int[] { num1, num2 }))
.filter(pair -> pair[0] + pair[1] > 7)
.findFirst();
}
}
|
repos\tutorials-master\core-java-modules\core-java-streams-7\src\main\java\com\baeldung\streams\NestedLoopsToStreamsConverter.java
| 1
|
请完成以下Java代码
|
public class PMM_PurchaseCandidate_DatePromised_FacetCollector extends SingleFacetCategoryCollectorTemplate<I_PMM_PurchaseCandidate>
{
private final DateFormat dateFormat = DisplayType.getDateFormat(DisplayType.Date);
public PMM_PurchaseCandidate_DatePromised_FacetCollector()
{
super(FacetCategory.builder()
.setDisplayNameAndTranslate(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised)
.setCollapsed(true) // 08755: default collapsed
.build());
}
@Override
protected List<IFacet<I_PMM_PurchaseCandidate>> collectFacets(final IQueryBuilder<I_PMM_PurchaseCandidate> queryBuilder)
{
final Timestamp today = Env.getDate(queryBuilder.getCtx());
final List<Map<String, Object>> datePromised = queryBuilder
.addNotEqualsFilter(I_PMM_PurchaseCandidate.COLUMN_DatePromised, null)
.addCompareFilter(I_PMM_PurchaseCandidate.COLUMN_DatePromised, Operator.GREATER_OR_EQUAL, today)
.create()
.listDistinct(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised);
final List<IFacet<I_PMM_PurchaseCandidate>> facets = new ArrayList<>(datePromised.size() + 1);
for (final Map<String, Object> row : datePromised)
{
final IFacet<I_PMM_PurchaseCandidate> facet = createFacet(row);
facets.add(facet);
}
//
// Add Before Today facet
facets.add(0, Facet.<I_PMM_PurchaseCandidate> builder()
.setFacetCategory(getFacetCategory())
|
.setDisplayName(" < " + dateFormat.format(today))
.setFilter(TypedSqlQueryFilter.of(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised + "<" + DB.TO_DATE(today)))
.build()
);
return facets;
}
private IFacet<I_PMM_PurchaseCandidate> createFacet(final Map<String, Object> row)
{
final Timestamp date = (Timestamp)row.get(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised);
return Facet.<I_PMM_PurchaseCandidate> builder()
.setFacetCategory(getFacetCategory())
.setDisplayName(dateFormat.format(date))
.setFilter(TypedSqlQueryFilter.of(I_PMM_PurchaseCandidate.COLUMNNAME_DatePromised + "=" + DB.TO_DATE(date)))
.build();
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\facet\impl\PMM_PurchaseCandidate_DatePromised_FacetCollector.java
| 1
|
请完成以下Java代码
|
@Nullable Object getResponse() {
return this.response;
}
}
/**
* {@link CachedResponse} variant used when Reactor is present.
*/
static class ReactiveCachedResponse extends CachedResponse {
ReactiveCachedResponse(@Nullable Object response, long creationTime, long timeToLive) {
super(applyCaching(response, timeToLive), creationTime);
}
private static @Nullable Object applyCaching(@Nullable Object response, long timeToLive) {
if (response instanceof Mono) {
return ((Mono<?>) response).cache(Duration.ofMillis(timeToLive));
}
if (response instanceof Flux) {
return ((Flux<?>) response).cache(Duration.ofMillis(timeToLive));
}
return response;
}
}
private static final class CacheKey {
private static final Class<?>[] CACHEABLE_TYPES = new Class<?>[] { ApiVersion.class, SecurityContext.class,
WebServerNamespace.class };
private final ApiVersion apiVersion;
private final @Nullable Principal principal;
private final @Nullable WebServerNamespace serverNamespace;
private CacheKey(ApiVersion apiVersion, @Nullable Principal principal,
@Nullable WebServerNamespace serverNamespace) {
this.principal = principal;
this.apiVersion = apiVersion;
this.serverNamespace = serverNamespace;
}
static boolean containsType(Class<?> type) {
return Arrays.stream(CacheKey.CACHEABLE_TYPES).anyMatch((c) -> c.isAssignableFrom(type));
}
|
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null || getClass() != obj.getClass()) {
return false;
}
CacheKey other = (CacheKey) obj;
return this.apiVersion.equals(other.apiVersion)
&& ObjectUtils.nullSafeEquals(this.principal, other.principal)
&& ObjectUtils.nullSafeEquals(this.serverNamespace, other.serverNamespace);
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.apiVersion.hashCode();
result = prime * result + ObjectUtils.nullSafeHashCode(this.principal);
result = prime * result + ObjectUtils.nullSafeHashCode(this.serverNamespace);
return result;
}
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\invoker\cache\CachingOperationInvoker.java
| 1
|
请完成以下Java代码
|
public final CurrencyConversionContext getPaymentCurrencyConversionCtx()
{
if (paymentCurrencyConversionCtx == null)
{
final I_C_Payment payment = getC_Payment();
final I_C_CashLine cashLine = getC_CashLine();
if (payment != null)
{
final IPaymentBL paymentBL = Services.get(IPaymentBL.class);
paymentCurrencyConversionCtx = paymentBL.extractCurrencyConversionContext(payment);
}
else if (cashLine != null)
{
final ICurrencyBL currencyConversionBL = Services.get(ICurrencyBL.class);
final I_C_Cash cashJournal = cashLine.getC_Cash();
paymentCurrencyConversionCtx = currencyConversionBL.createCurrencyConversionContext(
InstantAndOrgId.ofTimestamp(cashJournal.getDateAcct(), OrgId.ofRepoId(cashLine.getAD_Org_ID())),
null, // C_ConversionType_ID - default
ClientId.ofRepoId(cashLine.getAD_Client_ID()));
}
else
{
throw new IllegalStateException("Allocation line does not have a payment or a cash line set: " + this);
}
}
return paymentCurrencyConversionCtx;
}
public final boolean hasPaymentDocument()
{
return getC_Payment() != null || getC_CashLine() != null;
}
public final OrgId getPaymentOrgId()
{
final I_C_Payment payment = getC_Payment();
if (payment != null)
{
return OrgId.ofRepoId(payment.getAD_Org_ID());
}
final I_C_CashLine cashLine = getC_CashLine();
if (cashLine != null)
{
|
return OrgId.ofRepoId(cashLine.getAD_Org_ID());
}
return getOrgId();
}
public final BPartnerId getPaymentBPartnerId()
{
final I_C_Payment payment = getC_Payment();
if (payment != null)
{
return BPartnerId.ofRepoId(payment.getC_BPartner_ID());
}
return getBPartnerId();
}
@Nullable
public final BPartnerLocationId getPaymentBPartnerLocationId()
{
final I_C_Payment payment = getC_Payment();
if (payment != null)
{
return BPartnerLocationId.ofRepoIdOrNull(payment.getC_BPartner_ID(), payment.getC_BPartner_Location_ID());
}
return getBPartnerLocationId();
}
public boolean isPaymentReceipt()
{
Check.assumeNotNull(paymentReceipt, "payment document exists");
return paymentReceipt;
}
} // DocLine_Allocation
|
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocLine_Allocation.java
| 1
|
请完成以下Java代码
|
public void updateAllCompensationLines()
{
moveAllManualCompensationLinesToEnd();
BigDecimal previousNetAmt = getRegularLinesNetAmt();
for (final GroupCompensationLine compensationLine : compensationLines)
{
updateCompensationLine(compensationLine, previousNetAmt);
previousNetAmt = previousNetAmt.add(compensationLine.getLineNetAmt());
}
}
private void updateCompensationLine(final GroupCompensationLine compensationLine, final BigDecimal baseAmt)
{
compensationLine.setBaseAmt(baseAmt);
if (compensationLine.isPercentage())
{
final Percent percentage = compensationLine.getPercentage();
final GroupCompensationType compensationType = compensationLine.getType();
final BigDecimal compensationAmt = percentage.computePercentageOf(baseAmt, pricePrecision.toInt());
final BigDecimal amt = OrderGroupCompensationUtils.adjustAmtByCompensationType(compensationAmt, compensationType);
final Quantity one = Quantity.of(ONE,
loadOutOfTrx(compensationLine.getUomId(), I_C_UOM.class));
compensationLine.setPriceAndQty(amt, one, amountPrecision);
}
}
public void addNewCompensationLine(final GroupCompensationLineCreateRequest request)
{
final BigDecimal price = request.getPrice();
final BigDecimal qtyEntered = request.getQtyEntered();
final BigDecimal lineNetAmt = price != null && qtyEntered != null
? amountPrecision.roundIfNeeded(price.multiply(qtyEntered))
: null;
final GroupCompensationLine compensationLine = GroupCompensationLine.builder()
.productId(request.getProductId())
.uomId(request.getUomId())
.type(request.getType())
.amtType(request.getAmtType())
.percentage(request.getPercentage())
.price(price)
.qtyEntered(qtyEntered)
.lineNetAmt(lineNetAmt)
.groupTemplateLineId(request.getGroupTemplateLineId())
.build();
updateCompensationLine(compensationLine, getTotalNetAmt());
|
compensationLines.add(compensationLine);
}
void removeAllGeneratedLines()
{
compensationLines.removeIf(GroupCompensationLine::isGeneratedLine);
}
private void moveAllManualCompensationLinesToEnd()
{
final ArrayList<GroupCompensationLine> manualCompensationLines = new ArrayList<>();
for (final Iterator<GroupCompensationLine> it = compensationLines.iterator(); it.hasNext(); )
{
final GroupCompensationLine compensationLine = it.next();
if (compensationLine.isManualLine())
{
manualCompensationLines.add(compensationLine);
it.remove();
}
}
compensationLines.addAll(manualCompensationLines);
}
boolean isBasedOnGroupTemplate()
{
return getGroupTemplateId() != null;
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\Group.java
| 1
|
请完成以下Java代码
|
public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
if (configAttributeMap == null) this.loadDataSource();
List<ConfigAttribute> configAttributes = new ArrayList<>();
//获取当前访问的路径
String url = ((FilterInvocation) o).getRequestUrl();
String path = URLUtil.getPath(url);
PathMatcher pathMatcher = new AntPathMatcher();
Iterator<String> iterator = configAttributeMap.keySet().iterator();
//获取访问该路径所需资源
while (iterator.hasNext()) {
String pattern = iterator.next();
if (pathMatcher.match(pattern, path)) {
configAttributes.add(configAttributeMap.get(pattern));
}
}
|
// 未设置操作请求权限,返回空集合
return configAttributes;
}
@Override
public Collection<ConfigAttribute> getAllConfigAttributes() {
return null;
}
@Override
public boolean supports(Class<?> aClass) {
return true;
}
}
|
repos\mall-master\mall-security\src\main\java\com\macro\mall\security\component\DynamicSecurityMetadataSource.java
| 1
|
请完成以下Java代码
|
public class JacksonJsonDataFormat implements DataFormat {
private static final JacksonJsonLogger LOG = ExternalTaskClientLogger.JSON_FORMAT_LOGGER;
protected String name;
protected ObjectMapper objectMapper;
protected List<TypeDetector> typeDetectors;
public JacksonJsonDataFormat(String name) {
this(name, new ObjectMapper());
}
public JacksonJsonDataFormat(String name, ObjectMapper objectMapper) {
this.name = name;
this.objectMapper = objectMapper;
this.typeDetectors = new ArrayList<>();
this.typeDetectors.add(new ListJacksonJsonTypeDetector());
this.typeDetectors.add(new DefaultJsonJacksonTypeDetector());
}
public String getName() {
return name;
}
public ObjectMapper getObjectMapper() {
return objectMapper;
}
public void setObjectMapper(ObjectMapper objectMapper) {
this.objectMapper = objectMapper;
}
public boolean canMap(Object parameter) {
return parameter != null;
}
public String writeValue(Object value) {
try {
StringWriter stringWriter = new StringWriter();
objectMapper.writeValue(stringWriter, value);
return stringWriter.toString();
}
catch (IOException e) {
throw LOG.unableToWriteValue(value, e);
}
}
@SuppressWarnings("unchecked")
public <T> T readValue(String value, String typeIdentifier) {
try {
Class<?> cls = Class.forName(typeIdentifier);
return (T) readValue(value, cls);
}
catch (ClassNotFoundException e) {
JavaType javaType = constructJavaTypeFromCanonicalString(typeIdentifier);
return readValue(value, javaType);
}
}
public <T> T readValue(String value, Class<T> cls) {
try {
return objectMapper.readValue(value, cls);
}
catch (JsonParseException e) {
throw LOG.unableToReadValue(value, e);
}
catch (JsonMappingException e) {
|
throw LOG.unableToReadValue(value, e);
}
catch (IOException e) {
throw LOG.unableToReadValue(value, e);
}
}
protected <C> C readValue(String value, JavaType type) {
try {
return objectMapper.readValue(value, type);
}
catch (JsonParseException e) {
throw LOG.unableToReadValue(value, e);
}
catch (JsonMappingException e) {
throw LOG.unableToReadValue(value, e);
}
catch (IOException e) {
throw LOG.unableToReadValue(value, e);
}
}
public JavaType constructJavaTypeFromCanonicalString(String canonicalString) {
try {
return TypeFactory.defaultInstance().constructFromCanonical(canonicalString);
}
catch (IllegalArgumentException e) {
throw LOG.unableToConstructJavaType(canonicalString, e);
}
}
public String getCanonicalTypeName(Object value) {
ensureNotNull("value", value);
for (TypeDetector typeDetector : typeDetectors) {
if (typeDetector.canHandle(value)) {
return typeDetector.detectType(value);
}
}
throw LOG.unableToDetectCanonicalType(value);
}
}
|
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\json\JacksonJsonDataFormat.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class TaskIdentityLinkFamilyResource extends TaskBaseResource {
@ApiOperation(value = "List identity links for a task for either groups or users", tags = { "Task Identity Links" }, nickname = "listIdentityLinksForFamily",
notes = "Returns only identity links targeting either users or groups. Response body and status-codes are exactly the same as when getting the full list of identity links for a task.")
@ApiResponses(value = {
@ApiResponse(code = 200, message = "Indicates the task was found and the requested identity links are returned."),
@ApiResponse(code = 404, message = "Indicates the requested task was not found.")
})
@GetMapping(value = "/cmmn-runtime/tasks/{taskId}/identitylinks/{family}", produces = "application/json")
public List<RestIdentityLink> getIdentityLinksForFamily(@ApiParam(name = "taskId") @PathVariable("taskId") String taskId, @ApiParam(name = "family") @PathVariable("family") String family) {
Task task = getTaskFromRequestWithoutAccessCheck(taskId);
if (family == null || (!CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_GROUPS.equals(family) && !CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS.equals(family))) {
throw new FlowableIllegalArgumentException("Identity link family should be 'users' or 'groups'.");
}
if (restApiInterceptor != null) {
restApiInterceptor.accessTaskIdentityLinks(task);
}
|
boolean isUser = family.equals(CmmnRestUrls.SEGMENT_IDENTITYLINKS_FAMILY_USERS);
List<RestIdentityLink> results = new ArrayList<>();
List<IdentityLink> allLinks = taskService.getIdentityLinksForTask(task.getId());
for (IdentityLink link : allLinks) {
boolean match = false;
if (isUser) {
match = link.getUserId() != null;
} else {
match = link.getGroupId() != null;
}
if (match) {
results.add(restResponseFactory.createRestIdentityLink(link));
}
}
return results;
}
}
|
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskIdentityLinkFamilyResource.java
| 2
|
请完成以下Java代码
|
public JobQuery orderByJobRetries() {
return orderBy(JobQueryProperty.RETRIES);
}
public JobQuery orderByTenantId() {
return orderBy(JobQueryProperty.TENANT_ID);
}
// results //////////////////////////////////////////
public long executeCount(CommandContext commandContext) {
checkQueryOk();
return commandContext.getJobEntityManager().findJobCountByQueryCriteria(this);
}
public List<Job> executeList(CommandContext commandContext, Page page) {
checkQueryOk();
return commandContext.getJobEntityManager().findJobsByQueryCriteria(this, page);
}
// getters //////////////////////////////////////////
public String getProcessInstanceId() {
return processInstanceId;
}
public String getExecutionId() {
return executionId;
}
public boolean getRetriesLeft() {
return retriesLeft;
}
public boolean getExecutable() {
return executable;
}
public Date getNow() {
return Context.getProcessEngineConfiguration().getClock().getCurrentTime();
}
public boolean isWithException() {
return withException;
}
public String getExceptionMessage() {
return exceptionMessage;
}
public String getTenantId() {
return tenantId;
}
public String getTenantIdLike() {
return tenantIdLike;
}
|
public boolean isWithoutTenantId() {
return withoutTenantId;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
public String getId() {
return id;
}
public String getProcessDefinitionId() {
return processDefinitionId;
}
public boolean isOnlyTimers() {
return onlyTimers;
}
public boolean isOnlyMessages() {
return onlyMessages;
}
public Date getDuedateHigherThan() {
return duedateHigherThan;
}
public Date getDuedateLowerThan() {
return duedateLowerThan;
}
public Date getDuedateHigherThanOrEqual() {
return duedateHigherThanOrEqual;
}
public Date getDuedateLowerThanOrEqual() {
return duedateLowerThanOrEqual;
}
public boolean isNoRetriesLeft() {
return noRetriesLeft;
}
public boolean isOnlyLocked() {
return onlyLocked;
}
public boolean isOnlyUnlocked() {
return onlyUnlocked;
}
}
|
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\JobQueryImpl.java
| 1
|
请完成以下Java代码
|
public abstract class AbstractExposableEndpoint<O extends Operation> implements ExposableEndpoint<O> {
private final EndpointId id;
private final Access defaultAccess;
private final List<O> operations;
/**
* Create a new {@link AbstractExposableEndpoint} instance.
* @param id the endpoint id
* @param defaultAccess access to the endpoint that is permitted by default
* @param operations the endpoint operations
* @since 3.4.0
*/
public AbstractExposableEndpoint(EndpointId id, Access defaultAccess, Collection<? extends O> operations) {
Assert.notNull(id, "'id' must not be null");
Assert.notNull(operations, "'operations' must not be null");
this.id = id;
this.defaultAccess = defaultAccess;
this.operations = List.copyOf(operations);
}
@Override
|
public EndpointId getEndpointId() {
return this.id;
}
@Override
public Access getDefaultAccess() {
return this.defaultAccess;
}
@Override
public Collection<O> getOperations() {
return this.operations;
}
}
|
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\AbstractExposableEndpoint.java
| 1
|
请完成以下Java代码
|
final class HUsToReceiveHUEditorViewCustomizer implements HUEditorViewCustomizer
{
public static final transient HUsToReceiveHUEditorViewCustomizer instance = new HUsToReceiveHUEditorViewCustomizer();
private HUsToReceiveHUEditorViewCustomizer()
{
}
@Override
public String getReferencingTableNameToMatch()
{
return I_M_ReceiptSchedule.Table_Name;
}
@Override
public HUEditorRowIsProcessedPredicate getHUEditorRowIsProcessedPredicate()
|
{
return HUEditorRowIsProcessedPredicates.IF_NOT_PLANNING_HUSTATUS;
}
@Override
public Boolean isAttributesAlwaysReadonly()
{
return Boolean.FALSE;
}
@Override
public void beforeCreate(final HUEditorViewBuilder viewBuilder)
{
viewBuilder.setParameter(WEBUI_M_HU_Transform.PARAM_CheckExistingHUsInsideView, true);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\receiptSchedule\HUsToReceiveHUEditorViewCustomizer.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public RouteLocator customRouteLocator(RouteLocatorBuilder builder,
@Value("${httpbin}") String httpbin,
MyCustomFilter myCustomFilter) {
return builder.routes()
.route("error_404", r -> r.path("/test/error_404")
.filters(f -> f.filter(myCustomFilter).filter((exchange, chain) -> switchRequestUri(exchange, chain, "error_404", "404")))
.uri(httpbin + "/status/404"))
.route("error_500", r -> r.path("/test/error_500")
.filters(f -> f.filter(myCustomFilter).filter((exchange, chain) -> switchRequestUri(exchange, chain, "error_500", "500")))
.uri(httpbin+"/status/500"))
.route("error_400", r -> r.path("/test/error_400")
.filters(f -> f.filter(myCustomFilter).filter((exchange, chain) -> switchRequestUri(exchange, chain, "error_400", "400")))
.uri(httpbin+"/status/400"))
.route("error_409", r -> r.path("/test/error_409")
.filters(f -> f.filter(myCustomFilter).filter((exchange, chain) -> switchRequestUri(exchange, chain, "error_409", "409")))
.uri(httpbin+"/status/409"))
.route("custom_rate_limit", r -> r.path("/test/custom_rate_limit").filters(f -> f.filter(myCustomFilter)).uri(httpbin+"/uuid"))
.route("custom_auth", r -> r.path("/test/custom_auth").filters(f -> f.filter(myCustomFilter)).uri(httpbin+"/api/custom_auth"))
.route("anything", r -> r.path("/test/anything")
.filters(f -> f.changeRequestUri((exchange) -> Optional.of(UriComponentsBuilder.fromUri(exchange.getRequest().getURI())
.host("httpbin.org")
.port(80)
.replacePath("/anything").build().toUri())))
.uri("http://httpbin.org"))
.build();
}
|
private Mono<Void> switchRequestUri(ServerWebExchange exchange,
GatewayFilterChain chain,
String externalUri,
String internalUri) {
ServerHttpRequest req = exchange.getRequest();
addOriginalRequestUrl(exchange, req.getURI());
String path = req.getURI().getRawPath();
String newPath = path.replaceAll("/test/" + externalUri, "/status/" + internalUri);
ServerHttpRequest request = req.mutate().path(newPath).build();
exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, request.getURI());
return chain.filter(exchange.mutate().request(request).build());
}
public static void main(String[] args) {
SpringApplication.run(Main.class, args);
}
}
|
repos\tutorials-master\spring-cloud-modules\gateway-exception-management\src\main\java\com\baeldung\errorhandling\Main.java
| 2
|
请在Spring Boot框架中完成以下Java代码
|
public BigInteger getMInOutID() {
return mInOutID;
}
/**
* Sets the value of the mInOutID property.
*
* @param value
* allowed object is
* {@link BigInteger }
*
*/
public void setMInOutID(BigInteger value) {
this.mInOutID = value;
}
/**
* Gets the value of the movementDate property.
*
* @return
* possible object is
* {@link XMLGregorianCalendar }
*
*/
public XMLGregorianCalendar getMovementDate() {
return movementDate;
}
/**
* Sets the value of the movementDate property.
*
* @param value
* allowed object is
* {@link XMLGregorianCalendar }
*
*/
public void setMovementDate(XMLGregorianCalendar value) {
this.movementDate = value;
}
/**
* Gets the value of the poReference property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getPOReference() {
return poReference;
}
|
/**
* Sets the value of the poReference property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setPOReference(String value) {
this.poReference = value;
}
/**
* Gets the value of the shipmentDocumentno property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getShipmentDocumentno() {
return shipmentDocumentno;
}
/**
* Sets the value of the shipmentDocumentno property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setShipmentDocumentno(String value) {
this.shipmentDocumentno = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop111VType.java
| 2
|
请完成以下Java代码
|
protected void configureNextAcquisitionCycle(JobAcquisitionContext acquisitionContext, JobAcquisitionStrategy acquisitionStrategy) {
acquisitionStrategy.reconfigure(acquisitionContext);
}
protected JobAcquisitionStrategy initializeAcquisitionStrategy() {
return new BackoffJobAcquisitionStrategy(jobExecutor);
}
public JobAcquisitionContext getAcquisitionContext() {
return acquisitionContext;
}
protected void executeJobs(JobAcquisitionContext context, ProcessEngineImpl currentProcessEngine, AcquiredJobs acquiredJobs) {
// submit those jobs that were acquired in previous cycles but could not be scheduled for execution
List<List<String>> additionalJobs = context.getAdditionalJobsByEngine().get(currentProcessEngine.getName());
if (additionalJobs != null) {
for (List<String> jobBatch : additionalJobs) {
LOG.executeJobs(currentProcessEngine.getName(), jobBatch);
jobExecutor.executeJobs(jobBatch, currentProcessEngine);
}
}
// submit those jobs that were acquired in the current cycle
for (List<String> jobIds : acquiredJobs.getJobIdBatches()) {
LOG.executeJobs(currentProcessEngine.getName(), jobIds);
jobExecutor.executeJobs(jobIds, currentProcessEngine);
}
}
|
protected AcquiredJobs acquireJobs(
JobAcquisitionContext context,
JobAcquisitionStrategy acquisitionStrategy,
ProcessEngineImpl currentProcessEngine) {
CommandExecutor commandExecutor = currentProcessEngine.getProcessEngineConfiguration()
.getCommandExecutorTxRequired();
int numJobsToAcquire = acquisitionStrategy.getNumJobsToAcquire(currentProcessEngine.getName());
LOG.jobsToAcquire(currentProcessEngine.getName(), numJobsToAcquire);
AcquiredJobs acquiredJobs = null;
if (numJobsToAcquire > 0) {
jobExecutor.logAcquisitionAttempt(currentProcessEngine);
acquiredJobs = commandExecutor.execute(jobExecutor.getAcquireJobsCmd(numJobsToAcquire));
}
else {
acquiredJobs = new AcquiredJobs(numJobsToAcquire);
}
context.submitAcquiredJobs(currentProcessEngine.getName(), acquiredJobs);
jobExecutor.logAcquiredJobs(currentProcessEngine, acquiredJobs.size());
jobExecutor.logAcquisitionFailureJobs(currentProcessEngine, acquiredJobs.getNumberOfJobsFailedToLock());
LOG.acquiredJobs(currentProcessEngine.getName(), acquiredJobs);
LOG.failedAcquisitionLocks(currentProcessEngine.getName(), acquiredJobs);
return acquiredJobs;
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\jobexecutor\SequentialJobAcquisitionRunnable.java
| 1
|
请完成以下Java代码
|
public List<String> segment(String text)
{
List<String> wordList = new LinkedList<String>();
segment(text, CharTable.convert(text), wordList);
return wordList;
}
@Override
public void segment(String text, String normalized, List<String> output)
{
int[] obsArray = new int[text.length()];
for (int i = 0; i < obsArray.length; i++)
{
obsArray[i] = vocabulary.idOf(normalized.substring(i, i + 1));
}
int[] tagArray = new int[text.length()];
model.predict(obsArray, tagArray);
StringBuilder result = new StringBuilder();
result.append(text.charAt(0));
for (int i = 1; i < tagArray.length; i++)
{
if (tagArray[i] == tagSet.B || tagArray[i] == tagSet.S)
{
output.add(result.toString());
result.setLength(0);
}
result.append(text.charAt(i));
}
if (result.length() != 0)
{
output.add(result.toString());
}
}
@Override
protected List<String[]> convertToSequence(Sentence sentence)
{
List<String[]> charList = new LinkedList<String[]>();
for (Word w : sentence.toSimpleWordList())
{
String word = CharTable.convert(w.value);
if (word.length() == 1)
{
charList.add(new String[]{word, "S"});
}
else
|
{
charList.add(new String[]{word.substring(0, 1), "B"});
for (int i = 1; i < word.length() - 1; ++i)
{
charList.add(new String[]{word.substring(i, i + 1), "M"});
}
charList.add(new String[]{word.substring(word.length() - 1), "E"});
}
}
return charList;
}
@Override
protected TagSet getTagSet()
{
return tagSet;
}
/**
* 获取兼容旧的Segment接口
*
* @return
*/
public Segment toSegment()
{
return new Segment()
{
@Override
protected List<Term> segSentence(char[] sentence)
{
List<String> wordList = segment(new String(sentence));
List<Term> termList = new LinkedList<Term>();
for (String word : wordList)
{
termList.add(new Term(word, null));
}
return termList;
}
}.enableCustomDictionary(false);
}
}
|
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\hmm\HMMSegmenter.java
| 1
|
请完成以下Java代码
|
private static void exchange() {
Book book = new Book(
"Effective Java",
"Joshua Bloch",
2001);
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("username", "password");
ResponseEntity<Book> response = restTemplate.exchange(
"https://api.bookstore.com",
HttpMethod.POST,
new HttpEntity<>(book, headers),
Book.class);
}
private static void execute() {
ResponseEntity<Book> response = restTemplate.execute(
"https://api.bookstore.com",
HttpMethod.POST,
new RequestCallback() {
@Override
public void doWithRequest(ClientHttpRequest request) throws IOException {
// Create or decorate the request object as needed
}
},
new ResponseExtractor<ResponseEntity<Book>>() {
@Override
public ResponseEntity<Book> extractData(ClientHttpResponse response) throws IOException {
// extract required data from response
return null;
}
|
}
);
// Could also use some factory methods in RestTemplate for
// the request callback and/or response extractor
Book book = new Book(
"Reactive Spring",
"Josh Long",
2020);
response = restTemplate.execute(
"https://api.bookstore.com",
HttpMethod.POST,
restTemplate.httpEntityCallback(book),
restTemplate.responseEntityExtractor(Book.class)
);
}
private static class Book {
String title;
String author;
int yearPublished;
public Book(String title, String author, int yearPublished) {
this.title = title;
this.author = author;
this.yearPublished = yearPublished;
}
}
}
|
repos\tutorials-master\spring-web-modules\spring-resttemplate-2\src\main\java\com\baeldung\resttemplate\json\methods\RestTemplateMethodsApplication.java
| 1
|
请完成以下Java代码
|
public class HistoricCaseActivityInstanceManager extends AbstractHistoricManager {
public void deleteHistoricCaseActivityInstancesByCaseInstanceIds(List<String> historicCaseInstanceIds) {
if (isHistoryEnabled()) {
getDbEntityManager().delete(HistoricCaseActivityInstanceEntity.class, "deleteHistoricCaseActivityInstancesByCaseInstanceIds", historicCaseInstanceIds);
}
}
public void insertHistoricCaseActivityInstance(HistoricCaseActivityInstanceEntity historicCaseActivityInstance) {
getDbEntityManager().insert(historicCaseActivityInstance);
}
public HistoricCaseActivityInstanceEntity findHistoricCaseActivityInstance(String caseActivityId, String caseInstanceId) {
Map<String, String> parameters = new HashMap<String, String>();
parameters.put("caseActivityId", caseActivityId);
parameters.put("caseInstanceId", caseInstanceId);
return (HistoricCaseActivityInstanceEntity) getDbEntityManager().selectOne("selectHistoricCaseActivityInstance", parameters);
}
public long findHistoricCaseActivityInstanceCountByQueryCriteria(HistoricCaseActivityInstanceQueryImpl historicCaseActivityInstanceQuery) {
configureHistoricCaseActivityInstanceQuery(historicCaseActivityInstanceQuery);
return (Long) getDbEntityManager().selectOne("selectHistoricCaseActivityInstanceCountByQueryCriteria", historicCaseActivityInstanceQuery);
|
}
@SuppressWarnings("unchecked")
public List<HistoricCaseActivityInstance> findHistoricCaseActivityInstancesByQueryCriteria(HistoricCaseActivityInstanceQueryImpl historicCaseActivityInstanceQuery, Page page) {
configureHistoricCaseActivityInstanceQuery(historicCaseActivityInstanceQuery);
return getDbEntityManager().selectList("selectHistoricCaseActivityInstancesByQueryCriteria", historicCaseActivityInstanceQuery, page);
}
@SuppressWarnings("unchecked")
public List<HistoricCaseActivityInstance> findHistoricCaseActivityInstancesByNativeQuery(Map<String, Object> parameterMap, int firstResult, int maxResults) {
return getDbEntityManager().selectListWithRawParameter("selectHistoricCaseActivityInstanceByNativeQuery", parameterMap, firstResult, maxResults);
}
public long findHistoricCaseActivityInstanceCountByNativeQuery(Map<String, Object> parameterMap) {
return (Long) getDbEntityManager().selectOne("selectHistoricCaseActivityInstanceCountByNativeQuery", parameterMap);
}
protected void configureHistoricCaseActivityInstanceQuery(HistoricCaseActivityInstanceQueryImpl query) {
getTenantManager().configureQuery(query);
}
}
|
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricCaseActivityInstanceManager.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public void setDISCREPANCYDESC(String value) {
this.discrepancydesc = value;
}
/**
* Gets the value of the discrepancydate1 property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getDISCREPANCYDATE1() {
return discrepancydate1;
}
/**
* Sets the value of the discrepancydate1 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDISCREPANCYDATE1(String value) {
this.discrepancydate1 = value;
}
/**
* Gets the value of the discrepancydate2 property.
*
* @return
* possible object is
* {@link String }
|
*
*/
public String getDISCREPANCYDATE2() {
return discrepancydate2;
}
/**
* Sets the value of the discrepancydate2 property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setDISCREPANCYDATE2(String value) {
this.discrepancydate2 = value;
}
}
|
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_stepcom_desadv\de\metas\edi\esb\jaxb\stepcom\desadv\DQVAR1.java
| 2
|
请完成以下Java代码
|
public static final Number mul(TypeConverter converter, Object o1, Object o2) {
if (o1 == null && o2 == null) {
return LONG_ZERO;
}
if (o1 instanceof BigDecimal || o2 instanceof BigDecimal) {
return converter.convert(o1, BigDecimal.class).multiply(converter.convert(o2, BigDecimal.class));
}
if (isFloatOrDoubleOrDotEe(o1) || isFloatOrDoubleOrDotEe(o2)) {
if (o1 instanceof BigInteger || o2 instanceof BigInteger) {
return converter.convert(o1, BigDecimal.class).multiply(converter.convert(o2, BigDecimal.class));
}
return converter.convert(o1, Double.class) * converter.convert(o2, Double.class);
}
if (o1 instanceof BigInteger || o2 instanceof BigInteger) {
return converter.convert(o1, BigInteger.class).multiply(converter.convert(o2, BigInteger.class));
}
return converter.convert(o1, Long.class) * converter.convert(o2, Long.class);
}
public static final Number div(TypeConverter converter, Object o1, Object o2) {
if (o1 == null && o2 == null) {
return LONG_ZERO;
}
if (isBigDecimalOrBigInteger(o1) || isBigDecimalOrBigInteger(o2)) {
return converter.convert(o1, BigDecimal.class).divide(converter.convert(o2, BigDecimal.class), RoundingMode.HALF_UP);
}
return converter.convert(o1, Double.class) / converter.convert(o2, Double.class);
}
public static final Number mod(TypeConverter converter, Object o1, Object o2) {
if (o1 == null && o2 == null) {
return LONG_ZERO;
}
if (isBigDecimalOrFloatOrDoubleOrDotEe(o1) || isBigDecimalOrFloatOrDoubleOrDotEe(o2)) {
return converter.convert(o1, Double.class) % converter.convert(o2, Double.class);
}
if (o1 instanceof BigInteger || o2 instanceof BigInteger) {
return converter.convert(o1, BigInteger.class).remainder(converter.convert(o2, BigInteger.class));
}
return converter.convert(o1, Long.class) % converter.convert(o2, Long.class);
}
public static final Number neg(TypeConverter converter, Object value) {
if (value == null) {
return LONG_ZERO;
}
if (value instanceof BigDecimal) {
return ((BigDecimal)value).negate();
}
if (value instanceof BigInteger) {
return ((BigInteger)value).negate();
}
if (value instanceof Double) {
return -((Double) value).doubleValue();
|
}
if (value instanceof Float) {
return -((Float) value).floatValue();
}
if (value instanceof String) {
if (isDotEe((String)value)) {
return -converter.convert(value, Double.class).doubleValue();
}
return -converter.convert(value, Long.class).longValue();
}
if (value instanceof Long) {
return -((Long) value).longValue();
}
if (value instanceof Integer) {
return -((Integer) value).intValue();
}
if (value instanceof Short) {
return (short) -((Short) value).shortValue();
}
if (value instanceof Byte) {
return (byte) -((Byte) value).byteValue();
}
throw new ELException(LocalMessages.get("error.negate", value.getClass()));
}
}
|
repos\camunda-bpm-platform-master\juel\src\main\java\org\camunda\bpm\impl\juel\NumberOperations.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
public class SysDepartRoleUserServiceImpl extends ServiceImpl<SysDepartRoleUserMapper, SysDepartRoleUser> implements ISysDepartRoleUserService {
@Autowired
private SysDepartRoleMapper sysDepartRoleMapper;
@Override
public void deptRoleUserAdd(String userId, String newRoleId, String oldRoleId) {
List<String> add = getDiff(oldRoleId,newRoleId);
if(add!=null && add.size()>0) {
List<SysDepartRoleUser> list = new ArrayList<>();
for (String roleId : add) {
if(oConvertUtils.isNotEmpty(roleId)) {
SysDepartRoleUser rolepms = new SysDepartRoleUser(userId, roleId);
list.add(rolepms);
}
}
this.saveBatch(list);
}
List<String> remove = getDiff(newRoleId,oldRoleId);
if(remove!=null && remove.size()>0) {
for (String roleId : remove) {
this.remove(new QueryWrapper<SysDepartRoleUser>().lambda().eq(SysDepartRoleUser::getUserId, userId).eq(SysDepartRoleUser::getDroleId, roleId));
}
}
}
@Override
@Transactional(rollbackFor = Exception.class)
public void removeDeptRoleUser(List<String> userIds, String depId) {
for(String userId : userIds){
List<SysDepartRole> sysDepartRoleList = sysDepartRoleMapper.selectList(new QueryWrapper<SysDepartRole>().eq("depart_id",depId));
List<String> roleIds = sysDepartRoleList.stream().map(SysDepartRole::getId).collect(Collectors.toList());
if(roleIds != null && roleIds.size()>0){
QueryWrapper<SysDepartRoleUser> query = new QueryWrapper<>();
query.eq("user_id",userId).in("drole_id",roleIds);
this.remove(query);
}
}
}
/**
* 从diff中找出main中没有的元素
* @param main
* @param diff
* @return
|
*/
private List<String> getDiff(String main, String diff){
if(oConvertUtils.isEmpty(diff)) {
return null;
}
if(oConvertUtils.isEmpty(main)) {
return Arrays.asList(diff.split(","));
}
String[] mainArr = main.split(",");
String[] diffArr = diff.split(",");
Map<String, Integer> map = new HashMap(5);
for (String string : mainArr) {
map.put(string, 1);
}
List<String> res = new ArrayList<String>();
for (String key : diffArr) {
if(oConvertUtils.isNotEmpty(key) && !map.containsKey(key)) {
res.add(key);
}
}
return res;
}
}
|
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\service\impl\SysDepartRoleUserServiceImpl.java
| 2
|
请完成以下Java代码
|
public int getQtyTU()
{
return _qtyTU;
}
@Override
public String getTUName()
{
return _tuPIName;
}
public final I_M_HU_PI getTU_HU_PI()
{
return _tuPI;
}
@Override
public IHandlingUnitsInfo add(final IHandlingUnitsInfo infoToAdd)
{
if (infoToAdd == null)
{
return this;
}
//
// TU PI
final I_M_HU_PI tuPI = getTU_HU_PI();
// TODO make sure tuPIs are compatible
//
// Qty TU
final int qtyTU = getQtyTU();
final int qtyTU_ToAdd = infoToAdd.getQtyTU();
|
final int qtyTU_New = qtyTU + qtyTU_ToAdd;
final boolean isReadWrite = false;
final HUHandlingUnitsInfo infoNew = new HUHandlingUnitsInfo(tuPI, qtyTU_New, isReadWrite);
return infoNew;
}
protected void setQtyTUInner(final int qtyTU)
{
Check.errorIf(!_isQtyWritable, "This instance {} is read-only", this);
_qtyTU = qtyTU;
}
@Override
public String toString()
{
return ObjectUtils.toString(this);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\materialtracking\spi\impl\HUHandlingUnitsInfo.java
| 1
|
请完成以下Spring Boot application配置
|
server.port: 8085
spring:
application:
name: echo
eureka:
instance:
hostname: localhost
leaseRenewalIntervalInSeconds: 1
leaseExpirationDurationInSeconds: 2
client:
service-ur
|
l:
defaultZone: http://127.0.0.1:8761/eureka
healthcheck:
enabled: true
|
repos\tutorials-master\spring-cloud-modules\spring-cloud-netflix-sidecar\spring-cloud-netflix-sidecar-echo-demo\src\main\resources\application.yml
| 2
|
请完成以下Java代码
|
public Object getHeaderAggregationKey()
{
// the pricelist is no aggregation criterion, because
// the orderline's price is manually set, i.e. the pricing system is not invoked
// and we often want to combine candidates with C_Flatrate_Terms (-> no pricelist, price take from the term)
// and candidates without a term, where the candidate's price is computed by the pricing system
return Util.mkKey(getAD_Org_ID(),
getM_Warehouse_ID(),
getC_BPartner_ID(),
getDatePromised().getTime(),
getM_PricingSystem_ID(),
// getM_PriceList_ID(),
getC_Currency_ID());
}
/**
* This method is actually used by the item aggregation key builder of {@link OrderLinesAggregator}.
*
* @return
*/
public Object getLineAggregationKey()
{
return Util.mkKey(
getM_Product_ID(),
getAttributeSetInstanceId().getRepoId(),
getC_UOM_ID(),
getM_HU_PI_Item_Product_ID(),
|
getPrice());
}
/**
* Creates and {@link I_PMM_PurchaseCandidate} to {@link I_C_OrderLine} line allocation using the whole candidate's QtyToOrder.
*
* @param orderLine
*/
/* package */void createAllocation(final I_C_OrderLine orderLine)
{
Check.assumeNotNull(orderLine, "orderLine not null");
final BigDecimal qtyToOrder = getQtyToOrder();
final BigDecimal qtyToOrderTU = getQtyToOrder_TU();
//
// Create allocation
final I_PMM_PurchaseCandidate_OrderLine alloc = InterfaceWrapperHelper.newInstance(I_PMM_PurchaseCandidate_OrderLine.class, orderLine);
alloc.setC_OrderLine(orderLine);
alloc.setPMM_PurchaseCandidate(model);
alloc.setQtyOrdered(qtyToOrder);
alloc.setQtyOrdered_TU(qtyToOrderTU);
InterfaceWrapperHelper.save(alloc);
// NOTE: on alloc's save we expect the model's quantities to be updated
InterfaceWrapperHelper.markStaled(model); // FIXME: workaround because we are modifying the model from alloc's model interceptor
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\order\impl\PurchaseCandidate.java
| 1
|
请完成以下Java代码
|
protected final ViewId getInitialViewId()
{
return getView().getInitialViewId();
}
protected final ProductsProposalView getInitialView()
{
return ProductsProposalView.cast(viewsRepo.getView(getInitialViewId()));
}
protected final void closeAllViewsAndShowInitialView()
{
closeAllViewsExcludingInitialView();
afterCloseOpenView(getInitialViewId());
}
private final void closeAllViewsExcludingInitialView()
{
IView currentView = getView();
while (currentView != null && currentView.getParentViewId() != null)
{
try
{
viewsRepo.closeView(currentView.getViewId(), ViewCloseAction.CANCEL);
}
catch (Exception ex)
{
logger.warn("Failed closing view {}. Ignored", currentView, ex);
|
}
final ViewId viewId = currentView.getParentViewId();
currentView = viewsRepo.getViewIfExists(viewId);
}
}
protected final void afterCloseOpenView(final ViewId viewId)
{
getResult().setWebuiViewToOpen(WebuiViewToOpen.builder()
.viewId(viewId.toJson())
.target(ViewOpenTarget.ModalOverlay)
.build());
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\process\ProductsProposalViewBasedProcess.java
| 1
|
请在Spring Boot框架中完成以下Java代码
|
static final class StaticAuthenticationManagerResolver
implements AuthenticationManagerResolver<HttpServletRequest> {
private final AuthenticationManager authenticationManager;
StaticAuthenticationManagerResolver(AuthenticationManager authenticationManager) {
this.authenticationManager = authenticationManager;
}
@Override
public AuthenticationManager resolve(HttpServletRequest context) {
return this.authenticationManager;
}
}
static final class NimbusJwtDecoderJwkSetUriFactoryBean implements FactoryBean<JwtDecoder> {
private final String jwkSetUri;
NimbusJwtDecoderJwkSetUriFactoryBean(String jwkSetUri) {
this.jwkSetUri = jwkSetUri;
}
@Override
public JwtDecoder getObject() {
return NimbusJwtDecoder.withJwkSetUri(this.jwkSetUri).build();
}
@Override
public Class<?> getObjectType() {
return JwtDecoder.class;
}
}
static final class BearerTokenRequestMatcher implements RequestMatcher {
private final BearerTokenResolver bearerTokenResolver;
BearerTokenRequestMatcher(BearerTokenResolver bearerTokenResolver) {
Assert.notNull(bearerTokenResolver, "bearerTokenResolver cannot be null");
this.bearerTokenResolver = bearerTokenResolver;
}
@Override
public boolean matches(HttpServletRequest request) {
try {
return this.bearerTokenResolver.resolve(request) != null;
}
|
catch (OAuth2AuthenticationException ex) {
return false;
}
}
}
static final class BearerTokenAuthenticationRequestMatcher implements RequestMatcher {
private final AuthenticationConverter authenticationConverter;
BearerTokenAuthenticationRequestMatcher() {
this.authenticationConverter = new BearerTokenAuthenticationConverter();
}
BearerTokenAuthenticationRequestMatcher(AuthenticationConverter authenticationConverter) {
Assert.notNull(authenticationConverter, "authenticationConverter cannot be null");
this.authenticationConverter = authenticationConverter;
}
@Override
public boolean matches(HttpServletRequest request) {
try {
return this.authenticationConverter.convert(request) != null;
}
catch (OAuth2AuthenticationException ex) {
return false;
}
}
}
}
|
repos\spring-security-main\config\src\main\java\org\springframework\security\config\http\OAuth2ResourceServerBeanDefinitionParser.java
| 2
|
请完成以下Java代码
|
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
|
请在Spring Boot框架中完成以下Java代码
|
private Optional<Quantity> extractTargetCatchWeight(@NonNull final JsonManufacturingOrderEvent.ReceiveFrom receiveFrom)
{
if (receiveFrom.getCatchWeight() == null || Check.isBlank(receiveFrom.getCatchWeightUomSymbol()))
{
return Optional.empty();
}
return uomDAO.getBySymbol(receiveFrom.getCatchWeightUomSymbol())
.map(uom -> Quantity.of(receiveFrom.getCatchWeight(), uom));
}
public QueryLimit getLaunchersLimit()
{
final int limitInt = sysConfigBL.getIntValue(Constants.SYSCONFIG_LaunchersLimit, -100);
return limitInt == -100
? Constants.DEFAULT_LaunchersLimit
: QueryLimit.ofInt(limitInt);
}
public ManufacturingJob autoIssueWhatWasReceived(
@NonNull final ManufacturingJob job,
@NonNull final RawMaterialsIssueStrategy issueStrategy)
|
{
return newIssueWhatWasReceivedCommand()
.job(job)
.issueStrategy(issueStrategy)
.build().execute();
}
public IssueWhatWasReceivedCommandBuilder newIssueWhatWasReceivedCommand()
{
return IssueWhatWasReceivedCommand.builder()
.issueScheduleService(ppOrderIssueScheduleService)
.jobService(this)
.ppOrderSourceHUService(ppOrderSourceHUService)
.sourceHUsService(sourceHUsService);
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing.rest-api\src\main\java\de\metas\manufacturing\job\service\ManufacturingJobService.java
| 2
|
请完成以下Java代码
|
public String getFileName() {
return fileName;
}
/**
* Sets the full filename path
*
* @param fileName the full filename path
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* Gets the bytes that represent the contents of the file
*
* @return the bytes that represent the contents of the file
*/
public byte[] getBytes() {
return bytes;
}
/**
* Sets the bytes that represent the contents of the file
*
* @param bytes the bytes that represent the contents of the file
*/
public void setBytes(byte[] bytes) {
|
this.bytes = bytes;
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("File [fileName=");
builder.append(fileName);
builder.append(", bytes=");
builder.append(Arrays.toString(bytes));
builder.append("]");
return builder.toString();
}
}
}
|
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\SparkplugMetricUtil.java
| 1
|
请完成以下Java代码
|
public String getAccountNo() {
return accountNo;
}
public void setAccountNo(String accountNo) {
this.accountNo = accountNo;
}
public String getAccountStatus() {
return accountStatus;
}
public void setAccountStatus(String accountStatus) {
this.accountStatus = accountStatus;
}
public Long getBalanceBegin() {
return balanceBegin;
}
public void setBalanceBegin(Long balanceBegin) {
this.balanceBegin = balanceBegin;
}
public Long getBalanceEnd() {
return balanceEnd;
}
public void setBalanceEnd(Long balanceEnd) {
this.balanceEnd = balanceEnd;
}
public String getCreateDateBegin() {
return createDateBegin;
}
|
public void setCreateDateBegin(String createDateBegin) {
this.createDateBegin = createDateBegin;
}
public String getCreateDateEnd() {
return createDateEnd;
}
public void setCreateDateEnd(String createDateEnd) {
this.createDateEnd = createDateEnd;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
}
|
repos\spring-boot-leaning-master\2.x_data\2-4 MongoDB 支持动态 SQL、分页方案\spring-boot-mongodb-page\src\main\java\com\neo\param\AccountPageParam.java
| 1
|
请完成以下Java代码
|
public PriceListVersionId getPriceListVersionId(final PriceListId priceListId, final ZonedDateTime date)
{
return priceListsRepo.retrievePriceListVersionId(priceListId, date);
}
public I_M_PriceList_Version getPriceListVersionOrNull(final PriceListId priceListId, final ZonedDateTime date, final Boolean processedPLVFiltering)
{
return priceListsRepo.retrievePriceListVersionOrNull(priceListId, date, processedPLVFiltering);
}
public ImmutableList<ProductPrice> getProductPrices(@NonNull final PriceListVersionId priceListVersionId)
{
return priceListsRepo.retrieveProductPrices(priceListVersionId)
.map(productPriceRepository::toProductPrice)
.collect(ImmutableList.toImmutableList());
}
@NonNull
public ImmutableList<I_M_ProductPrice> getProductPricesByPLVAndProduct(@NonNull final PriceListVersionId priceListVersionId, @NonNull final ProductId productId)
{
return priceListsRepo.retrieveProductPrices(priceListVersionId, productId);
}
@NonNull
public ImmutableMap<ProductId, String> getProductValues(final ImmutableSet<ProductId> productIds)
{
return productsService.getProductValues(productIds);
}
@NonNull
public String getProductValue(@NonNull final ProductId productId)
{
return productsService.getProductValue(productId);
}
// TODO move this method to de.metas.bpartner.service.IBPartnerDAO since it has nothing to do with price list
// TODO: IdentifierString must also be moved to the module containing IBPartnerDAO
public Optional<BPartnerId> getBPartnerId(final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final BPartnerQuery query = createBPartnerQuery(bpartnerIdentifier, orgId);
return bpartnersRepo.retrieveBPartnerIdBy(query);
}
private static BPartnerQuery createBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier, final OrgId orgId)
{
final Type type = bpartnerIdentifier.getType();
final BPartnerQuery.BPartnerQueryBuilder builder = BPartnerQuery.builder();
if (orgId != null)
{
builder.onlyOrgId(orgId);
|
}
if (Type.METASFRESH_ID.equals(type))
{
return builder
.bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId))
.build();
}
else if (Type.EXTERNAL_ID.equals(type))
{
return builder
.externalId(bpartnerIdentifier.asExternalId())
.build();
}
else if (Type.VALUE.equals(type))
{
return builder
.bpartnerValue(bpartnerIdentifier.asValue())
.build();
}
else if (Type.GLN.equals(type))
{
return builder
.gln(bpartnerIdentifier.asGLN())
.build();
}
else
{
throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier);
}
}
}
|
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\bpartner_pricelist\BpartnerPriceListServicesFacade.java
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.