instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public class Config { private String toDoEndpoint; private String postEndpoint; private String environmentName; private Credentials toDoCredentials; private Credentials postCredentials; public String getToDoEndpoint() { return toDoEndpoint; } public void setToDoEndpoint(String toDoEndpoint) { this.toDoEndpoint = toDoEndpoint; } public String getPostEndpoint() { return postEndpoint; } public void setPostEndpoint(String postEndpoint) { this.postEndpoint = postEndpoint; } public String getEnvironmentName() { return environmentName; } public void setEnvironmentName(String environmentName) { this.environmentName = environmentName; }
public Credentials getToDoCredentials() { return toDoCredentials; } public void setToDoCredentials(Credentials toDoCredentials) { this.toDoCredentials = toDoCredentials; } public Credentials getPostCredentials() { return postCredentials; } public void setPostCredentials(Credentials postCredentials) { this.postCredentials = postCredentials; } }
repos\tutorials-master\aws-modules\aws-lambda-modules\todo-reminder-lambda\ToDoFunction\src\main\java\com\baeldung\lambda\todo\config\Config.java
2
请完成以下Java代码
public Font getFont() { return m_retFont; } // getFont /** * ActionListener * @param e */ @Override public void actionPerformed(ActionEvent e) { if (m_setting) return; if (e.getSource() == bOK) { m_retFont = m_font; dispose(); } else if (e.getSource() == bCancel) dispose(); else if (e.getSource() == fontName) { String s = fontName.getSelectedItem().toString(); m_font = new Font(s, m_font.getStyle(), m_font.getSize()); } else if (e.getSource() == fontSize) { String s = fontSize.getSelectedItem().toString(); m_font = new Font(m_font.getName(), m_font.getStyle(), Integer.parseInt(s)); } else if (e.getSource() == fontStyle) { FontStyle fs = fontStyle.getSelectedItem(); m_font = new Font(m_font.getName(), fs.getID(), m_font.getSize()); } // System.out.println("NewFont - " + m_font.toString()); setFont(m_font); } // actionPerformed } // FontChooser /**
* Font Style Value Object */ class FontStyle { /** * Create FontStyle * @param name * @param id */ public FontStyle(String name, int id) { m_name = name; m_id = id; } // FontStyle private String m_name; private int m_id; /** * Get Name * @return name */ @Override public String toString() { return m_name; } // getName /** * Get int value of Font Style * @return id */ public int getID() { return m_id; } // getID } // FontStyle
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\FontChooser.java
1
请完成以下Java代码
class SqlServerR2dbcDockerComposeConnectionDetailsFactory extends DockerComposeConnectionDetailsFactory<R2dbcConnectionDetails> { SqlServerR2dbcDockerComposeConnectionDetailsFactory() { super("mssql/server", "io.r2dbc.spi.ConnectionFactoryOptions"); } @Override protected R2dbcConnectionDetails getDockerComposeConnectionDetails(DockerComposeConnectionSource source) { return new SqlServerR2dbcDockerComposeConnectionDetails(source.getRunningService()); } /** * {@link R2dbcConnectionDetails} backed by a {@code mssql} {@link RunningService}. */ static class SqlServerR2dbcDockerComposeConnectionDetails extends DockerComposeConnectionDetails implements R2dbcConnectionDetails { private static final ConnectionFactoryOptionsBuilder connectionFactoryOptionsBuilder = new ConnectionFactoryOptionsBuilder(
"mssql", 1433); private final ConnectionFactoryOptions connectionFactoryOptions; SqlServerR2dbcDockerComposeConnectionDetails(RunningService service) { super(service); SqlServerEnvironment environment = new SqlServerEnvironment(service.env()); this.connectionFactoryOptions = connectionFactoryOptionsBuilder.build(service, "", environment.getUsername(), environment.getPassword()); } @Override public ConnectionFactoryOptions getConnectionFactoryOptions() { return this.connectionFactoryOptions; } } }
repos\spring-boot-4.0.1\module\spring-boot-r2dbc\src\main\java\org\springframework\boot\r2dbc\docker\compose\SqlServerR2dbcDockerComposeConnectionDetailsFactory.java
1
请完成以下Java代码
public User userStatus(Integer userStatus) { this.userStatus = userStatus; return this; } /** * User Status * @return userStatus **/ @ApiModelProperty(value = "User Status") public Integer getUserStatus() { return userStatus; } public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } User user = (User) o; return Objects.equals(this.id, user.id) && Objects.equals(this.username, user.username) && Objects.equals(this.firstName, user.firstName) && Objects.equals(this.lastName, user.lastName) && Objects.equals(this.email, user.email) && Objects.equals(this.password, user.password) && Objects.equals(this.phone, user.phone) && Objects.equals(this.userStatus, user.userStatus); } @Override public int hashCode() { return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); } @Override
public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class User {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" username: ").append(toIndentedString(username)).append("\n"); sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); sb.append(" email: ").append(toIndentedString(email)).append("\n"); sb.append(" password: ").append(toIndentedString(password)).append("\n"); sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); sb.append(" userStatus: ").append(toIndentedString(userStatus)).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\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\User.java
1
请完成以下Java代码
public int getLine() { return orderLine.getLine(); } public ZonedDateTime getDatePromised() { return orderLine.getDatePromised(); } public ProductId getProductId() { return orderLine.getProductId(); }
public AttributeSetInstanceId getAsiId() { return orderLine.getAsiId(); } public Quantity getOrderedQty() { return orderLine.getOrderedQty(); } public ProductPrice getPriceActual() { return orderLine.getPriceActual(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.purchasecandidate.base\src\main\java\de\metas\purchasecandidate\SalesOrderLine.java
1
请完成以下Java代码
public class TbCheckpointNode implements TbNode { private String queueName; @Override public void init(TbContext ctx, TbNodeConfiguration configuration) throws TbNodeException { queueName = ctx.getQueueName(); } @Override public void onMsg(TbContext ctx, TbMsg msg) { ctx.enqueueForTellNext(msg, queueName, TbNodeConnectionType.SUCCESS, () -> ctx.ack(msg), error -> ctx.tellFailure(msg, error)); } @Override public TbPair<Boolean, JsonNode> upgrade(int fromVersion, JsonNode oldConfiguration) throws TbNodeException {
boolean hasChanges = false; switch (fromVersion) { case 0: if (oldConfiguration.has(QUEUE_NAME)) { hasChanges = true; ((ObjectNode) oldConfiguration).remove(QUEUE_NAME); } break; default: break; } return new TbPair<>(hasChanges, oldConfiguration); } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\flow\TbCheckpointNode.java
1
请完成以下Java代码
public class ParaModel { @ApiModelProperty(allowableValues = "省") private String provice; @ApiModelProperty(allowableValues = "地区") private String area; private List<Street> streets; @Override public String toString() { return "ParaModel{" + "provice='" + provice + '\'' + ", area='" + area + '\'' + ", streets=" + streets + '}'; } public String getProvice() { return provice; }
public void setProvice(String provice) { this.provice = provice; } public String getArea() { return area; } public void setArea(String area) { this.area = area; } public List<Street> getStreets() { return streets; } public void setStreets(List<Street> streets) { this.streets = streets; } }
repos\spring-boot-quick-master\quick-swagger\src\main\java\com\quick\po\ParaModel.java
1
请完成以下Java代码
private void writeObject(ObjectOutputStream out) throws IOException { loseWeight(); out.writeInt(size); out.writeObject(data); out.writeInt(linearExpandFactor); out.writeBoolean(exponentialExpanding); out.writeDouble(exponentialExpandFactor); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { size = in.readInt(); data = (int[]) in.readObject(); linearExpandFactor = in.readInt();
exponentialExpanding = in.readBoolean(); exponentialExpandFactor = in.readDouble(); } @Override public String toString() { ArrayList<Integer> head = new ArrayList<Integer>(20); for (int i = 0; i < Math.min(size, 20); ++i) { head.add(data[i]); } return head.toString(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\trie\datrie\IntArrayList.java
1
请完成以下Java代码
public class RouteToRequestUrlFilter implements GlobalFilter, Ordered { /** * Order of Route to URL. */ public static final int ROUTE_TO_URL_FILTER_ORDER = 10000; private static final Log log = LogFactory.getLog(RouteToRequestUrlFilter.class); private static final String SCHEME_REGEX = "[a-zA-Z]([a-zA-Z]|\\d|\\+|\\.|-)*:.*"; static final Pattern schemePattern = Pattern.compile(SCHEME_REGEX); /* for testing */ static boolean hasAnotherScheme(URI uri) { return schemePattern.matcher(uri.getSchemeSpecificPart()).matches() && uri.getHost() == null && uri.getRawPath() == null; } @Override public int getOrder() { return ROUTE_TO_URL_FILTER_ORDER; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { Route route = exchange.getAttribute(GATEWAY_ROUTE_ATTR); if (route == null) { return chain.filter(exchange); } log.trace("RouteToRequestUrlFilter start"); URI uri = exchange.getRequest().getURI(); boolean encoded = containsEncodedParts(uri);
URI routeUri = route.getUri(); if (hasAnotherScheme(routeUri)) { // this is a special url, save scheme to special attribute // replace routeUri with schemeSpecificPart exchange.getAttributes().put(GATEWAY_SCHEME_PREFIX_ATTR, routeUri.getScheme()); routeUri = URI.create(routeUri.getSchemeSpecificPart()); } if ("lb".equalsIgnoreCase(routeUri.getScheme()) && routeUri.getHost() == null) { // Load balanced URIs should always have a host. If the host is null it is // most likely because the host name was invalid (for example included an // underscore) throw new IllegalStateException("Invalid host: " + routeUri.toString()); } URI mergedUrl = UriComponentsBuilder.fromUri(uri) // .uri(routeUri) .scheme(routeUri.getScheme()) .host(routeUri.getHost()) .port(routeUri.getPort()) .build(encoded) .toUri(); exchange.getAttributes().put(GATEWAY_REQUEST_URL_ATTR, mergedUrl); return chain.filter(exchange); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\RouteToRequestUrlFilter.java
1
请在Spring Boot框架中完成以下Java代码
public class NettyServer { private Logger logger = LoggerFactory.getLogger(getClass()); @Value("${netty.port}") private Integer port; @Autowired private NettyServerHandlerInitializer nettyServerHandlerInitializer; /** * boss 线程组,用于服务端接受客户端的连接 */ private EventLoopGroup bossGroup = new NioEventLoopGroup(); /** * worker 线程组,用于服务端接受客户端的数据读写 */ private EventLoopGroup workerGroup = new NioEventLoopGroup(); /** * Netty Server Channel */ private Channel channel; /** * 启动 Netty Server */ @PostConstruct public void start() throws InterruptedException { // 创建 ServerBootstrap 对象,用于 Netty Server 启动 ServerBootstrap bootstrap = new ServerBootstrap(); // 设置 ServerBootstrap 的各种属性 bootstrap.group(bossGroup, workerGroup) // 设置两个 EventLoopGroup 对象 .channel(NioServerSocketChannel.class) // 指定 Channel 为服务端 NioServerSocketChannel .localAddress(new InetSocketAddress(port)) // 设置 Netty Server 的端口
.option(ChannelOption.SO_BACKLOG, 1024) // 服务端 accept 队列的大小 .childOption(ChannelOption.SO_KEEPALIVE, true) // TCP Keepalive 机制,实现 TCP 层级的心跳保活功能 .childOption(ChannelOption.TCP_NODELAY, true) // 允许较小的数据包的发送,降低延迟 .childHandler(nettyServerHandlerInitializer); // 绑定端口,并同步等待成功,即启动服务端 ChannelFuture future = bootstrap.bind().sync(); if (future.isSuccess()) { channel = future.channel(); logger.info("[start][Netty Server 启动在 {} 端口]", port); } } /** * 关闭 Netty Server */ @PreDestroy public void shutdown() { // 关闭 Netty Server if (channel != null) { channel.close(); } // 优雅关闭两个 EventLoopGroup 对象 bossGroup.shutdownGracefully(); workerGroup.shutdownGracefully(); } }
repos\SpringBoot-Labs-master\lab-67\lab-67-netty-demo\lab-67-netty-demo-server\src\main\java\cn\iocoder\springboot\lab67\nettyserverdemo\server\NettyServer.java
2
请完成以下Java代码
public void setResponseText (String ResponseText) { set_Value (COLUMNNAME_ResponseText, ResponseText); } /** Get Response Text. @return Request Response Text */ public String getResponseText () { return (String)get_Value(COLUMNNAME_ResponseText); } /** Set Standard Response. @param R_StandardResponse_ID Request Standard Response */ public void setR_StandardResponse_ID (int R_StandardResponse_ID) { if (R_StandardResponse_ID < 1)
set_ValueNoCheck (COLUMNNAME_R_StandardResponse_ID, null); else set_ValueNoCheck (COLUMNNAME_R_StandardResponse_ID, Integer.valueOf(R_StandardResponse_ID)); } /** Get Standard Response. @return Request Standard Response */ public int getR_StandardResponse_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_R_StandardResponse_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_R_StandardResponse.java
1
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public long getInstances() { return instances; } public void setInstances(long instances) { this.instances = instances; } public long getFinished() { return finished; } public void setFinished(long finished) { this.finished = finished; } public long getCanceled() { return canceled; } public void setCanceled(long canceled) { this.canceled = canceled; } public long getCompleteScope() { return completeScope; } public void setCompleteScope(long completeScope) { this.completeScope = completeScope; } public long getOpenIncidents() { return openIncidents;
} public void setOpenIncidents(long openIncidents) { this.openIncidents = openIncidents; } public long getResolvedIncidents() { return resolvedIncidents; } public void setResolvedIncidents(long resolvedIncidents) { this.resolvedIncidents = resolvedIncidents; } public long getDeletedIncidents() { return deletedIncidents; } public void setDeletedIncidents(long closedIncidents) { this.deletedIncidents = closedIncidents; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\HistoricActivityStatisticsImpl.java
1
请在Spring Boot框架中完成以下Java代码
public Result<SystemRuleEntity> apiUpdateIfNotNull(Long id, String app, Double highestSystemLoad, Double highestCpuUsage, Long avgRt, Long maxThread, Double qps) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } SystemRuleEntity entity = repository.findById(id); if (entity == null) { return Result.ofFail(-1, "id " + id + " dose not exist"); } if (StringUtil.isNotBlank(app)) { entity.setApp(app.trim()); } if (highestSystemLoad != null) { if (highestSystemLoad < 0) { return Result.ofFail(-1, "highestSystemLoad must >= 0"); } entity.setHighestSystemLoad(highestSystemLoad); } if (highestCpuUsage != null) { if (highestCpuUsage < 0) { return Result.ofFail(-1, "highestCpuUsage must >= 0"); } if (highestCpuUsage > 1) { return Result.ofFail(-1, "highestCpuUsage must <= 1"); } entity.setHighestCpuUsage(highestCpuUsage); } if (avgRt != null) { if (avgRt < 0) { return Result.ofFail(-1, "avgRt must >= 0"); } entity.setAvgRt(avgRt); } if (maxThread != null) { if (maxThread < 0) { return Result.ofFail(-1, "maxThread must >= 0"); } entity.setMaxThread(maxThread); } if (qps != null) { if (qps < 0) { return Result.ofFail(-1, "qps must >= 0"); } entity.setQps(qps); } Date date = new Date(); entity.setGmtModified(date); try { entity = repository.save(entity); publishRules(entity.getApp()); } catch (Throwable throwable) { logger.error("save error:", throwable); return Result.ofThrowable(-1, throwable); }
return Result.ofSuccess(entity); } @RequestMapping("/delete.json") @AuthAction(PrivilegeType.DELETE_RULE) public Result<?> delete(Long id) { if (id == null) { return Result.ofFail(-1, "id can't be null"); } SystemRuleEntity oldEntity = repository.findById(id); if (oldEntity == null) { return Result.ofSuccess(null); } try { repository.delete(id); publishRules(oldEntity.getApp()); } catch (Throwable throwable) { logger.error("delete error:", throwable); return Result.ofThrowable(-1, throwable); } return Result.ofSuccess(id); } private void publishRules(String app) throws Exception { List<SystemRuleEntity> rules = repository.findAllByApp(app); rulePublisher.publish(app, rules); //延迟加载 delayTime(); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-sentinel\src\main\java\com\alibaba\csp\sentinel\dashboard\controller\SystemController.java
2
请在Spring Boot框架中完成以下Java代码
private ImmutableList<BPartnerId> extractBPartnerIds(@Nullable final I_AD_User userRecord) { final ImmutableList<BPartnerId> result; if (userRecord == null) // can happen while we are in the process of storing a bpartner with locations and contacts { result = ImmutableList.of(); } else { final BPartnerId bpartnerId = BPartnerId.ofRepoIdOrNull(userRecord.getC_BPartner_ID()); result = bpartnerId != null ? ImmutableList.of(bpartnerId) : ImmutableList.of(); } return result; } @Override public boolean isResetAll(@NonNull final TableRecordReference recordRef) {
if (I_C_BPartner.Table_Name.equals(recordRef.getTableName())) { return false; // recordRef.getRecord_ID() returns the C_BPartner_ID to invalidate => no need to reset all } else if (I_C_User_Role.Table_Name.equals(recordRef.getTableName()) || I_C_User_Assigned_Role.Table_Name.equals(recordRef.getTableName())) { return true; // there might be too many C_BPartners using the given role; also this change is not frequent; so, better reset the whole cache } // If we can't retrieve the model - e.g. because it was already deleted - then we can't extract the C_BPartner_ID to invalidate. // In that case we need to reset all final Object recordRefModel = recordRef.getModel(Object.class); return recordRefModel == null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\composite\repository\BPartnerCompositeCachingKeysMapper.java
2
请完成以下Java代码
public ProcessInstanceResult getExecutionResult() { Check.assumeNotNull(result, "action was already executed"); return result; } @Override public ProcessInstanceResult startProcess(@NonNull final ProcessExecutionContext context) { assertNotExecuted(); // // Validate parameters, if any if (parametersDocument != null) { parametersDocument.checkAndGetValidStatus().throwIfInvalid(); } // // Execute view action's method final IView view = getView(); final Method viewActionMethod = viewActionDescriptor.getViewActionMethod(); final Object[] viewActionParams = viewActionDescriptor.extractMethodArguments(view, parametersDocument, selectedDocumentIds); try { final Object targetObject = Modifier.isStatic(viewActionMethod.getModifiers()) ? null : view; final Object resultActionObj = viewActionMethod.invoke(targetObject, viewActionParams); final ResultAction resultAction = viewActionDescriptor.convertReturnType(resultActionObj); final ResultAction resultActionProcessed = processResultAction(resultAction, context.getViewsRepo()); final ProcessInstanceResult result = ProcessInstanceResult.builder(pinstanceId) .action(resultActionProcessed) .build(); this.result = result; return result; } catch (final Throwable ex) {
throw AdempiereException.wrapIfNeeded(ex); } } private ResultAction processResultAction(final ResultAction resultAction, final IViewsRepository viewRepos) { if (resultAction == null) { return null; } if (resultAction instanceof CreateAndOpenIncludedViewAction) { final IView view = viewRepos.createView(((CreateAndOpenIncludedViewAction)resultAction).getCreateViewRequest()); return OpenIncludedViewAction.builder().viewId(view.getViewId()).build(); } return resultAction; } /* package */ void assertNotExecuted() { Check.assumeNull(result, "view action instance not already executed"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\process\view\ViewActionInstance.java
1
请完成以下Java代码
public static Map<String, String> createSingletonMap() { Map<String, String> passwordMap = Collections.singletonMap("username1", "password1"); return passwordMap; } public Map<String, String> createEmptyMap() { Map<String, String> emptyMap = Collections.emptyMap(); return emptyMap; } public Map<String, String> createUsingDoubleBrace() { Map<String, String> doubleBraceMap = new HashMap<String, String>() { /** * */ private static final long serialVersionUID = 1L; { put("key1", "value1"); put("key2", "value2"); } }; return doubleBraceMap; } public Map<String, String> createMapUsingStreamStringArray() { Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, }) .collect(Collectors.toMap(data -> data[0], data -> data[1])); return map; } public Map<String, Integer> createMapUsingStreamObjectArray() { Map<String, Integer> map = Stream.of(new Object[][] { { "data1", 1 }, { "data2", 2 }, })
.collect(Collectors.toMap(data -> (String) data[0], data -> (Integer) data[1])); return map; } public Map<String, Integer> createMapUsingStreamSimpleEntry() { Map<String, Integer> map = Stream.of(new AbstractMap.SimpleEntry<>("idea", 1), new AbstractMap.SimpleEntry<>("mobile", 2)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return map; } public Map<String, Integer> createMapUsingStreamSimpleImmutableEntry() { Map<String, Integer> map = Stream.of(new AbstractMap.SimpleImmutableEntry<>("idea", 1), new AbstractMap.SimpleImmutableEntry<>("mobile", 2)) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)); return map; } public Map<String, String> createImmutableMapWithStreams() { Map<String, String> map = Stream.of(new String[][] { { "Hello", "World" }, { "John", "Doe" }, }) .collect(Collectors.collectingAndThen(Collectors.toMap(data -> data[0], data -> data[1]), Collections::<String, String> unmodifiableMap)); return map; } }
repos\tutorials-master\core-java-modules\core-java-collections-maps\src\main\java\com\baeldung\map\initialize\MapInitializer.java
1
请完成以下Java代码
public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((id == null) ? 0 : id.hashCode()); result = prime * result + ((models == null) ? 0 : models.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } /* (non-Javadoc) * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CarMaker other = (CarMaker) obj; if (id == null) {
if (other.id != null) return false; } else if (!id.equals(other.id)) return false; if (models == null) { if (other.models != null) return false; } else if (!models.equals(other.models)) return false; if (name == null) { if (other.name != null) return false; } else if (!name.equals(other.name)) return false; return true; } }
repos\tutorials-master\apache-olingo\src\main\java\com\baeldung\examples\olingo2\domain\CarMaker.java
1
请完成以下Java代码
public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getBatchId() { return batchId; } public void setBatchId(String batchId) { this.batchId = batchId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getExternalTaskId() { return externalTaskId; } public void setExternalTaskId(String externalTaskId) {
this.externalTaskId = externalTaskId; } public String getAnnotation() { return annotation; } public void setAnnotation(String annotation) { this.annotation = annotation; } @Override public String toString() { return this.getClass().getSimpleName() + "[taskId=" + taskId + ", deploymentId=" + deploymentId + ", processDefinitionKey=" + processDefinitionKey + ", jobId=" + jobId + ", jobDefinitionId=" + jobDefinitionId + ", batchId=" + batchId + ", operationId=" + operationId + ", operationType=" + operationType + ", userId=" + userId + ", timestamp=" + timestamp + ", property=" + property + ", orgValue=" + orgValue + ", newValue=" + newValue + ", id=" + id + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", processInstanceId=" + processInstanceId + ", externalTaskId=" + externalTaskId + ", tenantId=" + tenantId + ", entityType=" + entityType + ", category=" + category + ", annotation=" + annotation + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\UserOperationLogEntryEventEntity.java
1
请完成以下Java代码
abstract class AbstractClientHttpRequestFactoryBuilder<T extends ClientHttpRequestFactory> implements ClientHttpRequestFactoryBuilder<T> { private final List<Consumer<T>> customizers; protected AbstractClientHttpRequestFactoryBuilder(@Nullable List<Consumer<T>> customizers) { this.customizers = (customizers != null) ? customizers : Collections.emptyList(); } protected final List<Consumer<T>> getCustomizers() { return this.customizers; } protected final List<Consumer<T>> mergedCustomizers(Consumer<T> customizer) { Assert.notNull(this.customizers, "'customizer' must not be null"); return merge(this.customizers, List.of(customizer)); } protected final List<Consumer<T>> mergedCustomizers(Collection<Consumer<T>> customizers) { Assert.notNull(customizers, "'customizers' must not be null"); Assert.noNullElements(customizers, "'customizers' must not contain null elements"); return merge(this.customizers, customizers); }
private <E> List<E> merge(Collection<E> list, Collection<? extends E> additional) { List<E> merged = new ArrayList<>(list); merged.addAll(additional); return List.copyOf(merged); } @Override @SuppressWarnings("unchecked") public final T build(@Nullable HttpClientSettings settings) { T factory = createClientHttpRequestFactory((settings != null) ? settings : HttpClientSettings.defaults()); LambdaSafe.callbacks(Consumer.class, this.customizers, factory).invoke((consumer) -> consumer.accept(factory)); return factory; } protected abstract T createClientHttpRequestFactory(HttpClientSettings settings); }
repos\spring-boot-4.0.1\module\spring-boot-http-client\src\main\java\org\springframework\boot\http\client\AbstractClientHttpRequestFactoryBuilder.java
1
请完成以下Java代码
public Iterator<E> iterator() { return new CustomIterator(); } @Override public ListIterator<E> listIterator() { return null; } @Override public ListIterator<E> listIterator(int index) { // ignored for brevity return null; } private class CustomIterator implements Iterator<E> {
int index; @Override public boolean hasNext() { return index != internal.length; } @SuppressWarnings("unchecked") @Override public E next() { E element = (E) CustomList.this.internal[index]; index++; return element; } } }
repos\tutorials-master\core-java-modules\core-java-collections-list-7\src\main\java\com\baeldung\list\CustomList.java
1
请完成以下Java代码
public RouterFunctions.Builder resources(String pattern, Resource location) { builder.resources(pattern, location); return this; } @Override public RouterFunctions.Builder resources(Function<ServerRequest, Optional<Resource>> lookupFunction) { builder.resources(lookupFunction); return this; } @Override public RouterFunctions.Builder resources(String pattern, Resource location, BiConsumer<Resource, HttpHeaders> headersConsumer) { builder.resources(pattern, location, headersConsumer); return this; } @Override public RouterFunctions.Builder resources(Function<ServerRequest, Optional<Resource>> lookupFunction, BiConsumer<Resource, HttpHeaders> headersConsumer) { builder.resources(lookupFunction, headersConsumer); return this; } @Override public <T extends ServerResponse> RouterFunctions.Builder nest(RequestPredicate predicate, Supplier<RouterFunction<T>> routerFunctionSupplier) { builder.nest(predicate, routerFunctionSupplier); return this; } @Override public RouterFunctions.Builder nest(RequestPredicate predicate, Consumer<RouterFunctions.Builder> builderConsumer) { builder.nest(predicate, builderConsumer); return this; } @Override public <T extends ServerResponse> RouterFunctions.Builder path(String pattern, Supplier<RouterFunction<T>> routerFunctionSupplier) { builder.path(pattern, routerFunctionSupplier); return this; } @Override public RouterFunctions.Builder path(String pattern, Consumer<RouterFunctions.Builder> builderConsumer) { builder.path(pattern, builderConsumer); return this; } @Override public <T extends ServerResponse, R extends ServerResponse> RouterFunctions.Builder filter(
HandlerFilterFunction<T, R> filterFunction) { builder.filter(filterFunction); return this; } @Override public RouterFunctions.Builder before(Function<ServerRequest, ServerRequest> requestProcessor) { builder.before(requestProcessor); return this; } @Override public <T extends ServerResponse, R extends ServerResponse> RouterFunctions.Builder after( BiFunction<ServerRequest, T, R> responseProcessor) { builder.after(responseProcessor); return this; } @Override public <T extends ServerResponse> RouterFunctions.Builder onError(Predicate<Throwable> predicate, BiFunction<Throwable, ServerRequest, T> responseProvider) { builder.onError(predicate, responseProvider); return this; } @Override public <T extends ServerResponse> RouterFunctions.Builder onError(Class<? extends Throwable> exceptionType, BiFunction<Throwable, ServerRequest, T> responseProvider) { builder.onError(exceptionType, responseProvider); return this; } @Override public RouterFunctions.Builder withAttribute(String name, Object value) { builder.withAttribute(name, value); return this; } @Override public RouterFunctions.Builder withAttributes(Consumer<Map<String, Object>> attributesConsumer) { builder.withAttributes(attributesConsumer); return this; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\handler\GatewayRouterFunctionsBuilder.java
1
请完成以下Java代码
public Builder withProcessInstanceId(String processInstanceId) { this.processInstanceId = processInstanceId; return this; } /** * Builder method for processDefinitionId parameter. * @param processDefinitionId field to set * @return builder */ public Builder withProcessDefinitionId(String processDefinitionId) { this.processDefinitionId = processDefinitionId; return this; } /** * Builder method for businessKey parameter. * @param businessKey field to set * @return builder */ public Builder withBusinessKey(String businessKey) { this.businessKey = businessKey; return this; } /** * Builder method for configuration parameter. * @param configuration field to set * @return builder */ public Builder withConfiguration(String configuration) { this.configuration = configuration; return this;
} /** * Builder method for activityId parameter. * @param activityId field to set * @return builder */ public Builder withActivityId(String activityId) { this.activityId = activityId; return this; } /** * Builder method for created parameter. * @param created field to set * @return builder */ public Builder withCreated(Date created) { this.created = created; return this; } /** * Builder method of the builder. * @return built class */ public MessageSubscriptionImpl build() { return new MessageSubscriptionImpl(this); } } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\MessageSubscriptionImpl.java
1
请完成以下Java代码
public static Map<String, Object> map(Object... objects) { return mapOfClass(Object.class, objects); } /** * Helper method to easily create a map with keys of type String and values of a given Class. Null values are allowed. * * @param clazz the target Value class * @param objects varargs containing the key1, value1, key2, value2, etc. Note: although an Object, we will cast the key to String internally * @throws ActivitiIllegalArgumentException when objects are not even or key/value are not expected types */ public static <T> Map<String, T> mapOfClass(Class<T> clazz, Object... objects) { if (objects.length % 2 != 0) { throw new ActivitiIllegalArgumentException( "The input should always be even since we expect a list of key-value pairs!" ); } Map<String, T> map = new HashMap(); for (int i = 0; i < objects.length; i += 2) { int keyIndex = i; int valueIndex = i + 1; Object key = objects[keyIndex]; Object value = objects[valueIndex];
if (!String.class.isInstance(key)) { throw new ActivitiIllegalArgumentException( "key at index " + keyIndex + " should be a String but is a " + key.getClass() ); } if (value != null && !clazz.isInstance(value)) { throw new ActivitiIllegalArgumentException( "value at index " + valueIndex + " should be a " + clazz + " but is a " + value.getClass() ); } map.put((String) key, (T) value); } return map; } public static boolean isEmpty(Collection<?> collection) { return (collection == null || collection.isEmpty()); } public static boolean isNotEmpty(Collection<?> collection) { return !isEmpty(collection); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\util\CollectionUtil.java
1
请完成以下Java代码
public String getCurrency() { return currency; } public void setCurrency(String currency) { this.currency = currency; } public BigDecimal getAsk() { return ask; } public void setAsk(BigDecimal ask) { this.ask = ask; } public BigDecimal getBid() {
return bid; } public void setBid(BigDecimal bid) { this.bid = bid; } public LocalDate getDate() { return date; } public void setDate(LocalDate date) { this.date = date; } }
repos\tutorials-master\core-java-modules\java-spi\exchange-rate-api\src\main\java\com\baeldung\rate\api\Quote.java
1
请在Spring Boot框架中完成以下Java代码
public class SessionController { @GetMapping("/websession/test") public Mono<CustomResponse> testWebSessionByParam( @RequestParam(value = "id") int id, @RequestParam(value = "note") String note, WebSession session) { session.getAttributes().put("id", id); session.getAttributes().put("note", note); CustomResponse r = new CustomResponse(); r.setId((int) session.getAttributes().get("id")); r.setNote((String) session.getAttributes().get("note")); return Mono.just(r);
} @GetMapping("/websession") public Mono<CustomResponse> getSession(WebSession session) { session.getAttributes().putIfAbsent("id", 0); session.getAttributes().putIfAbsent("note", "Howdy Cosmic Spheroid!"); CustomResponse r = new CustomResponse(); r.setId((int) session.getAttributes().get("id")); r.setNote((String) session.getAttributes().get("note")); return Mono.just(r); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-3\src\main\java\com\baeldung\websession\controller\SessionController.java
2
请完成以下Java代码
public @NonNull Set<FAOpenItemsHandlerMatchingKey> getMatchers() { // shall not be called return ImmutableSet.of(); } @Override public Optional<FAOpenItemTrxInfo> computeTrxInfo(final FAOpenItemTrxInfoComputeRequest request) { final ElementValue elementValue = elementValueService.getById(request.getElementValueId()); if (elementValue.isOpenItem()) { final FAOpenItemKey key = FAOpenItemKey.ofTableRecordLineAndSubLineId( request.getAccountConceptualName(), request.getTableName(), request.getRecordId(), request.getLineId(), request.getSubLineId()); final FAOpenItemTrxInfo trxInfo = isClearing(request.getTableName()) ? FAOpenItemTrxInfo.clearing(key) : FAOpenItemTrxInfo.opening(key); return Optional.of(trxInfo); } else { return Optional.empty(); } }
private static boolean isClearing(final String tableName) { return I_C_AllocationHdr.Table_Name.equals(tableName) || I_M_MatchInv.Table_Name.equals(tableName); } @Override public void onGLJournalLineCompleted(final SAPGLJournalLine line) { } @Override public void onGLJournalLineReactivated(final SAPGLJournalLine line) { } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\open_items\handlers\Generic_OIHandler.java
1
请完成以下Java代码
public DbEntityCache getDbEntityCache() { return dbEntityCache; } public void setDbEntityCache(DbEntityCache dbEntityCache) { this.dbEntityCache = dbEntityCache; } // query factory methods //////////////////////////////////////////////////// public DeploymentQueryImpl createDeploymentQuery() { return new DeploymentQueryImpl(); } public ProcessDefinitionQueryImpl createProcessDefinitionQuery() { return new ProcessDefinitionQueryImpl(); } public CaseDefinitionQueryImpl createCaseDefinitionQuery() { return new CaseDefinitionQueryImpl(); } public ProcessInstanceQueryImpl createProcessInstanceQuery() { return new ProcessInstanceQueryImpl(); } public ExecutionQueryImpl createExecutionQuery() { return new ExecutionQueryImpl(); } public TaskQueryImpl createTaskQuery() { return new TaskQueryImpl(); } public JobQueryImpl createJobQuery() { return new JobQueryImpl(); } public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() { return new HistoricProcessInstanceQueryImpl(); } public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() { return new HistoricActivityInstanceQueryImpl(); } public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() { return new HistoricTaskInstanceQueryImpl(); } public HistoricDetailQueryImpl createHistoricDetailQuery() { return new HistoricDetailQueryImpl(); } public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() { return new HistoricVariableInstanceQueryImpl(); }
public HistoricJobLogQueryImpl createHistoricJobLogQuery() { return new HistoricJobLogQueryImpl(); } public UserQueryImpl createUserQuery() { return new DbUserQueryImpl(); } public GroupQueryImpl createGroupQuery() { return new DbGroupQueryImpl(); } public void registerOptimisticLockingListener(OptimisticLockingListener optimisticLockingListener) { if(optimisticLockingListeners == null) { optimisticLockingListeners = new ArrayList<>(); } optimisticLockingListeners.add(optimisticLockingListener); } public List<String> getTableNamesPresentInDatabase() { return persistenceSession.getTableNamesPresent(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\DbEntityManager.java
1
请完成以下Java代码
public void setDescription (final java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } @Override public java.lang.String getDescription() { return get_ValueAsString(COLUMNNAME_Description); } /** * FileCharset AD_Reference_ID=541224 * Reference name: FileCharset */ public static final int FILECHARSET_AD_Reference_ID=541224; /** UTF-8 = utf-8 */ public static final String FILECHARSET_UTF_8 = "utf-8"; /** Windows-1252 = Windows-1252 */ public static final String FILECHARSET_Windows_1252 = "Windows-1252"; @Override public void setFileCharset (final java.lang.String FileCharset) { set_Value (COLUMNNAME_FileCharset, FileCharset); } @Override public java.lang.String getFileCharset() { return get_ValueAsString(COLUMNNAME_FileCharset); } /** * FormatType AD_Reference_ID=209 * Reference name: AD_ImpFormat FormatType */ public static final int FORMATTYPE_AD_Reference_ID=209; /** Fixed Position = F */ public static final String FORMATTYPE_FixedPosition = "F"; /** CommaSeparated = C */ public static final String FORMATTYPE_CommaSeparated = "C"; /** TabSeparated = T */ public static final String FORMATTYPE_TabSeparated = "T"; /** XML = X */ public static final String FORMATTYPE_XML = "X"; /** SemicolonSeparated = S */ public static final String FORMATTYPE_SemicolonSeparated = "S"; @Override public void setFormatType (final java.lang.String FormatType) { set_Value (COLUMNNAME_FormatType, FormatType); } @Override public java.lang.String getFormatType() { return get_ValueAsString(COLUMNNAME_FormatType); } @Override public void setIsManualImport (final boolean IsManualImport) { set_Value (COLUMNNAME_IsManualImport, IsManualImport);
} @Override public boolean isManualImport() { return get_ValueAsBoolean(COLUMNNAME_IsManualImport); } @Override public void setIsMultiLine (final boolean IsMultiLine) { set_Value (COLUMNNAME_IsMultiLine, IsMultiLine); } @Override public boolean isMultiLine() { return get_ValueAsBoolean(COLUMNNAME_IsMultiLine); } @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 setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSkipFirstNRows (final int SkipFirstNRows) { set_Value (COLUMNNAME_SkipFirstNRows, SkipFirstNRows); } @Override public int getSkipFirstNRows() { return get_ValueAsInt(COLUMNNAME_SkipFirstNRows); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_ImpFormat.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(payerId, payerType, numberOfInsured, copaymentFromDate, copaymentToDate); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientPayer {\n"); sb.append(" payerId: ").append(toIndentedString(payerId)).append("\n"); sb.append(" payerType: ").append(toIndentedString(payerType)).append("\n"); sb.append(" numberOfInsured: ").append(toIndentedString(numberOfInsured)).append("\n"); sb.append(" copaymentFromDate: ").append(toIndentedString(copaymentFromDate)).append("\n"); sb.append(" copaymentToDate: ").append(toIndentedString(copaymentToDate)).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-patient-api\src\main\java\io\swagger\client\model\PatientPayer.java
2
请完成以下Java代码
public static void main(String[] args) { try { generateImageFromPDF(PDF, "png"); generateImageFromPDF(PDF, "jpeg"); generateImageFromPDF(PDF, "gif"); generatePDFFromImage(JPG, "jpg"); generatePDFFromImage(GIF, "gif"); } catch (IOException | DocumentException | URISyntaxException e) { e.printStackTrace(); } } private static void generateImageFromPDF(String filename, String extension) throws IOException { PDDocument document = PDDocument.load(new File(filename)); PDFRenderer pdfRenderer = new PDFRenderer(document); for (int page = 0; page < document.getNumberOfPages(); ++page) { BufferedImage bim = pdfRenderer.renderImageWithDPI(page, 300, ImageType.RGB); ImageIOUtil.writeImage(bim, String.format("src/output/pdf-%d.%s", page + 1, extension), 300); }
document.close(); } private static void generatePDFFromImage(String filename, String extension) throws IOException, DocumentException, URISyntaxException { Document document = new Document(); String input = filename + "." + extension; String output = "src/output/" + extension + ".pdf"; FileOutputStream fos = new FileOutputStream(output); PdfWriter writer = PdfWriter.getInstance(document, fos); writer.open(); document.open(); document.add(Image.getInstance((new URI(input).toURL()))); document.close(); writer.close(); } }
repos\tutorials-master\text-processing-libraries-modules\pdf\src\main\java\com\baeldung\pdf\PDF2ImageExample.java
1
请完成以下Java代码
public void setMobileUI_UserProfile_Picking_ID (final int MobileUI_UserProfile_Picking_ID) { if (MobileUI_UserProfile_Picking_ID < 1) set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_Picking_ID, null); else set_ValueNoCheck (COLUMNNAME_MobileUI_UserProfile_Picking_ID, MobileUI_UserProfile_Picking_ID); } @Override public int getMobileUI_UserProfile_Picking_ID() { return get_ValueAsInt(COLUMNNAME_MobileUI_UserProfile_Picking_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } /** * PickingJobAggregationType AD_Reference_ID=541931 * Reference name: PickingJobAggregationType */ public static final int PICKINGJOBAGGREGATIONTYPE_AD_Reference_ID=541931; /** sales_order = sales_order */ public static final String PICKINGJOBAGGREGATIONTYPE_Sales_order = "sales_order"; /** product = product */ public static final String PICKINGJOBAGGREGATIONTYPE_Product = "product"; /** delivery_location = delivery_location */ public static final String PICKINGJOBAGGREGATIONTYPE_Delivery_location = "delivery_location"; @Override public void setPickingJobAggregationType (final java.lang.String PickingJobAggregationType) { set_Value (COLUMNNAME_PickingJobAggregationType, PickingJobAggregationType); } @Override public java.lang.String getPickingJobAggregationType() { return get_ValueAsString(COLUMNNAME_PickingJobAggregationType); } /** * PickingLineGroupBy AD_Reference_ID=541899 * Reference name: PickingLineGroupByValues */ public static final int PICKINGLINEGROUPBY_AD_Reference_ID=541899; /** Product_Category = product_category */ public static final String PICKINGLINEGROUPBY_Product_Category = "product_category"; @Override public void setPickingLineGroupBy (final @Nullable java.lang.String PickingLineGroupBy) { set_Value (COLUMNNAME_PickingLineGroupBy, PickingLineGroupBy); }
@Override public java.lang.String getPickingLineGroupBy() { return get_ValueAsString(COLUMNNAME_PickingLineGroupBy); } /** * PickingLineSortBy AD_Reference_ID=541900 * Reference name: PickingLineSortByValues */ public static final int PICKINGLINESORTBY_AD_Reference_ID=541900; /** ORDER_LINE_SEQ_NO = ORDER_LINE_SEQ_NO */ public static final String PICKINGLINESORTBY_ORDER_LINE_SEQ_NO = "ORDER_LINE_SEQ_NO"; /** QTY_TO_PICK_ASC = QTY_TO_PICK_ASC */ public static final String PICKINGLINESORTBY_QTY_TO_PICK_ASC = "QTY_TO_PICK_ASC"; /** QTY_TO_PICK_DESC = QTY_TO_PICK_DESC */ public static final String PICKINGLINESORTBY_QTY_TO_PICK_DESC = "QTY_TO_PICK_DESC"; @Override public void setPickingLineSortBy (final @Nullable java.lang.String PickingLineSortBy) { set_Value (COLUMNNAME_PickingLineSortBy, PickingLineSortBy); } @Override public java.lang.String getPickingLineSortBy() { return get_ValueAsString(COLUMNNAME_PickingLineSortBy); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_MobileUI_UserProfile_Picking.java
1
请完成以下Java代码
public int hashCode() { return Objects.hash(code, type, message); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class ModelApiResponse {\n"); sb.append(" code: ").append(toIndentedString(code)).append("\n"); sb.append(" type: ").append(toIndentedString(type)).append("\n"); sb.append(" message: ").append(toIndentedString(message)).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\tutorials-master\spring-swagger-codegen-modules\spring-swagger-codegen-api-client\src\main\java\com\baeldung\petstore\client\model\ModelApiResponse.java
1
请完成以下Java代码
private Collection<ObjectName> register() { return this.endpoints.stream().filter(this::hasOperations).map(this::register).toList(); } private boolean hasOperations(ExposableJmxEndpoint endpoint) { return !CollectionUtils.isEmpty(endpoint.getOperations()); } private ObjectName register(ExposableJmxEndpoint endpoint) { Assert.notNull(endpoint, "'endpoint' must not be null"); try { ObjectName name = this.objectNameFactory.getObjectName(endpoint); EndpointMBean mbean = new EndpointMBean(this.responseMapper, this.classLoader, endpoint); this.mBeanServer.registerMBean(mbean, name); return name; } catch (MalformedObjectNameException ex) { throw new IllegalStateException("Invalid ObjectName for " + getEndpointDescription(endpoint), ex); } catch (Exception ex) { throw new MBeanExportException("Failed to register MBean for " + getEndpointDescription(endpoint), ex); } } private void unregister(Collection<ObjectName> objectNames) { objectNames.forEach(this::unregister);
} private void unregister(ObjectName objectName) { try { if (logger.isDebugEnabled()) { logger.debug("Unregister endpoint with ObjectName '" + objectName + "' from the JMX domain"); } this.mBeanServer.unregisterMBean(objectName); } catch (InstanceNotFoundException ex) { // Ignore and continue } catch (MBeanRegistrationException ex) { throw new JmxException("Failed to unregister MBean with ObjectName '" + objectName + "'", ex); } } private String getEndpointDescription(ExposableJmxEndpoint endpoint) { return "endpoint '" + endpoint.getEndpointId() + "'"; } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\jmx\JmxEndpointExporter.java
1
请完成以下Java代码
public void setC_Invoice_Candidate_Commission_ID (final int C_Invoice_Candidate_Commission_ID) { if (C_Invoice_Candidate_Commission_ID < 1) set_Value (COLUMNNAME_C_Invoice_Candidate_Commission_ID, null); else set_Value (COLUMNNAME_C_Invoice_Candidate_Commission_ID, C_Invoice_Candidate_Commission_ID); } @Override public int getC_Invoice_Candidate_Commission_ID() { return get_ValueAsInt(COLUMNNAME_C_Invoice_Candidate_Commission_ID); } /** * Commission_Fact_State AD_Reference_ID=541042 * Reference name: C_Commission_Fact_State */ public static final int COMMISSION_FACT_STATE_AD_Reference_ID=541042; /** FORECASTED = FORECASTED */ public static final String COMMISSION_FACT_STATE_FORECASTED = "FORECASTED"; /** INVOICEABLE = INVOICEABLE */ public static final String COMMISSION_FACT_STATE_INVOICEABLE = "INVOICEABLE"; /** INVOICED = INVOICED */ public static final String COMMISSION_FACT_STATE_INVOICED = "INVOICED"; /** SETTLED = SETTLED */ public static final String COMMISSION_FACT_STATE_SETTLED = "SETTLED"; /** TO_SETTLE = TO_SETTLE */ public static final String COMMISSION_FACT_STATE_TO_SETTLE = "TO_SETTLE"; @Override public void setCommission_Fact_State (final java.lang.String Commission_Fact_State) { set_ValueNoCheck (COLUMNNAME_Commission_Fact_State, Commission_Fact_State); } @Override public java.lang.String getCommission_Fact_State() { return get_ValueAsString(COLUMNNAME_Commission_Fact_State); } @Override public void setCommissionFactTimestamp (final java.lang.String CommissionFactTimestamp) { set_ValueNoCheck (COLUMNNAME_CommissionFactTimestamp, CommissionFactTimestamp);
} @Override public java.lang.String getCommissionFactTimestamp() { return get_ValueAsString(COLUMNNAME_CommissionFactTimestamp); } @Override public void setCommissionPoints (final BigDecimal CommissionPoints) { set_ValueNoCheck (COLUMNNAME_CommissionPoints, CommissionPoints); } @Override public BigDecimal getCommissionPoints() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_CommissionPoints); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\commission\model\X_C_Commission_Fact.java
1
请完成以下Java代码
public boolean isRegisterDefaultServlet() { return this.registerDefaultServlet; } public void setRegisterDefaultServlet(boolean registerDefaultServlet) { this.registerDefaultServlet = registerDefaultServlet; } public MimeMappings getMimeMappings() { return this.mimeMappings; } public @Nullable File getDocumentRoot() { return this.documentRoot; } public void setDocumentRoot(@Nullable File documentRoot) { this.documentRoot = documentRoot; } public List<? extends ServletContextInitializer> getInitializers() { return this.initializers; } public void setJsp(Jsp jsp) { this.jsp = jsp; } public Jsp getJsp() { return this.jsp; } public Map<Locale, Charset> getLocaleCharsetMappings() { return this.localeCharsetMappings; } public Map<String, String> getInitParameters() { return this.initParameters; } public List<? extends CookieSameSiteSupplier> getCookieSameSiteSuppliers() { return this.cookieSameSiteSuppliers; } public void setMimeMappings(MimeMappings mimeMappings) { Assert.notNull(mimeMappings, "'mimeMappings' must not be null"); this.mimeMappings = new MimeMappings(mimeMappings); } public void addMimeMappings(MimeMappings mimeMappings) { mimeMappings.forEach((mapping) -> this.mimeMappings.add(mapping.getExtension(), mapping.getMimeType())); } public void setInitializers(List<? extends ServletContextInitializer> initializers) { Assert.notNull(initializers, "'initializers' must not be null"); this.initializers = new ArrayList<>(initializers); } public void addInitializers(ServletContextInitializer... initializers) { Assert.notNull(initializers, "'initializers' must not be null"); this.initializers.addAll(Arrays.asList(initializers)); }
public void setLocaleCharsetMappings(Map<Locale, Charset> localeCharsetMappings) { Assert.notNull(localeCharsetMappings, "'localeCharsetMappings' must not be null"); this.localeCharsetMappings = localeCharsetMappings; } public void setInitParameters(Map<String, String> initParameters) { this.initParameters = initParameters; } public void setCookieSameSiteSuppliers(List<? extends CookieSameSiteSupplier> cookieSameSiteSuppliers) { Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null"); this.cookieSameSiteSuppliers = new ArrayList<>(cookieSameSiteSuppliers); } public void addCookieSameSiteSuppliers(CookieSameSiteSupplier... cookieSameSiteSuppliers) { Assert.notNull(cookieSameSiteSuppliers, "'cookieSameSiteSuppliers' must not be null"); this.cookieSameSiteSuppliers.addAll(Arrays.asList(cookieSameSiteSuppliers)); } public void addWebListenerClassNames(String... webListenerClassNames) { this.webListenerClassNames.addAll(Arrays.asList(webListenerClassNames)); } public Set<String> getWebListenerClassNames() { return this.webListenerClassNames; } public List<URL> getStaticResourceUrls() { return this.staticResourceJars.getUrls(); } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\servlet\ServletWebServerSettings.java
1
请在Spring Boot框架中完成以下Java代码
public class ArticleDAO implements IArticleDAO { @PersistenceContext private EntityManager entityManager; @Override public Article getArticleById(int articleId) { return entityManager.find(Article.class, articleId); } @SuppressWarnings("unchecked") @Override public List<Article> getAllArticles() { String hql = "FROM Article as atcl ORDER BY atcl.articleId"; return (List<Article>) entityManager.createQuery(hql).getResultList(); } @Override public void addArticle(Article article) { entityManager.persist(article); } @Override
public void updateArticle(Article article) { Article artcl = getArticleById(article.getArticleId()); artcl.setTitle(article.getTitle()); artcl.setCategory(article.getCategory()); entityManager.flush(); } @Override public void deleteArticle(int articleId) { entityManager.remove(getArticleById(articleId)); } @Override public boolean articleExists(String title, String category) { String hql = "FROM Article as atcl WHERE atcl.title = ? and atcl.category = ?"; int count = entityManager.createQuery(hql) .setParameter(0, title) .setParameter(1, category).getResultList().size(); return count > 0; } }
repos\SpringBootBucket-master\springboot-hibernate\src\main\java\com\xncoding\pos\dao\repository\impl\ArticleDAO.java
2
请完成以下Java代码
public HashMap<String, ExecutionEntity> getCreatedEmbeddedSubProcesses() { return createdEmbeddedSubProcess; } public Optional<ExecutionEntity> getCreatedEmbeddedSubProcessByKey(String key) { return Optional.ofNullable(createdEmbeddedSubProcess.get(key)); } public void addCreatedEmbeddedSubProcess(String key, ExecutionEntity executionEntity) { this.createdEmbeddedSubProcess.put(key, executionEntity); } public HashMap<String, ExecutionEntity> getCreatedMultiInstanceRootExecution() { return createdMultiInstanceRootExecution; } public void setCreatedMultiInstanceRootExecution(HashMap<String, ExecutionEntity> createdMultiInstanceRootExecution) { this.createdMultiInstanceRootExecution = createdMultiInstanceRootExecution; } public void addCreatedMultiInstanceRootExecution(String key, ExecutionEntity executionEntity) {
this.createdMultiInstanceRootExecution.put(key, executionEntity); } public Map<String, List<ExecutionEntity>> getProcessInstanceActiveEmbeddedExecutions() { return processInstanceActiveEmbeddedExecutions; } public ProcessInstanceChangeState setProcessInstanceActiveEmbeddedExecutions(Map<String, List<ExecutionEntity>> processInstanceActiveEmbeddedExecutions) { this.processInstanceActiveEmbeddedExecutions = processInstanceActiveEmbeddedExecutions; return this; } public HashMap<StartEvent, ExecutionEntity> getPendingEventSubProcessesStartEvents() { return pendingEventSubProcessesStartEvents; } public void addPendingEventSubProcessStartEvent(StartEvent startEvent, ExecutionEntity eventSubProcessParent) { this.pendingEventSubProcessesStartEvents.put(startEvent, eventSubProcessParent); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\dynamic\ProcessInstanceChangeState.java
1
请在Spring Boot框架中完成以下Java代码
public SecurityWebFilterChain securityWebFilterChain(ServerHttpSecurity http) { return http .csrf(csrfSpec -> csrfSpec.disable()) .authorizeExchange(auth -> auth.pathMatchers(HttpMethod.GET,"/**") .authenticated()) .httpBasic(httpBasicSpec -> httpBasicSpec.disable()) .addFilterAfter(authenticationWebFilter(), SecurityWebFiltersOrder.REACTOR_CONTEXT) .build(); } public AuthenticationWebFilter authenticationWebFilter() { return new AuthenticationWebFilter(resolver()); } public ReactiveAuthenticationManagerResolver<ServerWebExchange> resolver() { return exchange -> { if (exchange .getRequest() .getPath() .subPath(0) .value() .startsWith("/employee")) { return Mono.just(employeesAuthenticationManager()); } return Mono.just(customersAuthenticationManager()); }; } public ReactiveAuthenticationManager customersAuthenticationManager() { return authentication -> customer(authentication) .switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication .getPrincipal() .toString()))) .map(b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) ) ); }
public ReactiveAuthenticationManager employeesAuthenticationManager() { return authentication -> employee(authentication) .switchIfEmpty(Mono.error(new UsernameNotFoundException(authentication .getPrincipal() .toString()))) .map( b -> new UsernamePasswordAuthenticationToken(authentication.getPrincipal(), authentication.getCredentials(), Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")) ) ); } public Mono<String> customer(Authentication authentication) { return Mono.justOrEmpty(authentication .getPrincipal() .toString() .startsWith("customer") ? authentication .getPrincipal() .toString() : null); } public Mono<String> employee(Authentication authentication) { return Mono.justOrEmpty(authentication .getPrincipal() .toString() .startsWith("employee") ? authentication .getPrincipal() .toString() : null); } }
repos\tutorials-master\spring-reactive-modules\spring-reactive-security\src\main\java\com\baeldung\reactive\authresolver\CustomWebSecurityConfig.java
2
请完成以下Java代码
public static List<JSONDocumentReference> ofList(final Collection<WebuiDocumentReference> documentReferences, final JSONOptions jsonOpts) { if (documentReferences.isEmpty()) { return ImmutableList.of(); } return documentReferences.stream() .map(documentReference -> of(documentReference, jsonOpts)) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } private static final transient Logger logger = LogManager.getLogger(JSONDocumentReference.class); @JsonProperty("id") private final String id; @JsonProperty("priority") private final int priority; @JsonProperty("internalName") private final String internalName; @JsonProperty("caption") private final String caption; @JsonProperty("targetWindowId") private final WindowId targetWindowId; @JsonProperty("targetCategory") private final String targetCategory; @JsonProperty("documentsCount") private final int documentsCount;
@JsonProperty("filter") private final JSONDocumentFilter filter; @JsonProperty("loadDuration") @JsonInclude(JsonInclude.Include.NON_EMPTY) private final String loadDuration; private JSONDocumentReference( @NonNull final WebuiDocumentReference documentReference, @NonNull final JSONOptions jsonOpts) { final String adLanguage = jsonOpts.getAdLanguage(); id = documentReference.getId().toJson(); priority = documentReference.getPriority().toInt(); internalName = documentReference.getInternalName(); caption = documentReference.getCaption(adLanguage); targetWindowId = documentReference.getTargetWindow().getWindowId(); targetCategory = documentReference.getTargetWindow().getCategory(); documentsCount = documentReference.getDocumentsCount(); final DocumentFilter filter = documentReference.getFilter(); this.filter = JSONDocumentFilter.of(filter, jsonOpts); final Duration loadDuration = documentReference.getLoadDuration(); this.loadDuration = loadDuration != null ? TimeUtil.formatElapsed(loadDuration) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\references\json\JSONDocumentReference.java
1
请完成以下Java代码
public static com.baeldung.serialization.protocols.UserProtos.User getDefaultInstance() { return DEFAULT_INSTANCE; } private static final com.google.protobuf.Parser<User> PARSER = new com.google.protobuf.AbstractParser<User>() { @java.lang.Override public User parsePartialFrom(com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new User(input, extensionRegistry); } }; public static com.google.protobuf.Parser<User> parser() { return PARSER; } @java.lang.Override public com.google.protobuf.Parser<User> getParserForType() { return PARSER; } @java.lang.Override public com.baeldung.serialization.protocols.UserProtos.User getDefaultInstanceForType() {
return DEFAULT_INSTANCE; } } private static final com.google.protobuf.Descriptors.Descriptor internal_static_protobuf_User_descriptor; private static final com.google.protobuf.GeneratedMessageV3.FieldAccessorTable internal_static_protobuf_User_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\nuser.proto\022\010protobuf\" \n\004User\022\n\n\002id\030\001 \001" + "(\005\022\014\n\004name\030\002 \001(\tB0\n\"com.baeldung.seriali" + "zation.compareB\nUserProtosb\006proto3" }; descriptor = com.google.protobuf.Descriptors.FileDescriptor.internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] {}); internal_static_protobuf_User_descriptor = getDescriptor().getMessageTypes() .get(0); internal_static_protobuf_User_fieldAccessorTable = new com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(internal_static_protobuf_User_descriptor, new java.lang.String[] { "Id", "Name", }); } // @@protoc_insertion_point(outer_class_scope) }
repos\tutorials-master\libraries-data-io\src\main\java\com\baeldung\serialization\protocols\UserProtos.java
1
请完成以下Java代码
public class SpringAdvancedBusinessCalendarManagerFactory { private Integer defaultScheduleVersion; private Clock clock; public Integer getDefaultScheduleVersion() { return defaultScheduleVersion; } public void setDefaultScheduleVersion(Integer defaultScheduleVersion) { this.defaultScheduleVersion = defaultScheduleVersion; } public Clock getClock() { if (clock == null) { clock = new DefaultClockImpl(); } return clock; } public void setClock(Clock clock) { this.clock = clock; } public BusinessCalendarManager getBusinessCalendarManager() { MapBusinessCalendarManager mapBusinessCalendarManager = new MapBusinessCalendarManager();
mapBusinessCalendarManager.addBusinessCalendar( DurationBusinessCalendar.NAME, new DurationBusinessCalendar(getClock()) ); mapBusinessCalendarManager.addBusinessCalendar( DueDateBusinessCalendar.NAME, new DueDateBusinessCalendar(getClock()) ); mapBusinessCalendarManager.addBusinessCalendar( AdvancedCycleBusinessCalendar.NAME, new AdvancedCycleBusinessCalendar(getClock(), defaultScheduleVersion) ); return mapBusinessCalendarManager; } }
repos\Activiti-develop\activiti-core\activiti-spring\src\main\java\org\activiti\spring\SpringAdvancedBusinessCalendarManagerFactory.java
1
请完成以下Java代码
public class FieldDeclaration implements Serializable { private static final long serialVersionUID = 1L; protected String name; protected String type; protected Object value; public FieldDeclaration(String name, String type, Object value) { this.name = name; this.type = type; this.value = value; } public FieldDeclaration() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getType() {
return type; } public void setType(String type) { this.type = type; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\FieldDeclaration.java
1
请完成以下Java代码
public class Meter { protected AtomicLong counter = new AtomicLong(0); protected String name; public Meter(String name) { this.name = name; } public void mark() { counter.incrementAndGet(); } public void markTimes(long times) { counter.addAndGet(times); }
public String getName() { return name; } public void setName(String name) { this.name = name; } public long getAndClear() { return counter.getAndSet(0); } public long get() { return counter.get(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\metrics\Meter.java
1
请在Spring Boot框架中完成以下Java代码
public LocatorInfo getLocatorInfoByRepoId(final int locatorRepoId) { return warehouseService.getLocatorInfoByRepoId(locatorRepoId); } public Stream<I_DD_Order> stream(@NonNull final DDOrderQuery query) { return ddOrderService.streamDDOrders(query); } public I_DD_Order getDDOrderById(final DDOrderId ddOrderId) { return ddOrderService.getById(ddOrderId); } public Map<DDOrderId, List<I_DD_OrderLine>> getLinesByDDOrderIds(final Set<DDOrderId> ddOrderIds) { return ddOrderService.streamLinesByDDOrderIds(ddOrderIds) .collect(Collectors.groupingBy(ddOrderLine -> DDOrderId.ofRepoId(ddOrderLine.getDD_Order_ID()), Collectors.toList())); } public Map<DDOrderLineId, List<DDOrderMoveSchedule>> getSchedulesByDDOrderLineIds(final Set<DDOrderLineId> ddOrderLineIds) { if (ddOrderLineIds.isEmpty()) {return ImmutableMap.of();} final Map<DDOrderLineId, List<DDOrderMoveSchedule>> map = ddOrderMoveScheduleService.getByDDOrderLineIds(ddOrderLineIds) .stream() .collect(Collectors.groupingBy(DDOrderMoveSchedule::getDdOrderLineId, Collectors.toList())); return CollectionUtils.fillMissingKeys(map, ddOrderLineIds, ImmutableList.of()); } public boolean hasInTransitSchedules(@NonNull final LocatorId inTransitLocatorId) { return ddOrderMoveScheduleService.hasInTransitSchedules(inTransitLocatorId); }
public ZoneId getTimeZone(final OrgId orgId) { return orgDAO.getTimeZone(orgId); } public HUInfo getHUInfo(final HuId huId) {return huService.getHUInfoById(huId);} @Nullable public SalesOrderRef getSalesOderRef(@NonNull final I_DD_Order ddOrder) { final OrderId salesOrderId = OrderId.ofRepoIdOrNull(ddOrder.getC_Order_ID()); return salesOrderId != null ? sourceDocService.getSalesOderRef(salesOrderId) : null; } @Nullable public ManufacturingOrderRef getManufacturingOrderRef(@NonNull final I_DD_Order ddOrder) { final PPOrderId ppOrderId = PPOrderId.ofRepoIdOrNull(ddOrder.getForward_PP_Order_ID()); return ppOrderId != null ? sourceDocService.getManufacturingOrderRef(ppOrderId) : null; } @NonNull public PlantInfo getPlantInfo(@NonNull final ResourceId plantId) { return sourceDocService.getPlantInfo(plantId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\job\service\DistributionJobLoaderSupportingServices.java
2
请完成以下Java代码
public void setActive(boolean active) { this.active = active; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + id; return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null)
return false; if (getClass() != obj.getClass()) return false; Account other = (Account) obj; if (id != other.id) return false; return true; } @Override public String toString() { return MessageFormat.format("id:{0}, name:{1}, active:{2}, type:{3}", id, name, active, type); } }
repos\tutorials-master\persistence-modules\spring-hibernate-6\src\main\java\com\baeldung\hibernate\dynamicupdate\model\Account.java
1
请在Spring Boot框架中完成以下Java代码
public void setImportErrorMsg (final @Nullable java.lang.String ImportErrorMsg) { set_Value (COLUMNNAME_ImportErrorMsg, ImportErrorMsg); } @Override public java.lang.String getImportErrorMsg() { return get_ValueAsString(COLUMNNAME_ImportErrorMsg); } @Override public void setJSONValue (final @Nullable java.lang.String JSONValue) { set_Value (COLUMNNAME_JSONValue, JSONValue); } @Override public java.lang.String getJSONValue()
{ return get_ValueAsString(COLUMNNAME_JSONValue); } @Override public void setS_FailedTimeBooking_ID (final int S_FailedTimeBooking_ID) { if (S_FailedTimeBooking_ID < 1) set_ValueNoCheck (COLUMNNAME_S_FailedTimeBooking_ID, null); else set_ValueNoCheck (COLUMNNAME_S_FailedTimeBooking_ID, S_FailedTimeBooking_ID); } @Override public int getS_FailedTimeBooking_ID() { return get_ValueAsInt(COLUMNNAME_S_FailedTimeBooking_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.serviceprovider\src\main\java-gen\de\metas\serviceprovider\model\X_S_FailedTimeBooking.java
2
请完成以下Java代码
public Void execute(CommandContext commandContext) { if (deploymentId == null) { throw new FlowableIllegalArgumentException("Deployment id is null"); } ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); DeploymentEntity deployment = processEngineConfiguration.getDeploymentEntityManager().findById(deploymentId); if (deployment == null) { throw new FlowableObjectNotFoundException("No deployment found for id = '" + deploymentId + "'", Deployment.class); } if (Flowable5Util.isFlowable5Deployment(deployment, commandContext)) { processEngineConfiguration.getFlowable5CompatibilityHandler().setDeploymentCategory(deploymentId, category); } // Update category deployment.setCategory(category); FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableEventBuilder.createEntityEvent(FlowableEngineEventType.ENTITY_UPDATED, deployment), processEngineConfiguration.getEngineCfgKey()); } return null; }
public String getDeploymentId() { return deploymentId; } public void setDeploymentId(String deploymentId) { this.deploymentId = deploymentId; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\SetDeploymentCategoryCmd.java
1
请在Spring Boot框架中完成以下Java代码
public String getExchangeRate() { return exchangeRate; } public void setExchangeRate(String exchangeRate) { this.exchangeRate = exchangeRate; } public DisputeAmount value(String value) { this.value = value; return this; } /** * The monetary amount, in the currency specified by the currency field. This field is always returned with any container using Amount type. * * @return value **/ @javax.annotation.Nullable @ApiModelProperty(value = "The monetary amount, in the currency specified by the currency field. This field is always returned with any container using Amount type.") public String getValue() { return value; } public void setValue(String value) { this.value = value; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } DisputeAmount disputeAmount = (DisputeAmount)o;
return Objects.equals(this.convertedFromCurrency, disputeAmount.convertedFromCurrency) && Objects.equals(this.convertedFromValue, disputeAmount.convertedFromValue) && Objects.equals(this.currency, disputeAmount.currency) && Objects.equals(this.exchangeRate, disputeAmount.exchangeRate) && Objects.equals(this.value, disputeAmount.value); } @Override public int hashCode() { return Objects.hash(convertedFromCurrency, convertedFromValue, currency, exchangeRate, value); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class DisputeAmount {\n"); sb.append(" convertedFromCurrency: ").append(toIndentedString(convertedFromCurrency)).append("\n"); sb.append(" convertedFromValue: ").append(toIndentedString(convertedFromValue)).append("\n"); sb.append(" currency: ").append(toIndentedString(currency)).append("\n"); sb.append(" exchangeRate: ").append(toIndentedString(exchangeRate)).append("\n"); sb.append(" value: ").append(toIndentedString(value)).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\DisputeAmount.java
2
请完成以下Java代码
public String getSuperCaseInstanceId() { return superCaseInstanceId; } public String getCaseInstanceId() { return caseInstanceId; } public String getTenantId() { return tenantId; } public String getState() { return state; } public void setState(String state) { this.state = state; } public Date getRemovalTime() { return removalTime; } public void setRemovalTime(Date removalTime) { this.removalTime = removalTime; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public String getRestartedProcessInstanceId() { return restartedProcessInstanceId; } public void setRestartedProcessInstanceId(String restartedProcessInstanceId) { this.restartedProcessInstanceId = restartedProcessInstanceId; }
public static HistoricProcessInstanceDto fromHistoricProcessInstance(HistoricProcessInstance historicProcessInstance) { HistoricProcessInstanceDto dto = new HistoricProcessInstanceDto(); dto.id = historicProcessInstance.getId(); dto.businessKey = historicProcessInstance.getBusinessKey(); dto.processDefinitionId = historicProcessInstance.getProcessDefinitionId(); dto.processDefinitionKey = historicProcessInstance.getProcessDefinitionKey(); dto.processDefinitionName = historicProcessInstance.getProcessDefinitionName(); dto.processDefinitionVersion = historicProcessInstance.getProcessDefinitionVersion(); dto.startTime = historicProcessInstance.getStartTime(); dto.endTime = historicProcessInstance.getEndTime(); dto.removalTime = historicProcessInstance.getRemovalTime(); dto.durationInMillis = historicProcessInstance.getDurationInMillis(); dto.startUserId = historicProcessInstance.getStartUserId(); dto.startActivityId = historicProcessInstance.getStartActivityId(); dto.deleteReason = historicProcessInstance.getDeleteReason(); dto.rootProcessInstanceId = historicProcessInstance.getRootProcessInstanceId(); dto.superProcessInstanceId = historicProcessInstance.getSuperProcessInstanceId(); dto.superCaseInstanceId = historicProcessInstance.getSuperCaseInstanceId(); dto.caseInstanceId = historicProcessInstance.getCaseInstanceId(); dto.tenantId = historicProcessInstance.getTenantId(); dto.state = historicProcessInstance.getState(); dto.restartedProcessInstanceId = historicProcessInstance.getRestartedProcessInstanceId(); return dto; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\dto\history\HistoricProcessInstanceDto.java
1
请完成以下Java代码
public void actionPerformed(final ActionEvent e) { } /** * @see java.awt.event.MouseListener#mouseClicked(java.awt.event.MouseEvent) * @param e */ @Override public void mouseClicked(final MouseEvent e) { } /** * @see java.awt.event.MouseListener#mouseEntered(java.awt.event.MouseEvent) * @param e */ @Override public void mouseEntered(final MouseEvent e) { } /** * @see java.awt.event.MouseListener#mouseExited(java.awt.event.MouseEvent) * @param e */ @Override public void mouseExited(final MouseEvent e) { } /** * @see java.awt.event.MouseListener#mousePressed(java.awt.event.MouseEvent) * @param e */ @Override public void mousePressed(final MouseEvent e) { } /** * @see java.awt.event.MouseListener#mouseReleased(java.awt.event.MouseEvent) * @param e */ @Override public void mouseReleased(final MouseEvent e) { } /** * Set Title * * @param title title */ @Override public void setTitle(String title) { if (title != null) { final int pos = title.indexOf('&'); if (pos != -1 && title.length() > pos) // We have a nemonic { final int mnemonic = title.toUpperCase().charAt(pos + 1); if (mnemonic != ' ') { title = title.substring(0, pos) + title.substring(pos + 1); } } } super.setTitle(title); } // setTitle /** Dispose Action Name */ protected static String ACTION_DISPOSE = "CDialogDispose"; /** Action */ protected static DialogAction s_dialogAction = new DialogAction(ACTION_DISPOSE); /** ALT-EXCAPE */ protected static KeyStroke s_disposeKeyStroke = KeyStroke.getKeyStroke(KeyEvent.VK_PAUSE, InputEvent.ALT_MASK); /** * Adempiere Dialog Action * * @author Jorg Janke * @version $Id: CDialog.java,v 1.3 2006/07/30 00:52:24 jjanke Exp $ */ static class DialogAction extends AbstractAction { /** * */ private static final long serialVersionUID = -1502992970807699945L; DialogAction(final String actionName)
{ super(actionName); putValue(Action.ACTION_COMMAND_KEY, actionName); } // DialogAction /** * Action Listener * * @param e event */ @Override public void actionPerformed(final ActionEvent e) { if (ACTION_DISPOSE.equals(e.getActionCommand())) { Object source = e.getSource(); while (source != null) { if (source instanceof Window) { ((Window)source).dispose(); return; } if (source instanceof Container) { source = ((Container)source).getParent(); } else { source = null; } } } else { System.out.println("Action: " + e); } } // actionPerformed } // DialogAction } // CDialog
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CDialog.java
1
请在Spring Boot框架中完成以下Java代码
public Queue queueMessages() { return new Queue("topic.messages"); } //===============以上是验证topic Exchange的队列========== //===============以下是验证Fanout Exchange的队列========== @Bean public Queue AMessage() { return new Queue("fanout.A"); } @Bean public Queue BMessage() { return new Queue("fanout.B"); } @Bean public Queue CMessage() { return new Queue("fanout.C"); } //===============以上是验证Fanout Exchange的队列========== @Bean TopicExchange exchange() { return new TopicExchange("exchange"); } @Bean FanoutExchange fanoutExchange() { return new FanoutExchange("fanoutExchange"); } /** * 将队列topic.message与exchange绑定,binding_key为topic.message,就是完全匹配 * @param queueMessage * @param exchange * @return */ @Bean Binding bindingExchangeMessage(Queue queueMessage, TopicExchange exchange) { return BindingBuilder.bind(queueMessage).to(exchange).with("topic.message"); } /** * 将队列topic.messages与exchange绑定,binding_key为topic.#,模糊匹配 * @param queueMessages * @param exchange * @return */ @Bean
Binding bindingExchangeMessages(Queue queueMessages, TopicExchange exchange) { return BindingBuilder.bind(queueMessages).to(exchange).with("topic.#"); } @Bean Binding bindingExchangeA(Queue AMessage, FanoutExchange fanoutExchange) { return BindingBuilder.bind(AMessage).to(fanoutExchange); } @Bean Binding bindingExchangeB(Queue BMessage, FanoutExchange fanoutExchange) { return BindingBuilder.bind(BMessage).to(fanoutExchange); } @Bean Binding bindingExchangeC(Queue CMessage, FanoutExchange fanoutExchange) { return BindingBuilder.bind(CMessage).to(fanoutExchange); } @Bean @Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE) //必须是prototype类型 public RabbitTemplate rabbitTemplate() { RabbitTemplate template = new RabbitTemplate(connectionFactory()); return template; } }
repos\spring-boot-quick-master\quick-rabbitmq\src\main\java\com\quick\mq\config\RabbitConfig.java
2
请完成以下Java代码
private List<I_M_HU> retrieveVHUsFromStorage( @NonNull final List<I_M_ShipmentSchedule> shipmentSchedules, final boolean considerAttributes, final boolean isExcludeAllReserved) { // // Create storage queries from shipment schedules final IShipmentScheduleBL shipmentScheduleBL = Services.get(IShipmentScheduleBL.class); final ArrayList<IStorageQuery> storageQueries = new ArrayList<>(); for (final I_M_ShipmentSchedule shipmentSchedule : shipmentSchedules) { final IStorageQuery storageQuery = shipmentScheduleBL.createStorageQuery(shipmentSchedule, considerAttributes, isExcludeAllReserved); storageQueries.add(storageQuery); } // // Retrieve Storage records final IStorageEngineService storageEngineProvider = Services.get(IStorageEngineService.class); final IStorageEngine storageEngine = storageEngineProvider.getStorageEngine(); final IContextAware context = PlainContextAware.createUsingOutOfTransaction(); final Collection<IStorageRecord> storageRecords = storageEngine.retrieveStorageRecords(context, storageQueries); // // Fetch VHUs from storage records final List<I_M_HU> vhus = new ArrayList<>(); for (final IStorageRecord storageRecord : storageRecords) { addToVhusIfValid(storageRecord, vhus); } return vhus; } private void addToVhusIfValid( @NonNull final IStorageRecord storageRecord, @NonNull final List<I_M_HU> vhus) { final HUStorageRecord huStorageRecord = HUStorageRecord.cast(storageRecord); final I_M_HU vhu = huStorageRecord.getVHU(); // Skip those VHUs which are not about active HUs // (i.e. we are skipping things which were already picked) final IHUStatusBL huStatusBL = Services.get(IHUStatusBL.class); if (!(huStatusBL.isStatusActive(vhu))) { return; }
final I_M_Locator locator = huStorageRecord.getLocator(); if (locator != null && locator.getM_Locator_ID() != vhu.getM_Locator_ID()) { return; } final PickingCandidateRepository pickingCandidatesRepo = SpringContextHolder.instance.getBean(PickingCandidateRepository.class); final HuId huId = HuId.ofRepoId(vhu.getM_HU_ID()); if (pickingCandidatesRepo.isHuIdPicked(huId)) { return; } final ProductId productId = huStorageRecord.getProductId(); if (!huAttributesBL.areMandatoryPickingAttributesFulfilled(huId, productId)) { return; } final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); if (!handlingUnitsBL.isHUHierarchyCleared(HuId.ofRepoId(vhu.getM_HU_ID()))) { return; } // What was the purpose if this check? // At any rate, it caused the problem that if you selected a top-level VHU as source-HU, // you could never pick from it because it was not added to 'vhus'. // final SourceHUsService sourceHuService = SourceHUsService.get(); // if (sourceHuService.isSourceHu(vhu.getM_HU_ID())) // { // return; // } vhus.add(vhu); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\picking\slot\impl\HUPickingSlotBLs\RetrieveAvailableHUsToPick.java
1
请完成以下Java代码
public void setM_Attribute_ID (final int M_Attribute_ID) { if (M_Attribute_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Attribute_ID, M_Attribute_ID); } @Override public int getM_Attribute_ID() { return get_ValueAsInt(COLUMNNAME_M_Attribute_ID); } @Override public org.compiere.model.I_M_AttributeSearch getM_AttributeSearch() { return get_ValueAsPO(COLUMNNAME_M_AttributeSearch_ID, org.compiere.model.I_M_AttributeSearch.class); } @Override public void setM_AttributeSearch(final org.compiere.model.I_M_AttributeSearch M_AttributeSearch) { set_ValueFromPO(COLUMNNAME_M_AttributeSearch_ID, org.compiere.model.I_M_AttributeSearch.class, M_AttributeSearch); } @Override public void setM_AttributeSearch_ID (final int M_AttributeSearch_ID) { if (M_AttributeSearch_ID < 1) set_Value (COLUMNNAME_M_AttributeSearch_ID, null); else set_Value (COLUMNNAME_M_AttributeSearch_ID, M_AttributeSearch_ID); } @Override public int getM_AttributeSearch_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSearch_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPrintValue_Override (final @Nullable java.lang.String PrintValue_Override) { set_Value (COLUMNNAME_PrintValue_Override, PrintValue_Override); } @Override public java.lang.String getPrintValue_Override() { return get_ValueAsString(COLUMNNAME_PrintValue_Override); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); }
@Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueMax (final @Nullable BigDecimal ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } @Override public BigDecimal getValueMax() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMax); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValueMin (final @Nullable BigDecimal ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } @Override public BigDecimal getValueMin() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMin); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Attribute.java
1
请完成以下Java代码
public boolean getParameter_ToAsBool(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); if (processInfoParameter == null) { return false; } return processInfoParameter.getParameter_ToAsBoolean(); } @Override public final Timestamp getParameterAsTimestamp(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameterAsTimestamp() : null; } @Override public LocalDate getParameterAsLocalDate(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameterAsLocalDate() : null; } @Override public ZonedDateTime getParameterAsZonedDateTime(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameterAsZonedDateTime() : null; } @Override public Instant getParameterAsInstant(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameterAsInstant() : null; } @Override public Timestamp getParameter_ToAsTimestamp(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameter_ToAsTimestamp() : null; }
@Override public LocalDate getParameter_ToAsLocalDate(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameter_ToAsLocalDate() : null; } @Override public ZonedDateTime getParameter_ToAsZonedDateTime(final String parameterName) { final ProcessInfoParameter processInfoParameter = getProcessInfoParameterOrNull(parameterName); return processInfoParameter != null ? processInfoParameter.getParameter_ToAsZonedDateTime() : null; } /** * Returns an immutable collection of the wrapped process parameter names. */ @Override public Collection<String> getParameterNames() { return ImmutableSet.copyOf(getParametersMap().keySet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\ProcessParams.java
1
请在Spring Boot框架中完成以下Java代码
public Boolean isArchived() { return archived; } public void setArchived(Boolean archived) { this.archived = archived; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } PatientNote patientNote = (PatientNote) o; return Objects.equals(this.status, patientNote.status) && Objects.equals(this.noteText, patientNote.noteText) && Objects.equals(this.patientId, patientNote.patientId) && Objects.equals(this.archived, patientNote.archived); } @Override public int hashCode() { return Objects.hash(status, noteText, patientId, archived); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class PatientNote {\n"); sb.append(" status: ").append(toIndentedString(status)).append("\n"); sb.append(" noteText: ").append(toIndentedString(noteText)).append("\n"); sb.append(" patientId: ").append(toIndentedString(patientId)).append("\n");
sb.append(" archived: ").append(toIndentedString(archived)).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-patient-api\src\main\java\io\swagger\client\model\PatientNote.java
2
请在Spring Boot框架中完成以下Java代码
public class X_SUMUP_Config extends org.compiere.model.PO implements I_SUMUP_Config, org.compiere.model.I_Persistent { private static final long serialVersionUID = 886836191L; /** Standard Constructor */ public X_SUMUP_Config (final Properties ctx, final int SUMUP_Config_ID, @Nullable final String trxName) { super (ctx, SUMUP_Config_ID, trxName); } /** Load Constructor */ public X_SUMUP_Config (final Properties ctx, final ResultSet rs, @Nullable final String trxName) { super (ctx, rs, trxName); } /** Load Meta Data */ @Override protected org.compiere.model.POInfo initPO(final Properties ctx) { return org.compiere.model.POInfo.getPOInfo(Table_Name); } @Override public void setApiKey (final java.lang.String ApiKey) { set_Value (COLUMNNAME_ApiKey, ApiKey); } @Override public java.lang.String getApiKey() { return get_ValueAsString(COLUMNNAME_ApiKey); } @Override public de.metas.payment.sumup.repository.model.I_SUMUP_CardReader getSUMUP_CardReader() { return get_ValueAsPO(COLUMNNAME_SUMUP_CardReader_ID, de.metas.payment.sumup.repository.model.I_SUMUP_CardReader.class); } @Override public void setSUMUP_CardReader(final de.metas.payment.sumup.repository.model.I_SUMUP_CardReader SUMUP_CardReader) { set_ValueFromPO(COLUMNNAME_SUMUP_CardReader_ID, de.metas.payment.sumup.repository.model.I_SUMUP_CardReader.class, SUMUP_CardReader); } @Override public void setSUMUP_CardReader_ID (final int SUMUP_CardReader_ID) { if (SUMUP_CardReader_ID < 1) set_Value (COLUMNNAME_SUMUP_CardReader_ID, null); else set_Value (COLUMNNAME_SUMUP_CardReader_ID, SUMUP_CardReader_ID); } @Override
public int getSUMUP_CardReader_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_CardReader_ID); } @Override public void setSUMUP_Config_ID (final int SUMUP_Config_ID) { if (SUMUP_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_SUMUP_Config_ID, SUMUP_Config_ID); } @Override public int getSUMUP_Config_ID() { return get_ValueAsInt(COLUMNNAME_SUMUP_Config_ID); } @Override public void setSUMUP_merchant_code (final java.lang.String SUMUP_merchant_code) { set_Value (COLUMNNAME_SUMUP_merchant_code, SUMUP_merchant_code); } @Override public java.lang.String getSUMUP_merchant_code() { return get_ValueAsString(COLUMNNAME_SUMUP_merchant_code); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup\src\main\java-gen\de\metas\payment\sumup\repository\model\X_SUMUP_Config.java
2
请完成以下Java代码
public void setAD_AlertRecipient_ID (int AD_AlertRecipient_ID) { if (AD_AlertRecipient_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_AlertRecipient_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_AlertRecipient_ID, Integer.valueOf(AD_AlertRecipient_ID)); } /** Get Alert Recipient. @return Recipient of the Alert Notification */ public int getAD_AlertRecipient_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_AlertRecipient_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_Role getAD_Role() throws RuntimeException { return (I_AD_Role)MTable.get(getCtx(), I_AD_Role.Table_Name) .getPO(getAD_Role_ID(), get_TrxName()); } /** Set Role. @param AD_Role_ID Responsibility Role */ public void setAD_Role_ID (int AD_Role_ID) { if (AD_Role_ID < 0) set_Value (COLUMNNAME_AD_Role_ID, null); else set_Value (COLUMNNAME_AD_Role_ID, Integer.valueOf(AD_Role_ID)); } /** Get Role. @return Responsibility Role */ public int getAD_Role_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Role_ID); if (ii == null) return 0; return ii.intValue(); } public I_AD_User getAD_User() throws RuntimeException { return (I_AD_User)MTable.get(getCtx(), I_AD_User.Table_Name) .getPO(getAD_User_ID(), get_TrxName()); }
/** Set User/Contact. @param AD_User_ID User within the system - Internal or Business Partner Contact */ public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 1) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get User/Contact. @return User within the system - Internal or Business Partner Contact */ public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getAD_User_ID())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_AlertRecipient.java
1
请在Spring Boot框架中完成以下Java代码
public PPOrderId createRepairOrder( @NonNull final ServiceRepairProjectInfo project, @NonNull final ServiceRepairProjectTask task) { if (!ServiceRepairProjectTaskType.REPAIR_ORDER.equals(task.getType())) { throw new AdempiereException("Not an repair order task: " + task); } if (!ServiceRepairProjectTaskStatus.NOT_STARTED.equals(task.getStatus())) { throw new AdempiereException("Task already started: " + task); } if (task.getRepairOrderId() != null) { throw new AdempiereException("A Repair Order was already created: " + task); } final WarehouseId warehouseId = project.getWarehouseId(); if (warehouseId == null) { throw new AdempiereException("No warehouse for " + project); } final ResourceId plantId = productPlanningService.getPlantOfWarehouse(warehouseId) .orElseThrow(() -> new AdempiereException("No plant for warehouse " + warehouseId)); final PPRoutingId routingId = productPlanningService.getDefaultRoutingId(PPRoutingType.Repair) .orElse(PPRoutingId.NONE); final Instant now = SystemTime.asInstant(); final PPOrderId repairOrderId; final LocatorId locatorId; { final I_PP_Order repairOrder = ppOrderBL.createOrder(PPOrderCreateRequest.builder() .docBaseType(PPOrderDocBaseType.REPAIR_ORDER) .clientAndOrgId(task.getClientAndOrgId()) .warehouseId(warehouseId) .plantId(plantId) .routingId(routingId)
// .productId(task.getProductId()) .attributeSetInstanceId(task.getAsiId()) .qtyRequired(task.getQtyRequired()) // .dateOrdered(now) .datePromised(now) .dateStartSchedule(now) // .projectId(project.getProjectId()) // .completeDocument(true) // .build()); repairOrderId = PPOrderId.ofRepoId(repairOrder.getPP_Order_ID()); locatorId = LocatorId.ofRepoId(repairOrder.getM_Warehouse_ID(), repairOrder.getM_Locator_ID()); } huPPOrderQtyDAO.save(CreateReceiptCandidateRequest.builder() .orderId(repairOrderId) .orgId(task.getClientAndOrgId().getOrgId()) .date(TimeUtil.asZonedDateTime(now)) .locatorId(locatorId) .topLevelHUId(task.getRepairVhuId()) .productId(task.getProductId()) .qtyToReceive(task.getQtyRequired()) .alreadyProcessed(true) .build()); ppOrderBL.addQty(OrderQtyChangeRequest.builder() .ppOrderId(repairOrderId) .qtyReceivedToAdd(task.getQtyRequired()) .date(TimeUtil.asZonedDateTime(now)) .build()); return repairOrderId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\repair_order\RepairManufacturingOrderService.java
2
请完成以下Java代码
/* for testing */ static class Forwarded { private static final char EQUALS = '='; private static final char SEMICOLON = ';'; private final Map<String, String> values; Forwarded() { this.values = new HashMap<>(); } Forwarded(Map<String, String> values) { this.values = values; } public Forwarded put(String key, String value) { this.values.put(key, quoteIfNeeded(value)); return this; } private String quoteIfNeeded(String s) { if (s != null && s.contains(":")) { // TODO: broaded quote return "\"" + s + "\""; } return s; } public @Nullable String get(String key) {
return this.values.get(key); } /* for testing */ Map<String, String> getValues() { return this.values; } @Override public String toString() { return "Forwarded{" + "values=" + this.values + '}'; } public String toHeaderValue() { StringBuilder builder = new StringBuilder(); for (Map.Entry<String, String> entry : this.values.entrySet()) { if (!builder.isEmpty()) { builder.append(SEMICOLON); } builder.append(entry.getKey()).append(EQUALS).append(entry.getValue()); } return builder.toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\headers\ForwardedHeadersFilter.java
1
请在Spring Boot框架中完成以下Java代码
static class Jsr250MethodSecurityMetadataSourceBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory { private Jsr250MethodSecurityMetadataSource source = new Jsr250MethodSecurityMetadataSource(); Jsr250MethodSecurityMetadataSource getBean() { this.source.setDefaultRolePrefix(this.rolePrefix); return this.source; } } static class DefaultMethodSecurityExpressionHandlerBeanFactory extends AbstractGrantedAuthorityDefaultsBeanFactory { private DefaultMethodSecurityExpressionHandler handler = new DefaultMethodSecurityExpressionHandler(); DefaultMethodSecurityExpressionHandler getBean() { this.handler.setDefaultRolePrefix(this.rolePrefix); return this.handler; } } abstract static class AbstractGrantedAuthorityDefaultsBeanFactory implements ApplicationContextAware { protected String rolePrefix = "ROLE_"; @Override public final void setApplicationContext(ApplicationContext applicationContext) throws BeansException { applicationContext.getBeanProvider(GrantedAuthorityDefaults.class) .ifUnique((grantedAuthorityDefaults) -> this.rolePrefix = grantedAuthorityDefaults.getRolePrefix()); } } /** * Delays setting a bean of a given name to be lazyily initialized until after all the * beans are registered. * * @author Rob Winch * @since 3.2 */ private static final class LazyInitBeanDefinitionRegistryPostProcessor implements BeanDefinitionRegistryPostProcessor { private final String beanName;
private LazyInitBeanDefinitionRegistryPostProcessor(String beanName) { this.beanName = beanName; } @Override public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException { if (!registry.containsBeanDefinition(this.beanName)) { return; } BeanDefinition beanDefinition = registry.getBeanDefinition(this.beanName); beanDefinition.setLazyInit(true); } @Override public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException { } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\method\GlobalMethodSecurityBeanDefinitionParser.java
2
请完成以下Java代码
public void decisionWithoutExpression(Decision decision) { logInfo( "014", "The decision '{}' has no expression and will be ignored.", decision.getName() ); } public DmnTransformException requiredDecisionLoopDetected(String decisionId) { return new DmnTransformException(exceptionMessage( "015", "The decision '{}' has a loop.", decisionId) ); } public DmnTransformException errorWhileTransformingDefinitions(Throwable cause) { return new DmnTransformException(exceptionMessage( "016", "Error while transforming decision requirements graph: " + cause.getMessage()), cause );
} public DmnTransformException drdIdIsMissing(DmnDecisionRequirementsGraph drd) { return new DmnTransformException(exceptionMessage( "017", "The decision requirements graph '{}' must have an 'id' attribute set.", drd) ); } public DmnTransformException decisionVariableIsMissing(String decisionId) { return new DmnTransformException(exceptionMessage( "018", "The decision '{}' must have an 'variable' element if it contains a literal expression.", decisionId)); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DmnTransformLogger.java
1
请完成以下Java代码
public class TriggerPlanItemInstanceOperation extends AbstractPlanItemInstanceOperation { public TriggerPlanItemInstanceOperation(CommandContext commandContext, PlanItemInstanceEntity planItemInstanceEntity) { super(commandContext, planItemInstanceEntity); } @Override public void run() { if (PlanItemInstanceState.ACTIVE.equals(planItemInstanceEntity.getState()) || (planItemInstanceEntity.getPlanItem() != null && planItemInstanceEntity.getPlanItem().getPlanItemDefinition() instanceof EventListener && PlanItemInstanceState.AVAILABLE.equals(planItemInstanceEntity.getState()))){ executeTrigger(); } else { if (planItemInstanceEntity.getPlanItem() != null && planItemInstanceEntity.getPlanItem().getPlanItemDefinition() instanceof EventListener){ throw new FlowableIllegalStateException("Can only trigger an event listener plan item that is in the AVAILABLE state"); } else { throw new FlowableIllegalStateException("Can only trigger a plan item that is in the ACTIVE state"); } } }
protected void executeTrigger() { Object behaviorObject = planItemInstanceEntity.getPlanItem().getBehavior(); if (!(behaviorObject instanceof CmmnTriggerableActivityBehavior)) { throw new FlowableException("Cannot trigger a plan item which activity behavior does not implement the " + CmmnTriggerableActivityBehavior.class + " interface in " + planItemInstanceEntity); } CmmnTriggerableActivityBehavior behavior = (CmmnTriggerableActivityBehavior) planItemInstanceEntity.getPlanItem().getBehavior(); if (behavior instanceof CoreCmmnTriggerableActivityBehavior) { ((CoreCmmnTriggerableActivityBehavior) behavior).trigger(commandContext, planItemInstanceEntity); } else { behavior.trigger(planItemInstanceEntity); } } @Override public String toString() { PlanItem planItem = planItemInstanceEntity.getPlanItem(); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.append("[Trigger PlanItem] "); stringBuilder.append(planItem); return stringBuilder.toString(); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\TriggerPlanItemInstanceOperation.java
1
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_M_PromotionGroupLine[") .append(get_ID()).append("]"); return sb.toString(); } public I_M_Product getM_Product() throws RuntimeException { return (I_M_Product)MTable.get(getCtx(), I_M_Product.Table_Name) .getPO(getM_Product_ID(), get_TrxName()); } /** Set Product. @param M_Product_ID Product, Service, Item */ public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Product. @return Product, Service, Item */ public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_PromotionGroup getM_PromotionGroup() throws RuntimeException { return (I_M_PromotionGroup)MTable.get(getCtx(), I_M_PromotionGroup.Table_Name) .getPO(getM_PromotionGroup_ID(), get_TrxName()); } /** Set Promotion Group. @param M_PromotionGroup_ID Promotion Group */ public void setM_PromotionGroup_ID (int M_PromotionGroup_ID) { if (M_PromotionGroup_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, null); else
set_ValueNoCheck (COLUMNNAME_M_PromotionGroup_ID, Integer.valueOf(M_PromotionGroup_ID)); } /** Get Promotion Group. @return Promotion Group */ public int getM_PromotionGroup_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroup_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Promotion Group Line. @param M_PromotionGroupLine_ID Promotion Group Line */ public void setM_PromotionGroupLine_ID (int M_PromotionGroupLine_ID) { if (M_PromotionGroupLine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_PromotionGroupLine_ID, Integer.valueOf(M_PromotionGroupLine_ID)); } /** Get Promotion Group Line. @return Promotion Group Line */ public int getM_PromotionGroupLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_PromotionGroupLine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_PromotionGroupLine.java
1
请完成以下Java代码
public void output(Writer out) { output ( new PrintWriter(out) ); } /** Override output(BufferedWriter) incase any elements are in the registry. @param out OutputStream to write to. */ public void output(PrintWriter out) { boolean prettyPrint = getPrettyPrint(); int tabLevel = getTabLevel(); if (registry.size() == 0) { if ((prettyPrint && this instanceof Printable) && (tabLevel > 0)) putTabs(tabLevel, out); super.output(out); } else { if ((prettyPrint && this instanceof Printable) && (tabLevel > 0)) putTabs(tabLevel, out); out.write(createStartTag()); // If this is a StringElement that has ChildElements still print the TagText if(getTagText() != null) out.write(getTagText()); Enumeration<String> en = registryList.elements(); while(en.hasMoreElements()) { Object obj = registry.get(en.nextElement()); if(obj instanceof GenericElement) { Element e = (Element)obj; if (prettyPrint && this instanceof Printable) { if (getNeedLineBreak()) { out.write('\n'); e.setTabLevel(tabLevel + 1); } } e.output(out); } else { if (prettyPrint && this instanceof Printable) { if (getNeedLineBreak()) { out.write('\n'); putTabs(tabLevel + 1, out); } } String string = obj.toString(); if(getFilterState()) out.write(getFilter().process(string)); else out.write(string); } } if (getNeedClosingTag()) { if (prettyPrint && this instanceof Printable) { if (getNeedLineBreak()) { out.write('\n'); if (tabLevel > 0) putTabs(tabLevel, out); } }
out.write(createEndTag()); } } } /** * Allows all Elements the ability to be cloned. */ public Object clone() { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(this); out.close(); ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray()); ObjectInputStream in = new ObjectInputStream(bin); Object clone = in.readObject(); in.close(); return(clone); } catch(ClassNotFoundException cnfe) { throw new InternalError(cnfe.toString()); } catch(StreamCorruptedException sce) { throw new InternalError(sce.toString()); } catch(IOException ioe) { throw new InternalError(ioe.toString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\ConcreteElement.java
1
请在Spring Boot框架中完成以下Java代码
public class CustomizedResponseEntityExceptionHandler extends ResponseEntityExceptionHandler{ @ExceptionHandler(Exception.class) public final ResponseEntity<ErrorDetails> handleAllExceptions(Exception ex, WebRequest request) throws Exception { ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(), ex.getMessage(), request.getDescription(false)); return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.INTERNAL_SERVER_ERROR); } @ExceptionHandler(UserNotFoundException.class) public final ResponseEntity<ErrorDetails> handleUserNotFoundException(Exception ex, WebRequest request) throws Exception { ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(), ex.getMessage(), request.getDescription(false));
return new ResponseEntity<ErrorDetails>(errorDetails, HttpStatus.NOT_FOUND); } @Override protected ResponseEntity<Object> handleMethodArgumentNotValid( MethodArgumentNotValidException ex, HttpHeaders headers, HttpStatusCode status, WebRequest request) { ErrorDetails errorDetails = new ErrorDetails(LocalDateTime.now(), "Total Errors:" + ex.getErrorCount() + " First Error:" + ex.getFieldError().getDefaultMessage(), request.getDescription(false)); return new ResponseEntity(errorDetails, HttpStatus.BAD_REQUEST); } }
repos\master-spring-and-spring-boot-main\12-rest-api\src\main\java\com\in28minutes\rest\webservices\restfulwebservices\exception\CustomizedResponseEntityExceptionHandler.java
2
请在Spring Boot框架中完成以下Java代码
public class UserController { @Autowired private UserRepository userRepository; @RequestMapping("/hello") @Cacheable(value="helloCache") public String hello(String name) { System.out.println("没有走缓存!"); return "hello "+name; } @RequestMapping("/condition") @Cacheable(value="condition",condition="#name.length() <= 4") public String condition(String name) { System.out.println("没有走缓存!"); return "hello "+name; } @RequestMapping("/getUsers") @Cacheable(value="usersCache",key="#nickname",condition="#nickname.length() >= 6") public List<User> getUsers(String nickname) { List<User> users=userRepository.findByNickname(nickname); System.out.println("执行了数据库操作"); return users;
} @RequestMapping("/getPutUsers") @CachePut(value="usersCache",key="#nickname") public List<User> getPutUsers(String nickname) { List<User> users=userRepository.findByNickname(nickname); System.out.println("执行了数据库操作"); return users; } @RequestMapping("/allEntries") @CacheEvict(value="usersCache", allEntries=true) public String allEntries(String nickname) { String msg="执行了allEntries"; System.out.println(msg); return msg; } @RequestMapping("/beforeInvocation") @CacheEvict(value="usersCache", allEntries=true, beforeInvocation=true) public void beforeInvocation() { throw new RuntimeException("test beforeInvocation"); } }
repos\spring-boot-leaning-master\1.x\第10课:Redis实现数据缓存和Session共享\spring-boot-redis-data-cache\src\main\java\com\neo\web\UserController.java
2
请完成以下Java代码
public BigDecimal getAmount() { return amount; } /** * Sets the value of the amount property. * * @param value * allowed object is * {@link String } * */ public void setAmount(BigDecimal value) { this.amount = value; } /** * Gets the value of the vatRate property. * * @return * possible object is * {@link String } * */ public BigDecimal getVatRate() { if (vatRate == null) { return new Adapter1().unmarshal("0"); } else { return vatRate; } } /** * Sets the value of the vatRate property. * * @param value * allowed object is * {@link String } * */ public void setVatRate(BigDecimal value) { this.vatRate = value; } /** * Gets the value of the obligation property. * * @return * possible object is * {@link Boolean } * */ public boolean isObligation() { if (obligation == null) { return true; } else { return obligation; } } /** * Sets the value of the obligation property. * * @param value * allowed object is * {@link Boolean } * */ public void setObligation(Boolean value) { this.obligation = value; } /** * Gets the value of the sectionCode property.
* * @return * possible object is * {@link String } * */ public String getSectionCode() { return sectionCode; } /** * Sets the value of the sectionCode property. * * @param value * allowed object is * {@link String } * */ public void setSectionCode(String value) { this.sectionCode = value; } /** * Gets the value of the remark property. * * @return * possible object is * {@link String } * */ public String getRemark() { return remark; } /** * Sets the value of the remark property. * * @param value * allowed object is * {@link String } * */ public void setRemark(String value) { this.remark = value; } /** * Gets the value of the serviceAttributes property. * * @return * possible object is * {@link Long } * */ public long getServiceAttributes() { if (serviceAttributes == null) { return 0L; } else { return serviceAttributes; } } /** * Sets the value of the serviceAttributes property. * * @param value * allowed object is * {@link Long } * */ public void setServiceAttributes(Long value) { this.serviceAttributes = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\request\ServiceType.java
1
请完成以下Java代码
public BPartnerDepartment getById(@NonNull final BPartnerDepartmentId id) { return getByBPartnerId(id.getBpartnerId()) .stream() .filter(dpt -> id.equals(dpt.getId())) .findFirst().orElse(null); } @NonNull public BPartnerDepartment getByIdNotNull(@NonNull final BPartnerDepartmentId id) { return getByBPartnerId(id.getBpartnerId()) .stream() .filter(dpt -> id.equals(dpt.getId())) .findFirst().orElseThrow(() -> new AdempiereException("Missing BPartnerDepartment for id=" + id)); } @NonNull public List<BPartnerDepartment> getByBPartnerId(@NonNull final BPartnerId bPartnerId) { return bPartnerDepartmentCache.getOrLoad(bPartnerId, this::getByBPartnerId0); }
private List<BPartnerDepartment> getByBPartnerId0(@NonNull final BPartnerId bPartnerId) { return queryBL.createQueryBuilder(I_C_BPartner_Department.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_BPartner_Department.COLUMNNAME_C_BPartner_ID, bPartnerId) .orderBy(I_C_BPartner_Department.COLUMNNAME_Value) .create() .stream() .map(this::fromPO) .collect(ImmutableList.toImmutableList()); } private BPartnerDepartment fromPO(@NonNull final I_C_BPartner_Department po) { final BPartnerDepartmentId id = BPartnerDepartmentId.ofRepoId(po.getC_BPartner_ID(), po.getC_BPartner_Department_ID()); return new BPartnerDepartment(id, po.getValue(), po.getName(), po.getDescription()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\department\BPartnerDepartmentRepo.java
1
请完成以下Java代码
public DmnDecisionResultEntries get(int index) { return ruleResults.get(index); } @Override public boolean contains(Object o) { return ruleResults.contains(o); } @Override public Object[] toArray() { return ruleResults.toArray(); } @Override public <T> T[] toArray(T[] a) { return ruleResults.toArray(a); } @Override public boolean add(DmnDecisionResultEntries e) { throw new UnsupportedOperationException("decision result is immutable"); } @Override public boolean remove(Object o) { throw new UnsupportedOperationException("decision result is immutable"); } @Override public boolean containsAll(Collection<?> c) { return ruleResults.containsAll(c); } @Override public boolean addAll(Collection<? extends DmnDecisionResultEntries> c) { throw new UnsupportedOperationException("decision result is immutable"); } @Override public boolean addAll(int index, Collection<? extends DmnDecisionResultEntries> c) { throw new UnsupportedOperationException("decision result is immutable"); } @Override public boolean removeAll(Collection<?> c) { throw new UnsupportedOperationException("decision result is immutable"); } @Override public boolean retainAll(Collection<?> c) { throw new UnsupportedOperationException(); }
@Override public void clear() { throw new UnsupportedOperationException("decision result is immutable"); } @Override public DmnDecisionResultEntries set(int index, DmnDecisionResultEntries element) { throw new UnsupportedOperationException("decision result is immutable"); } @Override public void add(int index, DmnDecisionResultEntries element) { throw new UnsupportedOperationException("decision result is immutable"); } @Override public DmnDecisionResultEntries remove(int index) { throw new UnsupportedOperationException("decision result is immutable"); } @Override public int indexOf(Object o) { return ruleResults.indexOf(o); } @Override public int lastIndexOf(Object o) { return ruleResults.lastIndexOf(o); } @Override public ListIterator<DmnDecisionResultEntries> listIterator() { return asUnmodifiableList().listIterator(); } @Override public ListIterator<DmnDecisionResultEntries> listIterator(int index) { return asUnmodifiableList().listIterator(index); } @Override public List<DmnDecisionResultEntries> subList(int fromIndex, int toIndex) { return asUnmodifiableList().subList(fromIndex, toIndex); } @Override public String toString() { return ruleResults.toString(); } protected List<DmnDecisionResultEntries> asUnmodifiableList() { return Collections.unmodifiableList(ruleResults); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\DmnDecisionResultImpl.java
1
请完成以下Java代码
public void onPartitionsRevoked(Collection<TopicPartition> partitions) { logger.info("Revoked partitions: {}", partitions); // complete processing of current records } @Override public void onPartitionsAssigned(Collection<TopicPartition> partitions) { logger.info("Assigned partitions: {}", partitions); // initialize any partition-specific state } }); // process a few records to demonstrate int recordCount = 0; while (recordCount < 5) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100)); recordCount += records.count(); } consumer.close(); } public void processWithManualCommit() { Properties props = new Properties(); props.put("bootstrap.servers", bootstrapServers); props.put("group.id", "manual-commit-group"); props.put("enable.auto.commit", "false"); props.put("max.poll.records", "10"); props.put("key.deserializer", StringDeserializer.class.getName()); props.put("value.deserializer", StringDeserializer.class.getName()); props.put("auto.offset.reset", "earliest"); KafkaConsumer<String, String> consumer = new KafkaConsumer<>(props); consumer.subscribe(Arrays.asList("orders")); int totalProcessed = 0; while (totalProcessed < 10) { ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(100));
for (ConsumerRecord<String, String> record : records) { try { processOrder(record); totalProcessed++; } catch (Exception e) { logger.error("Processing failed for offset: {}", record.offset(), e); break; } } if (!records.isEmpty()) { consumer.commitSync(); logger.info("Committed {} records", records.count()); } } consumer.close(); } private void processOrder(ConsumerRecord<String, String> record) { // simulate order processing logger.info("Processing order: {}", record.value()); // this section is mostly your part of implementation, which is out of bounds of the article topic coverage } }
repos\tutorials-master\apache-kafka-3\src\main\java\com\baeldung\kafka\partitions\KafkaMultiplePartitionsDemo.java
1
请完成以下Java代码
public static POSPaymentMethod ofCode(@NonNull String code) {return index.ofCode(code);} @JsonValue @NonNull public String getCode() {return code;} public static boolean equals(@Nullable final POSPaymentMethod value1, @Nullable final POSPaymentMethod value2) {return Objects.equals(value1, value2);} public boolean isCash() {return this == CASH;} public boolean isCard() {return this == CARD;} public void assertCash() { if (!isCash())
{ throw new AdempiereException("Expected CASH payment method but it was " + this); } } public void assertCard() { if (!isCard()) { throw new AdempiereException("Expected CARD payment method but it was " + this); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSPaymentMethod.java
1
请在Spring Boot框架中完成以下Java代码
public Date getEndTime() { return endTime; } public void setEndTime(Date endTime) { this.endTime = endTime; } @ApiModelProperty(example = "kermit") public String getStartUserId() { return startUserId; } public void setStartUserId(String startUserId) { this.startUserId = startUserId; } @ApiModelProperty(example = "kermit") public String getEndUserId() { return endUserId; } public void setEndUserId(String endUserId) { this.endUserId = endUserId; } @ApiModelProperty(example = "3") public String getSuperProcessInstanceId() { return superProcessInstanceId; } public void setSuperProcessInstanceId(String superProcessInstanceId) { this.superProcessInstanceId = superProcessInstanceId; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } @ApiModelProperty(example = "null") public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId;
} @ApiModelProperty(example = "active") public String getState() { return state; } public void setState(String state) { this.state = state; } @ApiModelProperty(example = "123") public String getCallbackId() { return callbackId; } public void setCallbackId(String callbackId) { this.callbackId = callbackId; } @ApiModelProperty(example = "cmmn-1.1-to-cmmn-1.1-child-case") public String getCallbackType() { return callbackType; } public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @ApiModelProperty(example = "123") public String getReferenceId() { return referenceId; } public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @ApiModelProperty(example = "event-to-cmmn-1.1-case") public String getReferenceType() { return referenceType; } public void setReferenceType(String referenceType) { this.referenceType = referenceType; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\caze\HistoricCaseInstanceResponse.java
2
请完成以下Java代码
public final class PublicClientAuthenticationConverter implements AuthenticationConverter { @Nullable @Override public Authentication convert(HttpServletRequest request) { if (!OAuth2EndpointUtils.matchesPkceTokenRequest(request)) { return null; } MultiValueMap<String, String> parameters = "GET".equals(request.getMethod()) ? OAuth2EndpointUtils.getQueryParameters(request) : OAuth2EndpointUtils.getFormParameters(request); // client_id (REQUIRED for public clients) String clientId = parameters.getFirst(OAuth2ParameterNames.CLIENT_ID); if (!StringUtils.hasText(clientId) || parameters.get(OAuth2ParameterNames.CLIENT_ID).size() != 1) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST); }
// code_verifier (REQUIRED) if (parameters.get(PkceParameterNames.CODE_VERIFIER).size() != 1) { throw new OAuth2AuthenticationException(OAuth2ErrorCodes.INVALID_REQUEST); } parameters.remove(OAuth2ParameterNames.CLIENT_ID); Map<String, Object> additionalParameters = new HashMap<>(); parameters.forEach((key, value) -> additionalParameters.put(key, (value.size() == 1) ? value.get(0) : value.toArray(new String[0]))); return new OAuth2ClientAuthenticationToken(clientId, ClientAuthenticationMethod.NONE, null, additionalParameters); } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\web\authentication\PublicClientAuthenticationConverter.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonKPIDataResult { @With @JsonInclude(JsonInclude.Include.NON_NULL) Integer itemId; @JsonInclude(JsonInclude.Include.NON_NULL) TimeRange range; @JsonInclude(JsonInclude.Include.NON_NULL) List<JsonKPIDataSet> datasets; @JsonInclude(JsonInclude.Include.NON_NULL) JsonWebuiError error; @JsonInclude(JsonInclude.Include.NON_EMPTY) String took; @JsonInclude(JsonInclude.Include.NON_NULL) String computedTimestamp; public static JsonKPIDataResult of( @NonNull final UserDashboardItemDataResponse itemData, @NonNull final KPIJsonOptions jsonOpts) { if (itemData.getKpiData() != null) { final KPIDataResult kpiData = itemData.getKpiData(); return of(kpiData, jsonOpts) .withItemId(itemData.getItemId().getRepoId()); } else { final WebuiError error = itemData.getError();
assert error != null; return builder() .itemId(itemData.getItemId().getRepoId()) .error(JsonWebuiError.of(error, jsonOpts)) .build(); } } public static JsonKPIDataResult of( @NonNull final KPIDataResult kpiData, @NonNull final KPIJsonOptions jsonOpts) { return builder() .range(kpiData.getRange()) .datasets(kpiData.getDatasets() .stream() .map(dataSet -> JsonKPIDataSet.of(dataSet, jsonOpts)) .collect(ImmutableList.toImmutableList())) .took(kpiData.getDatasetsComputedTime().toString()) .computedTimestamp(DateTimeConverters.toJson(kpiData.getDatasetsComputedTime(), jsonOpts.getZoneId())) .error(kpiData.getError() != null ? JsonWebuiError.of(kpiData.getError(), jsonOpts) : null) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\dashboard\json\JsonKPIDataResult.java
2
请在Spring Boot框架中完成以下Java代码
public void get() throws URISyntaxException { ResponseEntity<TestDTO> responseEntity = this.restTemplate.getForEntity(HOST + GET_URL, TestDTO.class); System.out.println("getForEntity: " + responseEntity.getBody()); TestDTO forObject = this.restTemplate.getForObject(HOST + GET_URL, TestDTO.class); System.out.println("getForObject: " + forObject); RequestEntity<Void> requestEntity = RequestEntity.get(new URI(HOST + GET_URL)).build(); ResponseEntity<TestDTO> exchange = this.restTemplate.exchange(requestEntity, TestDTO.class); System.out.println("exchange: " + exchange.getBody()); } public void post() throws URISyntaxException { TestDTO td = new TestDTO(); td.setId(1); td.setName("post"); String url = HOST + POST_URL; HttpHeaders headers = new HttpHeaders(); HttpEntity<TestDTO> httpEntity = new HttpEntity<>(td, headers); ResponseEntity<TestDTO> responseEntity = this.restTemplate.postForEntity(url, httpEntity, TestDTO.class);
System.out.println("postForEntity: " + responseEntity.getBody()); TestDTO testDTO = this.restTemplate.postForObject(url, httpEntity, TestDTO.class); System.out.println("postForObject: " + testDTO); ResponseEntity<TestDTO> exchange = this.restTemplate.exchange(url, HttpMethod.POST, httpEntity, TestDTO.class); System.out.println("exchange: " + exchange.getBody()); } public void post4Form() { String url = HOST + POST_PARAM_URL; HttpHeaders headers = new HttpHeaders(); MultiValueMap<String, String> map= new LinkedMultiValueMap<>(); map.add("id", "100"); map.add("name", "post4Form"); HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers); ResponseEntity<String> responseEntity = this.restTemplate.postForEntity(url, request, String.class); System.out.println("postForEntity: " + responseEntity.getBody()); } }
repos\spring-boot-quick-master\quick-rest-template\src\main\java\com\rest\template\service\RestService.java
2
请完成以下Java代码
public void add(E e) { elements.add(e); int elementIndex = elements.size() - 1; while (!isRoot(elementIndex) && !isCorrectChild(elementIndex)) { int parentIndex = parentIndex(elementIndex); swap(elementIndex, parentIndex); elementIndex = parentIndex; } } public E pop() { if (isEmpty()) { throw new IllegalStateException("You cannot pop from an empty heap"); } E result = elementAt(0); int lasElementIndex = elements.size() - 1; swap(0, lasElementIndex); elements.remove(lasElementIndex); int elementIndex = 0; while (!isLeaf(elementIndex) && !isCorrectParent(elementIndex)) { int smallerChildIndex = smallerChildIndex(elementIndex); swap(elementIndex, smallerChildIndex); elementIndex = smallerChildIndex; } return result; } public boolean isEmpty() { return elements.isEmpty(); } private boolean isRoot(int index) { return index == 0; } private int smallerChildIndex(int index) { int leftChildIndex = leftChildIndex(index); int rightChildIndex = rightChildIndex(index); if (!isValidIndex(rightChildIndex)) { return leftChildIndex; } if (elementAt(leftChildIndex).compareTo(elementAt(rightChildIndex)) < 0) { return leftChildIndex; }
return rightChildIndex; } private boolean isLeaf(int index) { return !isValidIndex(leftChildIndex(index)); } private boolean isCorrectParent(int index) { return isCorrect(index, leftChildIndex(index)) && isCorrect(index, rightChildIndex(index)); } private boolean isCorrectChild(int index) { return isCorrect(parentIndex(index), index); } private boolean isCorrect(int parentIndex, int childIndex) { if (!isValidIndex(parentIndex) || !isValidIndex(childIndex)) { return true; } return elementAt(parentIndex).compareTo(elementAt(childIndex)) < 0; } private boolean isValidIndex(int index) { return index < elements.size(); } private void swap(int index1, int index2) { E element1 = elementAt(index1); E element2 = elementAt(index2); elements.set(index1, element2); elements.set(index2, element1); } private E elementAt(int index) { return elements.get(index); } private int parentIndex(int index) { return (index - 1) / 2; } private int leftChildIndex(int index) { return 2 * index + 1; } private int rightChildIndex(int index) { return 2 * index + 2; } }
repos\tutorials-master\algorithms-modules\algorithms-sorting-2\src\main\java\com\baeldung\algorithms\heapsort\Heap.java
1
请完成以下Java代码
protected String doIt() throws Exception { final List<ForecastRequest> forecastRequests = streamSelectedRows() .map(MaterialNeedsPlannerRow::ofViewRow) .filter(MaterialNeedsPlannerRow::isDemandFilled) .collect(Collectors.groupingBy(MaterialNeedsPlannerRow::getWarehouseId)) .entrySet() .stream() .map(entry -> { final ImmutableList<ForecastRequest.ForecastLineRequest> lines = entry.getValue().stream() .map(this::toForecastLineRequest) .collect(ImmutableList.toImmutableList()); return ForecastRequest.builder() .name(provideName(entry.getKey(), lines)) .warehouseId(entry.getKey()) .datePromised(p_DatePromised) .forecastLineRequests(lines) .build(); }) .collect(ImmutableList.toImmutableList()); final ImmutableSet<ForecastId> createdForecastIds = forecastService.createForecasts(forecastRequests); forecastService.completeAndNotifyUser(createdForecastIds, Env.getLoggedUserId()); return "@Created@: " + createdForecastIds.size(); } @Nullable @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { if (PARAM_DatePromised.equals(parameter.getColumnName())) { return getDefaultDatePromised(); } return DEFAULT_VALUE_NOTAVAILABLE; } @NonNull private ForecastRequest.ForecastLineRequest toForecastLineRequest(@NonNull final MaterialNeedsPlannerRow row) { final ProductId productId = row.getProductId(); final UomId uomId = productBL.getStockUOMId(productId); return ForecastRequest.ForecastLineRequest.builder() .productId(productId) .quantity(Quantitys.of(row.getLevelMin(), uomId)) .build(); } @NonNull
private Instant getDefaultDatePromised() { final OrgId orgId = getOrgId() != null ? getOrgId() : Env.getOrgId(); final ZoneId timeZone = orgDAO.getTimeZone(orgId); return SystemTime.asLocalDate() .with(TemporalAdjusters.next(DayOfWeek.MONDAY)) .atStartOfDay(timeZone) .toInstant(); } private String provideName(@NonNull final WarehouseId warehouseId, @NonNull final List<ForecastRequest.ForecastLineRequest> lineRequests) { if (lineRequests.size() != 1) { return warehouseBL.getWarehouseName(warehouseId) + "_" + p_DatePromised; } final ForecastRequest.ForecastLineRequest singleRequest = Check.singleElement(lineRequests); return productBL.getProductValueAndName(singleRequest.getProductId()) + " | " + singleRequest.getQuantity() + " | " + warehouseBL.getWarehouseName(warehouseId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\replenish\process\WEBUI_M_Replenish_Generate_Forecasts.java
1
请完成以下Java代码
public class Campus { @Id private String id; @Field @NotNull private String name; @Field @NotNull private Point location; public String getId() { return id; } public void setId(String id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Point getLocation() { return location; } public void setLocation(Point location) { this.location = location; } @Override public int hashCode() { int hash = 1; if (id != null) { hash = hash * 31 + id.hashCode(); } if (name != null) { hash = hash * 31 + name.hashCode(); } if (location != null) { hash = hash * 31 + location.hashCode(); } return hash; } @Override public boolean equals(Object obj) { if ((obj == null) || (obj.getClass() != this.getClass()))
return false; if (obj == this) return true; Campus other = (Campus) obj; return this.hashCode() == other.hashCode(); } @SuppressWarnings("unused") private Campus() { } public Campus(Builder b) { this.id = b.id; this.name = b.name; this.location = b.location; } public static class Builder { private String id; private String name; private Point location; public static Builder newInstance() { return new Builder(); } public Campus build() { return new Campus(this); } public Builder id(String id) { this.id = id; return this; } public Builder name(String name) { this.name = name; return this; } public Builder location(Point location) { this.location = location; return this; } } }
repos\tutorials-master\persistence-modules\spring-data-couchbase-2\src\main\java\com\baeldung\spring\data\couchbase\model\Campus.java
1
请在Spring Boot框架中完成以下Java代码
ServletRegistrationBean servletRegistrationBean() { ServletRegistrationBean servlet = new ServletRegistrationBean(new CamelHttpTransportServlet(), contextPath + "/*"); servlet.setName("CamelServlet"); return servlet; } @Component class RestApi extends RouteBuilder { @Override public void configure() { CamelContext context = new DefaultCamelContext(); // http://localhost:8080/camel/api-doc restConfiguration().contextPath(contextPath) // .port(serverPort) .enableCORS(true) .apiContextPath("/api-doc") .apiProperty("api.title", "Test REST API") .apiProperty("api.version", "v1") .apiProperty("cors", "true") // cross-site .apiContextRouteId("doc-api") .component("servlet") .bindingMode(RestBindingMode.json) .dataFormatProperty("prettyPrint", "true"); /** The Rest DSL supports automatic binding json/xml contents to/from POJOs using Camels Data Format. By default the binding mode is off, meaning there is no automatic binding happening for incoming and outgoing messages. You may want to use binding if you develop POJOs that maps to your REST services request and response types. */ rest("/api/").description("Teste REST Service") .id("api-route") .post("/bean") .produces(MediaType.APPLICATION_JSON) .consumes(MediaType.APPLICATION_JSON) // .get("/hello/{place}") .bindingMode(RestBindingMode.auto) .type(MyBean.class) .enableCORS(true) // .outType(OutBean.class)
.to("direct:remoteService"); from("direct:remoteService").routeId("direct-route") .tracing() .log(">>> ${body.id}") .log(">>> ${body.name}") // .transform().simple("blue ${in.body.name}") .process(new Processor() { @Override public void process(Exchange exchange) throws Exception { MyBean bodyIn = (MyBean) exchange.getIn() .getBody(); ExampleServices.example(bodyIn); exchange.getIn() .setBody(bodyIn); } }) .setHeader(Exchange.HTTP_RESPONSE_CODE, constant(201)); } } }
repos\tutorials-master\messaging-modules\spring-apache-camel\src\main\java\com\baeldung\camel\boot\Application.java
2
请完成以下Java代码
public void setVhuReservedFlag( @NonNull final I_M_HU_Reservation huReservationRecord, @NonNull final ModelChangeType type) { final boolean reservationIsHere = type.isNew() || ModelChangeUtil.isJustActivated(huReservationRecord); if (reservationIsHere) { final boolean isReserved = true; updateVhuIsReservedFlag(huReservationRecord, isReserved); } } @ModelChange( // timings = { ModelValidator.TYPE_AFTER_CHANGE, ModelValidator.TYPE_BEFORE_DELETE }, // ifColumnsChanged = I_M_HU_Reservation.COLUMNNAME_IsActive) public void unsetVhuReservedFlag( @NonNull final I_M_HU_Reservation huReservationRecord, @NonNull final ModelChangeType type)
{ final boolean reservationIsGone = type.isDelete() || ModelChangeUtil.isJustDeactivated(huReservationRecord); if (reservationIsGone) { final boolean isReserved = false; updateVhuIsReservedFlag(huReservationRecord, isReserved); } } private void updateVhuIsReservedFlag( @NonNull final I_M_HU_Reservation huReservationRecord, final boolean isReserved) { final HuId vhuId = HuId.ofRepoId(huReservationRecord.getVHU_ID()); Services.get(IHandlingUnitsDAO.class).setReservedByHUIds(ImmutableSet.of(vhuId), isReserved); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\reservation\interceptor\M_HU_Reservation.java
1
请完成以下Java代码
public class GuessGame extends BroadcastingGuessGame { public static final int SECOND = 1000; private static final Logger log = Logger.getLogger(GuessGame.class.getCanonicalName()); private final List<Player> players; private volatile boolean isFinished = false; private volatile boolean isPaused = false; public GuessGame(List<Player> players) { this.players = players; log.setLevel(Level.WARNING); } public void start() { int randomNumber = generateRandomNumber(); while (!isFinished) { waitASecond(); while (!isPaused && !isFinished) { log.info("Current random number is " + randomNumber); waitASecond(); for (Player player : players) { int guess = player.guessNumber(); if (guess == randomNumber) { log.info("Players " + player.getName() + " " + guess + " is correct"); player.incrementScore(); notifyAboutWinner(player); randomNumber = generateRandomNumber(); break; } log.info("Player " + player.getName() + " guessed incorrectly with " + guess); } log.info("\n"); } if (isPaused) { log.info("Game is paused"); } if (isFinished) { log.info("Game is finished"); } } }
@Override public void finishGame() { isFinished = true; } @Override public void pauseGame() { isPaused = true; } @Override public void unpauseGame() { isPaused = false; } public List<Player> getPlayers() { return players; } private void waitASecond() { try { Thread.sleep(SECOND); } catch (InterruptedException e) { e.printStackTrace(); } } }
repos\tutorials-master\core-java-modules\core-java-perf-2\src\main\java\com\baeldung\jmxterm\GuessGame.java
1
请在Spring Boot框架中完成以下Java代码
public void setCancelRequestState(String cancelRequestState) { this.cancelRequestState = cancelRequestState; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } CancelRequest cancelRequest = (CancelRequest)o; return Objects.equals(this.cancelCompletedDate, cancelRequest.cancelCompletedDate) && Objects.equals(this.cancelInitiator, cancelRequest.cancelInitiator) && Objects.equals(this.cancelReason, cancelRequest.cancelReason) && Objects.equals(this.cancelRequestedDate, cancelRequest.cancelRequestedDate) && Objects.equals(this.cancelRequestId, cancelRequest.cancelRequestId) && Objects.equals(this.cancelRequestState, cancelRequest.cancelRequestState); } @Override public int hashCode() { return Objects.hash(cancelCompletedDate, cancelInitiator, cancelReason, cancelRequestedDate, cancelRequestId, cancelRequestState); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class CancelRequest {\n");
sb.append(" cancelCompletedDate: ").append(toIndentedString(cancelCompletedDate)).append("\n"); sb.append(" cancelInitiator: ").append(toIndentedString(cancelInitiator)).append("\n"); sb.append(" cancelReason: ").append(toIndentedString(cancelReason)).append("\n"); sb.append(" cancelRequestedDate: ").append(toIndentedString(cancelRequestedDate)).append("\n"); sb.append(" cancelRequestId: ").append(toIndentedString(cancelRequestId)).append("\n"); sb.append(" cancelRequestState: ").append(toIndentedString(cancelRequestState)).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\CancelRequest.java
2
请完成以下Java代码
public URL checkValidFileLocation(String url) throws MalformedURLException { if (url == null || url.isEmpty()) { return null; } Pattern filePattern = Pattern.compile("^(/|[A-z]://?|[A-z]:\\\\).*[/|\\\\]bpm-platform\\.xml$", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE); Matcher fileMatcher = filePattern.matcher(url); if (fileMatcher.matches()) { File configurationLocation = new File(url); if (configurationLocation.isAbsolute() && configurationLocation.exists()) { return configurationLocation.toURI().toURL(); } } return null; } public URL lookupBpmPlatformXmlLocationFromJndi() { String jndi = "java:comp/env/" + BPM_PLATFORM_XML_LOCATION; try { String bpmPlatformXmlLocation = InitialContext.doLookup(jndi); URL fileLocation = checkValidBpmPlatformXmlResourceLocation(bpmPlatformXmlLocation); if (fileLocation != null) { LOG.foundConfigJndi(jndi, fileLocation.toString()); } return fileLocation; } catch (NamingException e) { LOG.debugExceptionWhileGettingConfigFromJndi(jndi, e); return null; } } public URL lookupBpmPlatformXmlLocationFromEnvironmentVariable() { String bpmPlatformXmlLocation = System.getenv(BPM_PLATFORM_XML_ENVIRONMENT_VARIABLE); String logStatement = "environment variable [" + BPM_PLATFORM_XML_ENVIRONMENT_VARIABLE + "]"; if (bpmPlatformXmlLocation == null) { bpmPlatformXmlLocation = System.getProperty(BPM_PLATFORM_XML_SYSTEM_PROPERTY); logStatement = "system property [" + BPM_PLATFORM_XML_SYSTEM_PROPERTY + "]"; } URL fileLocation = checkValidBpmPlatformXmlResourceLocation(bpmPlatformXmlLocation); if (fileLocation != null) { LOG.foundConfigAtLocation(logStatement, fileLocation.toString()); } return fileLocation; } public URL lookupBpmPlatformXmlFromClassPath(String resourceLocation) { URL fileLocation = ClassLoaderUtil.getClassloader(getClass()).getResource(resourceLocation);
if (fileLocation != null) { LOG.foundConfigAtLocation(resourceLocation, fileLocation.toString()); } return fileLocation; } public URL lookupBpmPlatformXmlFromClassPath() { return lookupBpmPlatformXmlFromClassPath(BPM_PLATFORM_XML_RESOURCE_LOCATION); } public URL lookupBpmPlatformXml() { URL fileLocation = lookupBpmPlatformXmlLocationFromJndi(); if (fileLocation == null) { fileLocation = lookupBpmPlatformXmlLocationFromEnvironmentVariable(); } if (fileLocation == null) { fileLocation = lookupBpmPlatformXmlFromClassPath(); } return fileLocation; } public abstract URL getBpmPlatformXmlStream(DeploymentOperation operationContext); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\deployment\AbstractParseBpmPlatformXmlStep.java
1
请在Spring Boot框架中完成以下Java代码
public class ProjectValueSequenceProvider implements ValueSequenceInfoProvider { private final IDocumentSequenceDAO documentSequenceDAO = Services.get(IDocumentSequenceDAO.class); private final ProjectTypeRepository projectTypeRepository; public ProjectValueSequenceProvider( @NonNull final ProjectTypeRepository projectTypeRepository) { this.projectTypeRepository = projectTypeRepository; } @Override public ProviderResult computeValueInfo(@NonNull final Object modelRecord) { if (!isInstanceOf(modelRecord, I_C_Project.class)) { return ProviderResult.EMPTY; } final I_C_Project projectRecord = create(modelRecord, I_C_Project.class); final ProjectTypeId projectTypeId = ProjectTypeId.ofRepoIdOrNull(projectRecord.getC_ProjectType_ID()); if (projectTypeId == null) {
return ProviderResult.EMPTY; } final ProjectType projectType = projectTypeRepository.getById(projectTypeId); final DocSequenceId docSequenceId = projectType.getDocSequenceId(); if (docSequenceId == null) { return ProviderResult.EMPTY; } final DocumentSequenceInfo documentSequenceInfo = documentSequenceDAO.retriveDocumentSequenceInfo(docSequenceId); return ProviderResult.of(documentSequenceInfo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\project\sequence\ProjectValueSequenceProvider.java
2
请完成以下Java代码
public void endElement (String uri, String localName, String qName) throws SAXException { if (qName.equals(PrintData.XML_TAG)) { pop(); } else if (qName.equals(PrintDataElement.XML_TAG)) { m_curPD.addNode(new PrintDataElement(m_curPDEname, m_curPDEvalue.toString(),0, null)); } } // endElement /*************************************************************************/ /** Stack */ private ArrayList<PrintData> m_stack = new ArrayList<PrintData>(); /** * Push new PD on Stack and set m_cutPD * @param newPD new PD */ private void push (PrintData newPD) { // add m_stack.add(newPD); m_curPD = newPD;
} // push /** * Pop last PD from Stack and set m_cutPD */ private void pop () { // remove last if (m_stack.size() > 0) m_stack.remove(m_stack.size()-1); // get previous if (m_stack.size() > 0) m_curPD = (PrintData)m_stack.get(m_stack.size()-1); } // pop } // PrintDataHandler
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataHandler.java
1
请完成以下Java代码
public String getBusinessKey() { return subscriptionConfiguration.getBusinessKey(); } @Override public String getProcessDefinitionId() { return subscriptionConfiguration.getProcessDefinitionId(); } @Override public List<String> getProcessDefinitionIdIn() { return subscriptionConfiguration.getProcessDefinitionIdIn(); } @Override public String getProcessDefinitionKey() { return subscriptionConfiguration.getProcessDefinitionKey(); } @Override public List<String> getProcessDefinitionKeyIn() { return subscriptionConfiguration.getProcessDefinitionKeyIn(); } @Override public String getProcessDefinitionVersionTag() { return subscriptionConfiguration.getProcessDefinitionVersionTag(); } @Override public Map<String, Object> getProcessVariables() { return subscriptionConfiguration.getProcessVariables(); }
@Override public boolean isWithoutTenantId() { return subscriptionConfiguration.getWithoutTenantId(); } @Override public List<String> getTenantIdIn() { return subscriptionConfiguration.getTenantIdIn(); } @Override public boolean isIncludeExtensionProperties() { return subscriptionConfiguration.getIncludeExtensionProperties(); } protected String[] toArray(List<String> list) { return list.toArray(new String[0]); } @Override public void afterPropertiesSet() throws Exception { } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter-client\spring\src\main\java\org\camunda\bpm\client\spring\impl\subscription\SpringTopicSubscriptionImpl.java
1
请完成以下Java代码
public int compare(Map.Entry<Integer, Double> o1, Map.Entry<Integer, Double> o2) { return o1.getValue().compareTo(o2.getValue()); } }); for (Map.Entry<Integer, Double> entry : selectedFeatures.entrySet()) { maxHeap.add(entry); } selectedFeatures.clear(); for (Map.Entry<Integer, Double> entry : maxHeap) { selectedFeatures.put(entry.getKey(), entry.getValue()); } } return selectedFeatures; } /** * 获取卡方临界值 * * @return */ public double getChisquareCriticalValue() { return chisquareCriticalValue; } /** * 设置卡方临界值 * * @param chisquareCriticalValue */ public void setChisquareCriticalValue(double chisquareCriticalValue)
{ this.chisquareCriticalValue = chisquareCriticalValue; } public ChiSquareFeatureExtractor setALevel(double aLevel) { chisquareCriticalValue = ContinuousDistributions.ChisquareInverseCdf(aLevel, 1); return this; } public double getALevel() { return ContinuousDistributions.ChisquareCdf(chisquareCriticalValue, 1); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\classification\features\ChiSquareFeatureExtractor.java
1
请完成以下Java代码
public void setEdiEnabledForNewOrder(@NonNull final I_C_Order order) { final boolean ediEnabledByInputDataSource; if (order.getAD_InputDataSource_ID() <= 0) { ediEnabledByInputDataSource = false; } else { ediEnabledByInputDataSource = inputDataSourceBL.isEDIInputDataSource(order.getAD_InputDataSource_ID()); } if (ediEnabledByInputDataSource) { order.setIsEdiEnabled(true); return; // no need to look further } final BPartnerId buyerBPartnerId = orderBL.getEffectiveBillPartnerId(order); if (buyerBPartnerId != null) { final I_C_BPartner buyer = InterfaceWrapperHelper.load(buyerBPartnerId, de.metas.edi.model.I_C_BPartner.class); if (buyer.isEdiInvoicRecipient()) { order.setIsEdiEnabled(true); return; } } final BPartnerId recipientBPartnerId = orderBL.getEffectiveDropshipPartnerId(order); if (recipientBPartnerId != null) { final I_C_BPartner recipient = InterfaceWrapperHelper.load(recipientBPartnerId, de.metas.edi.model.I_C_BPartner.class); if (recipient.isEdiDesadvRecipient()) { order.setIsEdiEnabled(true); return; } } order.setIsEdiEnabled(false); } /** * task http://dewiki908/mediawiki/index.php/08926_EDI-Ausschalten_f%C3%BCr_bestimmte_Belege_%28109751792947%29 */ @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_C_Order.COLUMNNAME_AD_InputDataSource_ID) public void updateEdiEnabled(final I_C_Order order) { final int orderInputDataSourceId = order.getAD_InputDataSource_ID(); if (orderInputDataSourceId <= 0) { // nothing to do return; } final boolean isEdiEnabled = inputDataSourceBL.isEDIInputDataSource(orderInputDataSourceId); if (isEdiEnabled) {
order.setIsEdiEnabled(true); } } @ModelChange(timings = ModelValidator.TYPE_BEFORE_CHANGE, ifColumnsChanged = I_C_Order.COLUMNNAME_C_BPartner_ID) public void onPartnerChange(final I_C_Order order) { final I_C_BPartner partner = InterfaceWrapperHelper.create(order.getC_BPartner(), de.metas.edi.model.I_C_BPartner.class); if (partner == null) { // nothing to do return; } final boolean isEdiRecipient = partner.isEdiDesadvRecipient() || partner.isEdiInvoicRecipient(); // in case the partner was changed and the new one is not an edi recipient, the order will not be edi enabled // If the new bp is edi recipient, we leave it to the user to set the flag or not if (!isEdiRecipient) { order.setIsEdiEnabled(false); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java\de\metas\edi\model\validator\C_Order.java
1
请完成以下Java代码
public class StreamSumCalculatorWithObject { public static Integer getSumUsingCustomizedAccumulator(List<Item> items) { return items.stream() .map(x -> x.getPrice()) .reduce(0, ArithmeticUtils::add); } public static Integer getSumUsingJavaAccumulator(List<Item> items) { return items.stream() .map(x -> x.getPrice()) .reduce(0, Integer::sum); } public static Integer getSumUsingReduce(List<Item> items) { return items.stream()
.map(item -> item.getPrice()) .reduce(0, (a, b) -> a + b); } public static Integer getSumUsingCollect(List<Item> items) { return items.stream() .map(x -> x.getPrice()) .collect(Collectors.summingInt(Integer::intValue)); } public static Integer getSumUsingSum(List<Item> items) { return items.stream() .mapToInt(x -> x.getPrice()) .sum(); } }
repos\tutorials-master\core-java-modules\core-java-streams\src\main\java\com\baeldung\stream\sum\StreamSumCalculatorWithObject.java
1
请在Spring Boot框架中完成以下Java代码
public Collection<ConfigAttribute> getAllConfigAttributes() { //初始化 所有资源 对应的角色 loadResourceDefine(); return null; } @Override public boolean supports(Class<?> aClass) { return true; } /** * 初始化 所有资源 对应的角色 */ public void loadResourceDefine() { map = new HashMap<>(16); //权限资源 和 角色对应的表 也就是 角色权限 中间表 List<RolePermisson> rolePermissons = permissionMapper.getRolePermissions(); //某个资源 可以被哪些角色访问 for (RolePermisson rolePermisson : rolePermissons) {
String url = rolePermisson.getUrl(); String roleName = rolePermisson.getRoleName(); ConfigAttribute role = new SecurityConfig(roleName); if(map.containsKey(url)){ map.get(url).add(role); }else{ List<ConfigAttribute> list = new ArrayList<>(); list.add( role ); map.put( url , list ); } } } }
repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\config\MyInvocationSecurityMetadataSourceService.java
2
请完成以下Java代码
public void setTargetFlowElement(FlowElement targetFlowElement) { this.targetFlowElement = targetFlowElement; } public List<Integer> getWaypoints() { return waypoints; } public void setWaypoints(List<Integer> waypoints) { this.waypoints = waypoints; } public String toString() { return sourceRef + " --> " + targetRef; }
public SequenceFlow clone() { SequenceFlow clone = new SequenceFlow(); clone.setValues(this); return clone; } public void setValues(SequenceFlow otherFlow) { super.setValues(otherFlow); setConditionExpression(otherFlow.getConditionExpression()); setSourceRef(otherFlow.getSourceRef()); setTargetRef(otherFlow.getTargetRef()); setSkipExpression(otherFlow.getSkipExpression()); } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\SequenceFlow.java
1
请完成以下Java代码
public void setC_BPartner_ID (final int C_BPartner_ID) { if (C_BPartner_ID < 1) set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, null); else set_ValueNoCheck (COLUMNNAME_C_BPartner_ID, C_BPartner_ID); } @Override public int getC_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_C_BPartner_ID); } @Override public void setGLN (final @Nullable java.lang.String GLN) { set_Value (COLUMNNAME_GLN, GLN); } @Override public java.lang.String getGLN() { return get_ValueAsString(COLUMNNAME_GLN); } @Override public void setLookup_Label (final @Nullable java.lang.String Lookup_Label) { set_ValueNoCheck (COLUMNNAME_Lookup_Label, Lookup_Label); } @Override public java.lang.String getLookup_Label()
{ return get_ValueAsString(COLUMNNAME_Lookup_Label); } @Override public void setStoreGLN (final @Nullable java.lang.String StoreGLN) { set_Value (COLUMNNAME_StoreGLN, StoreGLN); } @Override public java.lang.String getStoreGLN() { return get_ValueAsString(COLUMNNAME_StoreGLN); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_C_BPartner_Lookup_BPL_GLN_v.java
1
请完成以下Java代码
public class TelecomAddressType { @XmlElement(required = true) protected List<String> phone; protected List<String> fax; /** * Gets the value of the phone property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the phone property. * * <p> * For example, to add a new item, do as follows: * <pre> * getPhone().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getPhone() { if (phone == null) { phone = new ArrayList<String>(); } return this.phone; } /** * Gets the value of the fax property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the
* returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the fax property. * * <p> * For example, to add a new item, do as follows: * <pre> * getFax().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getFax() { if (fax == null) { fax = new ArrayList<String>(); } return this.fax; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_response\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\response\TelecomAddressType.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set C_DocBaseType_Counter. @param C_DocBaseType_Counter_ID C_DocBaseType_Counter */ @Override public void setC_DocBaseType_Counter_ID (int C_DocBaseType_Counter_ID) { if (C_DocBaseType_Counter_ID < 1) set_ValueNoCheck (COLUMNNAME_C_DocBaseType_Counter_ID, null); else set_ValueNoCheck (COLUMNNAME_C_DocBaseType_Counter_ID, Integer.valueOf(C_DocBaseType_Counter_ID)); } /** Get C_DocBaseType_Counter. @return C_DocBaseType_Counter */ @Override public int getC_DocBaseType_Counter_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocBaseType_Counter_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Counter_DocBaseType. @param Counter_DocBaseType Counter_DocBaseType */ @Override public void setCounter_DocBaseType (java.lang.String Counter_DocBaseType) { set_Value (COLUMNNAME_Counter_DocBaseType, Counter_DocBaseType); } /** Get Counter_DocBaseType. @return Counter_DocBaseType */ @Override public java.lang.String getCounter_DocBaseType () { return (java.lang.String)get_Value(COLUMNNAME_Counter_DocBaseType); }
/** Set Document BaseType. @param DocBaseType Logical type of document */ @Override public void setDocBaseType (java.lang.String DocBaseType) { set_Value (COLUMNNAME_DocBaseType, DocBaseType); } /** Get Document BaseType. @return Logical type of document */ @Override public java.lang.String getDocBaseType () { return (java.lang.String)get_Value(COLUMNNAME_DocBaseType); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_DocBaseType_Counter.java
1
请完成以下Java代码
public static String reversalMessage(String fromUserName, String toUserName, String Content) { TextMessage text = new TextMessage(); text.setToUserName(fromUserName); text.setFromUserName(toUserName); text.setContent(Content); text.setCreateTime(new Date().getTime()); text.setMsgType(ReqType.TEXT); return messageToxml(text); } /** * 封装voice消息对象 * * @param fromUserName * @param toUserName * @param mediaId * @return */ public static String reversalVoiceMessage(String fromUserName, String toUserName, String mediaId) { VoiceMessage voiceMessage = new VoiceMessage(); voiceMessage.setToUserName(fromUserName); voiceMessage.setFromUserName(toUserName); voiceMessage.setVoice(new Voice(mediaId)); voiceMessage.setCreateTime(new Date().getTime()); voiceMessage.setMsgType(ReqType.VOICE); return messageToxml(voiceMessage); } /** * 判断是否是QQ表情
* * @param content * @return */ public static boolean isQqFace(String content) { boolean result = false; // 判断QQ表情的正则表达式 Matcher m = p.matcher(content); if (m.matches()) { result = true; } return result; } }
repos\spring-boot-quick-master\quick-wx-public\src\main\java\com\wx\pn\api\utils\MessageUtil.java
1
请完成以下Java代码
public Optional<DocTax> getByTaxId(@Nullable final TaxId taxId) { if (taxId == null) { return Optional.empty(); } return Optional.ofNullable(taxesByTaxId.get(taxId)); } public void mapEach(@NonNull final UnaryOperator<DocTax> mapper) { final ImmutableSet<TaxId> taxIds = ImmutableSet.copyOf(taxesByTaxId.keySet()); // IMPORTANT: take a snapshot for (final TaxId taxId : taxIds) {
taxesByTaxId.compute(taxId, (k, docTax) -> mapper.apply(docTax)); } } public void add(@NonNull final DocTax docTax) { final TaxId taxId = docTax.getTaxId(); final DocTax existingDocTax = taxesByTaxId.get(taxId); if (existingDocTax != null) { throw new AdempiereException("Cannot add " + docTax + " since there is already a tax: " + existingDocTax); } taxesByTaxId.put(taxId, docTax); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\DocTaxesList.java
1
请完成以下Java代码
public class StartProcessInstanceAsyncCmd extends StartProcessInstanceCmd { public StartProcessInstanceAsyncCmd(ProcessInstanceBuilderImpl processInstanceBuilder) { super(processInstanceBuilder); } @Override public ProcessInstance execute(CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); ProcessDefinition processDefinition = getProcessDefinition(processEngineConfiguration, commandContext); processInstanceHelper = processEngineConfiguration.getProcessInstanceHelper(); ExecutionEntity processInstance = (ExecutionEntity) processInstanceHelper.createProcessInstance(processDefinition, businessKey, businessStatus, processInstanceName, startEventId, overrideDefinitionTenantId, predefinedProcessInstanceId, variables, transientVariables, callbackId, callbackType, referenceId, referenceType, ownerId, assigneeId, stageInstanceId, false); ExecutionEntity execution = processInstance.getExecutions().get(0); Process process = ProcessDefinitionUtil.getProcess(processInstance.getProcessDefinitionId()); processInstanceHelper.processAvailableEventSubProcesses(processInstance, process, commandContext); FlowableEventDispatcher eventDispatcher = processEngineConfiguration.getEventDispatcher(); if (eventDispatcher != null && eventDispatcher.isEnabled()) { eventDispatcher.dispatchEvent(FlowableEventBuilder.createProcessStartedEvent(execution, variables, false), processEngineConfiguration.getEngineCfgKey()); } executeAsynchronous(execution, process, commandContext);
return processInstance; } protected void executeAsynchronous(ExecutionEntity execution, Process process, CommandContext commandContext) { ProcessEngineConfigurationImpl processEngineConfiguration = CommandContextUtil.getProcessEngineConfiguration(commandContext); JobService jobService = processEngineConfiguration.getJobServiceConfiguration().getJobService(); JobEntity job = JobUtil.createJob(execution, process, AsyncContinuationJobHandler.TYPE, processEngineConfiguration); job.setElementName(process.getName()); jobService.createAsyncJob(job, false); jobService.scheduleAsyncJob(job); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\cmd\StartProcessInstanceAsyncCmd.java
1
请在Spring Boot框架中完成以下Java代码
public CommonResult create(@RequestParam String name) { int count = productAttributeCategoryService.create(name); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("修改商品属性分类") @RequestMapping(value = "/update/{id}", method = RequestMethod.POST) @ResponseBody public CommonResult update(@PathVariable Long id, @RequestParam String name) { int count = productAttributeCategoryService.update(id, name); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } } @ApiOperation("删除单个商品属性分类") @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult delete(@PathVariable Long id) { int count = productAttributeCategoryService.delete(id); if (count > 0) { return CommonResult.success(count); } else { return CommonResult.failed(); } }
@ApiOperation("获取单个商品属性分类信息") @RequestMapping(value = "/{id}", method = RequestMethod.GET) @ResponseBody public CommonResult<PmsProductAttributeCategory> getItem(@PathVariable Long id) { PmsProductAttributeCategory productAttributeCategory = productAttributeCategoryService.getItem(id); return CommonResult.success(productAttributeCategory); } @ApiOperation("分页获取所有商品属性分类") @RequestMapping(value = "/list", method = RequestMethod.GET) @ResponseBody public CommonResult<CommonPage<PmsProductAttributeCategory>> getList(@RequestParam(defaultValue = "5") Integer pageSize, @RequestParam(defaultValue = "1") Integer pageNum) { List<PmsProductAttributeCategory> productAttributeCategoryList = productAttributeCategoryService.getList(pageSize, pageNum); return CommonResult.success(CommonPage.restPage(productAttributeCategoryList)); } @ApiOperation("获取所有商品属性分类及其下属性") @RequestMapping(value = "/list/withAttr", method = RequestMethod.GET) @ResponseBody public CommonResult<List<PmsProductAttributeCategoryItem>> getListWithAttr() { List<PmsProductAttributeCategoryItem> productAttributeCategoryResultList = productAttributeCategoryService.getListWithAttr(); return CommonResult.success(productAttributeCategoryResultList); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\controller\PmsProductAttributeCategoryController.java
2
请在Spring Boot框架中完成以下Java代码
public class ExternalReferenceRestController { private final ExternalReferenceRestControllerService externalReferenceRestControllerService; public ExternalReferenceRestController(@NonNull final ExternalReferenceRestControllerService externalReferenceRestControllerService) { this.externalReferenceRestControllerService = externalReferenceRestControllerService; } // we actually ask for info and don't change anything in metasfresh...that's why would have a GET...despite a GET shouldn't have a request body @PutMapping("{orgCode}") public JsonExternalReferenceLookupResponse lookup( @ApiParam(required = true, value = "`AD_Org.Value` of the external references we are looking for") // @PathVariable("orgCode") // @NonNull final String orgCode, @RequestBody @NonNull final JsonExternalReferenceLookupRequest request) { return externalReferenceRestControllerService.performLookup(orgCode, request); } // note that we are not going to update references because they are not supposed to change @PostMapping("{orgCode}") public ResponseEntity<?> insert( @ApiParam(required = true, value = "`AD_Org.Value` of the external references we are inserting") // @PathVariable("orgCode") // @NonNull final String orgCode, @RequestBody @NonNull final JsonExternalReferenceCreateRequest request) { externalReferenceRestControllerService.performInsert(orgCode, request);
return ResponseEntity.ok().build(); } @PutMapping("/upsert/{orgCode}") public ResponseEntity<?> upsert( @ApiParam(required = true, value = "`AD_Org.Value` of the external references we are upserting") // @PathVariable("orgCode") // @Nullable final String orgCode, @RequestBody @NonNull final JsonRequestExternalReferenceUpsert request) { externalReferenceRestControllerService.performUpsert(request, orgCode); return ResponseEntity.ok().build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalreference\src\main\java\de\metas\externalreference\rest\v1\ExternalReferenceRestController.java
2
请完成以下Java代码
public class GatewayToStringStyler extends DefaultToStringStyler { private static final GatewayToStringStyler FILTER_INSTANCE = new GatewayToStringStyler(GatewayFilterFactory.class, NameUtils::normalizeFilterFactoryName); private final Function<Class, String> classNameFormatter; private final Class instanceClass; public static ToStringCreator filterToStringCreator(Object obj) { return new ToStringCreator(obj, FILTER_INSTANCE); } public GatewayToStringStyler(Class instanceClass, Function<Class, String> classNameFormatter) { super(new DefaultValueStyler()); this.classNameFormatter = classNameFormatter; this.instanceClass = instanceClass; }
@Override public void styleStart(StringBuilder buffer, Object obj) { if (!obj.getClass().isArray()) { String shortName; if (instanceClass.isInstance(obj)) { shortName = classNameFormatter.apply(obj.getClass()); } else { shortName = ClassUtils.getShortName(obj.getClass()); } buffer.append('[').append(shortName); } else { buffer.append('['); styleValue(buffer, obj); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\support\GatewayToStringStyler.java
1