instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public @Nullable String getRemoteIpHeader() { return this.remoteIpHeader; } public void setRemoteIpHeader(@Nullable String remoteIpHeader) { this.remoteIpHeader = remoteIpHeader; } public @Nullable String getTrustedProxies() { return this.trustedProxies; } public void setTrustedProxies(@Nullable String trustedProxies) { this.trustedProxies = trustedProxies; } } /** * When to use APR. */ public enum UseApr { /**
* Always use APR and fail if it's not available. */ ALWAYS, /** * Use APR if it is available. */ WHEN_AVAILABLE, /** * Never use APR. */ NEVER } }
repos\spring-boot-4.0.1\module\spring-boot-tomcat\src\main\java\org\springframework\boot\tomcat\autoconfigure\TomcatServerProperties.java
2
请完成以下Java代码
protected String determineTargetUrl(final Authentication authentication) { Map<String, String> roleTargetUrlMap = new HashMap<>(); roleTargetUrlMap.put("ROLE_USER", "/homepage.html"); roleTargetUrlMap.put("ROLE_ADMIN", "/console.html"); final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for (final GrantedAuthority grantedAuthority : authorities) { String authorityName = grantedAuthority.getAuthority(); if(roleTargetUrlMap.containsKey(authorityName)) { return roleTargetUrlMap.get(authorityName); } } throw new IllegalStateException(); }
/** * Removes temporary authentication-related data which may have been stored in the session * during the authentication process. */ protected final void clearAuthenticationAttributes(final HttpServletRequest request) { final HttpSession session = request.getSession(false); if (session == null) { return; } session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); } }
repos\tutorials-master\spring-security-modules\spring-security-web-mvc-custom\src\main\java\com\baeldung\security\MySimpleUrlAuthenticationSuccessHandler.java
1
请完成以下Java代码
private static String resolvePlaceholder(Properties properties, String text, String placeholderName) { String propertyValue = getProperty(placeholderName, null, text); if (propertyValue != null) { return propertyValue; } return (properties != null) ? properties.getProperty(placeholderName) : null; } static String getProperty(String key) { return getProperty(key, null, ""); } private static String getProperty(String key, String defaultValue, String text) { try { String value = System.getProperty(key); value = (value != null) ? value : System.getenv(key); value = (value != null) ? value : System.getenv(key.replace('.', '_')); value = (value != null) ? value : System.getenv(key.toUpperCase(Locale.ENGLISH).replace('.', '_')); return (value != null) ? value : defaultValue; } catch (Throwable ex) { System.err.println("Could not resolve key '" + key + "' in '" + text + "' as system property or in environment: " + ex); return defaultValue; } } private static int findPlaceholderEndIndex(CharSequence buf, int startIndex) { int index = startIndex + PLACEHOLDER_PREFIX.length(); int withinNestedPlaceholder = 0; while (index < buf.length()) { if (substringMatch(buf, index, PLACEHOLDER_SUFFIX)) { if (withinNestedPlaceholder > 0) { withinNestedPlaceholder--; index = index + PLACEHOLDER_SUFFIX.length();
} else { return index; } } else if (substringMatch(buf, index, SIMPLE_PREFIX)) { withinNestedPlaceholder++; index = index + SIMPLE_PREFIX.length(); } else { index++; } } return -1; } private static boolean substringMatch(CharSequence str, int index, CharSequence substring) { for (int j = 0; j < substring.length(); j++) { int i = index + j; if (i >= str.length() || str.charAt(i) != substring.charAt(j)) { return false; } } return true; } }
repos\spring-boot-4.0.1\loader\spring-boot-loader\src\main\java\org\springframework\boot\loader\launch\SystemPropertyUtils.java
1
请在Spring Boot框架中完成以下Java代码
protected boolean hasExpired(long lastRecordedTime) { return (getCurrentTimeMillis() - sessionInactivityTimeout) > lastRecordedTime; } @Override protected void onStateExpiry(UUID sessionId, TransportProtos.SessionInfoProto sessionInfo) { log.debug("Session with id: [{}] has expired due to last activity time.", sessionId); SessionMetaData expiredSession = sessions.remove(sessionId); if (expiredSession != null) { deregisterSession(sessionInfo); process(sessionInfo, SESSION_EVENT_MSG_CLOSED, null); expiredSession.getListener().onRemoteSessionCloseCommand(sessionId, SESSION_EXPIRED_NOTIFICATION_PROTO); } } @Override protected void reportActivity(UUID sessionId, TransportProtos.SessionInfoProto currentSessionInfo, long timeToReport, ActivityReportCallback<UUID> callback) { log.debug("Reporting activity state for session with id: [{}]. Time to report: [{}].", sessionId, timeToReport); SessionMetaData session = sessions.get(sessionId); TransportProtos.SubscriptionInfoProto subscriptionInfo = TransportProtos.SubscriptionInfoProto.newBuilder() .setAttributeSubscription(session != null && session.isSubscribedToAttributes()) .setRpcSubscription(session != null && session.isSubscribedToRPC()) .setLastActivityTime(timeToReport) .build();
TransportProtos.SessionInfoProto sessionInfo = session != null ? session.getSessionInfo() : currentSessionInfo; process(sessionInfo, subscriptionInfo, new TransportServiceCallback<>() { @Override public void onSuccess(Void msgAcknowledged) { callback.onSuccess(sessionId, timeToReport); } @Override public void onError(Throwable e) { callback.onFailure(sessionId, e); } }); } protected long getCurrentTimeMillis() { return System.currentTimeMillis(); } }
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\service\TransportActivityManager.java
2
请完成以下Java代码
public class Order extends RepresentationModel<Order> { private String orderId; private double price; private int quantity; public Order() { super(); } public Order(final String orderId, final double price, final int quantity) { super(); this.orderId = orderId; this.price = price; this.quantity = quantity; } public String getOrderId() { return orderId; } public void setOrderId(final String orderId) { this.orderId = orderId; } public double getPrice() { return price;
} public void setPrice(final double price) { this.price = price; } public int getQuantity() { return quantity; } public void setQuantity(final int quantity) { this.quantity = quantity; } @Override public String toString() { return "Order [orderId=" + orderId + ", price=" + price + ", quantity=" + quantity + "]"; } }
repos\tutorials-master\spring-web-modules\spring-boot-rest\src\main\java\com\baeldung\persistence\model\Order.java
1
请在Spring Boot框架中完成以下Java代码
static final class PropertiesCouchbaseConnectionDetails implements CouchbaseConnectionDetails { private final CouchbaseProperties properties; private final @Nullable SslBundles sslBundles; PropertiesCouchbaseConnectionDetails(CouchbaseProperties properties, @Nullable SslBundles sslBundles) { this.properties = properties; this.sslBundles = sslBundles; } @Override public String getConnectionString() { String connectionString = this.properties.getConnectionString(); Assert.state(connectionString != null, "'connectionString' must not be null"); return connectionString; } @Override public @Nullable String getUsername() { return this.properties.getUsername(); }
@Override public @Nullable String getPassword() { return this.properties.getPassword(); } @Override public @Nullable SslBundle getSslBundle() { Ssl ssl = this.properties.getEnv().getSsl(); if (!ssl.getEnabled()) { return null; } if (StringUtils.hasLength(ssl.getBundle())) { Assert.notNull(this.sslBundles, "SSL bundle name has been set but no SSL bundles found in context"); return this.sslBundles.getBundle(ssl.getBundle()); } return SslBundle.systemDefault(); } } }
repos\spring-boot-4.0.1\module\spring-boot-couchbase\src\main\java\org\springframework\boot\couchbase\autoconfigure\CouchbaseAutoConfiguration.java
2
请完成以下Java代码
public EdgeNodeDescriptor getEdgeNodeDescriptor() { return edgeNodeDescriptor; } /** * Returns the ID of the logical grouping of Edge of Network (EoN) Nodes and devices. * * @return the group ID */ public String getGroupId() { return groupId; } /** * Returns the ID of the Edge of Network (EoN) Node. * * @return the edge node ID */ public String getEdgeNodeId() { return edgeNodeId; } /** * Returns the ID of the device. * * @return the device ID */ public String getDeviceId() { return deviceId; } public void updateDeviceIdPlus(String deviceIdNew) { this.deviceId = this.deviceId.equals("+") ? deviceIdNew : this.deviceId; } /** * Returns the Host Application ID if this is a Host topic * * @return the Host Application ID */ public String getHostApplicationId() { return hostApplicationId; } /** * Returns the message type. * * @return the message type */ public SparkplugMessageType getType() { return type; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (hostApplicationId == null) { sb.append(getNamespace()).append("/").append(getGroupId()).append("/").append(getType()).append("/") .append(getEdgeNodeId());
if (getDeviceId() != null) { sb.append("/").append(getDeviceId()); } } else { sb.append(getNamespace()).append("/").append(getType()).append("/").append(hostApplicationId); } return sb.toString(); } /** * @param type the type to check * @return true if this topic's type matches the passes in type, false otherwise */ public boolean isType(SparkplugMessageType type) { return this.type != null && this.type.equals(type); } public boolean isNode() { return this.deviceId == null; } public String getNodeDeviceName() { return isNode() ? edgeNodeId : deviceId; } public static boolean isValidIdElementToUTF8(String deviceIdElement) { if (deviceIdElement == null) { return false; } String regex = "^(?!.*//)[^+#]*$"; return deviceIdElement.matches(regex); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\SparkplugTopic.java
1
请完成以下Java代码
public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Kommentar/Hilfe. @param Help Comment or Hint */ @Override public void setHelp (java.lang.String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Kommentar/Hilfe. @return Comment or Hint */ @Override public java.lang.String getHelp () { return (java.lang.String)get_Value(COLUMNNAME_Help); } /** Set Zusammenfassungseintrag. @param IsSummary This is a summary entity */ @Override public void setIsSummary (boolean IsSummary) { set_Value (COLUMNNAME_IsSummary, Boolean.valueOf(IsSummary)); } /** Get Zusammenfassungseintrag. @return This is a summary entity */ @Override public boolean isSummary () { Object oo = get_Value(COLUMNNAME_IsSummary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } @Override public org.compiere.model.I_C_Activity getParent_Activity() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_Parent_Activity_ID, org.compiere.model.I_C_Activity.class); } @Override public void setParent_Activity(org.compiere.model.I_C_Activity Parent_Activity) { set_ValueFromPO(COLUMNNAME_Parent_Activity_ID, org.compiere.model.I_C_Activity.class, Parent_Activity); } /** Set Hauptkostenstelle. @param Parent_Activity_ID Hauptkostenstelle */
@Override public void setParent_Activity_ID (int Parent_Activity_ID) { if (Parent_Activity_ID < 1) set_Value (COLUMNNAME_Parent_Activity_ID, null); else set_Value (COLUMNNAME_Parent_Activity_ID, Integer.valueOf(Parent_Activity_ID)); } /** Get Hauptkostenstelle. @return Hauptkostenstelle */ @Override public int getParent_Activity_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Parent_Activity_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Suchschlüssel. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Search key for the record in the format required - must be unique */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Activity.java
1
请完成以下Java代码
public String getClientId() { return this.clientId; } /** * Return the source topic. * @return the source. */ public String getSource() { return this.record.topic(); } /** * Return the consumer record. * @return the record. * @since 3.0.6 */ public ConsumerRecord<?, ?> getRecord() { return this.record; } /** * Return the partition.
* @return the partition. * @since 3.2 */ public String getPartition() { return Integer.toString(this.record.partition()); } /** * Return the offset. * @return the offset. * @since 3.2 */ public String getOffset() { return Long.toString(this.record.offset()); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\micrometer\KafkaRecordReceiverContext.java
1
请完成以下Java代码
public String getCountryname() { return countryname; } /** * 设置名称 * * @param countryname 名称 */ public void setCountryname(String countryname) { this.countryname = countryname; } /** * 获取代码 * * @return countrycode - 代码
*/ public String getCountrycode() { return countrycode; } /** * 设置代码 * * @param countrycode 代码 */ public void setCountrycode(String countrycode) { this.countrycode = countrycode; } }
repos\MyBatis-Spring-Boot-master\src\main\java\tk\mybatis\springboot\model\Country.java
1
请完成以下Java代码
public class FlowNodeHistoryParseHandler implements BpmnParseHandler { protected static final ActivityInstanceEndHandler ACTIVITI_INSTANCE_END_LISTENER = new ActivityInstanceEndHandler(); protected static final ActivityInstanceStartHandler ACTIVITY_INSTANCE_START_LISTENER = new ActivityInstanceStartHandler(); protected static Set<Class<? extends BaseElement>> supportedElementClasses = new HashSet<>(); static { supportedElementClasses.add(EndEvent.class); supportedElementClasses.add(ThrowEvent.class); supportedElementClasses.add(BoundaryEvent.class); supportedElementClasses.add(IntermediateCatchEvent.class); supportedElementClasses.add(ExclusiveGateway.class); supportedElementClasses.add(InclusiveGateway.class); supportedElementClasses.add(ParallelGateway.class); supportedElementClasses.add(EventGateway.class); supportedElementClasses.add(Task.class); supportedElementClasses.add(ManualTask.class); supportedElementClasses.add(ReceiveTask.class); supportedElementClasses.add(ScriptTask.class); supportedElementClasses.add(ServiceTask.class); supportedElementClasses.add(BusinessRuleTask.class); supportedElementClasses.add(SendTask.class); supportedElementClasses.add(UserTask.class); supportedElementClasses.add(CallActivity.class); supportedElementClasses.add(SubProcess.class); }
@Override public Set<Class<? extends BaseElement>> getHandledTypes() { return supportedElementClasses; } @Override public void parse(BpmnParse bpmnParse, BaseElement element) { ActivityImpl activity = bpmnParse.getCurrentScope().findActivity(element.getId()); if (element instanceof BoundaryEvent) { // A boundary-event never receives an activity start-event activity.addExecutionListener(org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_END, ACTIVITY_INSTANCE_START_LISTENER, 0); activity.addExecutionListener(org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_END, ACTIVITI_INSTANCE_END_LISTENER, 1); } else { activity.addExecutionListener(org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_START, ACTIVITY_INSTANCE_START_LISTENER, 0); activity.addExecutionListener(org.activiti.engine.impl.pvm.PvmEvent.EVENTNAME_END, ACTIVITI_INSTANCE_END_LISTENER); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\history\parse\FlowNodeHistoryParseHandler.java
1
请完成以下Java代码
protected void logProcessDefinitionRegistrations(StringBuilder builder, List<ProcessDefinition> processDefinitions) { if(processDefinitions.isEmpty()) { builder.append("Deployment does not provide any process definitions."); } else { builder.append("Will execute process definitions "); builder.append("\n"); for (ProcessDefinition processDefinition : processDefinitions) { builder.append("\n"); builder.append(" "); builder.append(processDefinition.getKey()); builder.append("[version: "); builder.append(processDefinition.getVersion()); builder.append(", id: "); builder.append(processDefinition.getId()); builder.append("]"); } builder.append("\n"); } } protected void logCaseDefinitionRegistrations(StringBuilder builder, List<CaseDefinition> caseDefinitions) { if(caseDefinitions.isEmpty()) { builder.append("Deployment does not provide any case definitions."); } else { builder.append("\n"); builder.append("Will execute case definitions "); builder.append("\n"); for (CaseDefinition caseDefinition : caseDefinitions) { builder.append("\n"); builder.append(" "); builder.append(caseDefinition.getKey()); builder.append("[version: "); builder.append(caseDefinition.getVersion()); builder.append(", id: "); builder.append(caseDefinition.getId()); builder.append("]");
} builder.append("\n"); } } public String getRegistrationSummary() { StringBuilder builder = new StringBuilder(); for (Entry<String, DefaultProcessApplicationRegistration> entry : registrationsByDeploymentId.entrySet()) { if(builder.length()>0) { builder.append(", "); } builder.append(entry.getKey()); builder.append("->"); builder.append(entry.getValue().getReference().getName()); } return builder.toString(); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\application\ProcessApplicationManager.java
1
请完成以下Java代码
class PickedHUEditorRow { @NonNull public static PickedHUEditorRow ofProcessedRow(@NonNull final HUEditorRow huEditorRow) { return new PickedHUEditorRow(huEditorRow, true, ImmutableMap.of()); } @NonNull public static PickedHUEditorRow ofUnprocessedRow( @NonNull final HUEditorRow huEditorRow, @NonNull final ImmutableMap<HuId, ImmutableSet<OrderId>> huIds2OpenPickingOrderIds) { return new PickedHUEditorRow(huEditorRow, false, huIds2OpenPickingOrderIds); } @NonNull HUEditorRow huEditorRow; boolean processed; @NonNull ImmutableMap<HuId, ImmutableSet<OrderId>> huIds2OpenPickingOrderIds;
@NonNull public HuId getHUId() { return huEditorRow.getHuId(); } @NonNull public ImmutableMap<HuId, ImmutableSet<OrderId>> getPickingOrderIdsFor(@NonNull final ImmutableSet<HuId> huIds) { return huIds.stream() .collect(ImmutableMap.toImmutableMap(Function.identity(), huId -> Optional.ofNullable(huIds2OpenPickingOrderIds.get(huId)) .orElse(ImmutableSet.of()))); } public boolean containsHUId(@NonNull final HuId packToHUId) { return huEditorRow.getAllHuIds().contains(packToHUId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\pickingslot\PickedHUEditorRow.java
1
请完成以下Java代码
public class SimpleCustomKeyValue<K, V> implements Map.Entry<K, V> { private final K key; private V value; public SimpleCustomKeyValue(K key, V value) { this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public V setValue(V value) { return this.value = value; } @Override public boolean equals(Object o) { if (this == o) {
return true; } if (o == null || getClass() != o.getClass()) { return false; } SimpleCustomKeyValue<?, ?> that = (SimpleCustomKeyValue<?, ?>) o; return Objects.equals(key, that.key) && Objects.equals(value, that.value); } @Override public int hashCode() { return Objects.hash(key, value); } @Override public String toString() { return new StringJoiner(", ", SimpleCustomKeyValue.class.getSimpleName() + "[", "]").add("key=" + key).add("value=" + value).toString(); } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-4\src\main\java\com\baeldung\entries\SimpleCustomKeyValue.java
1
请在Spring Boot框架中完成以下Java代码
public class SetupDataLoader implements ApplicationListener<ContextRefreshedEvent> { private boolean alreadySetup = false; @Autowired private UserRepository userRepository; @Autowired private RoleRepository roleRepository; @Autowired private PrivilegeRepository privilegeRepository; @Autowired private PasswordEncoder passwordEncoder; @Override @Transactional public void onApplicationEvent(ContextRefreshedEvent event) { if (alreadySetup) { return; } // == create initial privileges Privilege readPrivilege = createPrivilegeIfNotFound("READ_PRIVILEGE"); Privilege writePrivilege = createPrivilegeIfNotFound("WRITE_PRIVILEGE"); // == create initial roles List<Privilege> adminPrivileges = Arrays.asList(readPrivilege, writePrivilege); createRoleIfNotFound("ROLE_ADMIN", adminPrivileges); List<Privilege> rolePrivileges = new ArrayList<>(); createRoleIfNotFound("ROLE_USER", rolePrivileges); Role adminRole = roleRepository.findByName("ROLE_ADMIN"); User user = new User(); user.setFirstName("Admin"); user.setLastName("Admin"); user.setEmail("admin@test.com"); user.setPassword(passwordEncoder.encode("admin")); user.setRoles(Arrays.asList(adminRole)); user.setEnabled(true); userRepository.save(user); Role basicRole = roleRepository.findByName("ROLE_USER"); User basicUser = new User(); basicUser.setFirstName("User"); basicUser.setLastName("User"); basicUser.setEmail("user@test.com"); basicUser.setPassword(passwordEncoder.encode("user")); basicUser.setRoles(Arrays.asList(basicRole));
basicUser.setEnabled(true); userRepository.save(basicUser); alreadySetup = true; } @Transactional public Privilege createPrivilegeIfNotFound(String name) { Privilege privilege = privilegeRepository.findByName(name); if (privilege == null) { privilege = new Privilege(name); privilegeRepository.save(privilege); } return privilege; } @Transactional public Role createRoleIfNotFound(String name, Collection<Privilege> privileges) { Role role = roleRepository.findByName(name); if (role == null) { role = new Role(name); role.setPrivileges(privileges); roleRepository.save(role); } return role; } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\rolesauthorities\persistence\SetupDataLoader.java
2
请完成以下Spring Boot application配置
server: port: 8080 servlet: context-path: /demo xxl: job: # 执行器通讯TOKEN [选填]:非空时启用; access-token: admin: # 调度中心部署跟地址 [选填]:如调度中心集群部署存在多个地址则用逗号分隔。执行器将会使用该地址进行"执行器心跳注册"和"任务结果回调";为空则关闭自动注册; address: http://localhost:18080/xxl-job-admin executor: # 执行器AppName [选填]:执行器心跳注册分组依据;为空则关闭自动注册 app-name: spring-boot-demo-task-xxl-job-executor # 执行器IP [选填]:默认为空表示自动获取IP,多网卡时可手动设置指定IP,该IP不会绑定Host仅作为通讯实用;地址信息用于 "执行器注册" 和 "调度中心请求并触发任务"; ip: # 执行器端口号 [选填]:小于等于0则自动获取;默认端口为9999,单机部署多个执行器
时,注意要配置不同执行器端口; port: 9999 # 执行器运行日志文件存储磁盘路径 [选填] :需要对该路径拥有读写权限;为空则使用默认路径; log-path: logs/spring-boot-demo-task-xxl-job/task-log # 执行器日志保存天数 [选填] :值大于3时生效,启用执行器Log文件定期清理功能,否则不生效; log-retention-days: -1
repos\spring-boot-demo-master\demo-task-xxl-job\src\main\resources\application.yml
2
请完成以下Java代码
public void run(String... args) throws Exception { User luke = new User("id-1", "luke"); luke.setFirstname("Luke"); luke.setLastname("Skywalker"); luke.setPosts(List.of(new Post("I have a bad feeling about this."))); User leia = new User("id-2", "leia"); leia.setFirstname("Leia"); leia.setLastname("Organa"); User han = new User("id-3", "han"); han.setFirstname("Han"); han.setLastname("Solo"); han.setPosts(List.of(new Post("It's the ship that made the Kessel Run in less than 12 Parsecs."))); User chewbacca = new User("id-4", "chewbacca"); User yoda = new User("id-5", "yoda"); yoda.setPosts(List.of(new Post("Do. Or do not. There is no try."), new Post("Decide you must, how to serve them best. If you leave now, help them you could; but you would destroy all for which they have fought, and suffered."))); User vader = new User("id-6", "vader"); vader.setFirstname("Anakin"); vader.setLastname("Skywalker"); vader.setPosts(List.of(new Post("I am your father"))); User kylo = new User("id-7", "kylo"); kylo.setFirstname("Ben"); kylo.setLastname("Solo"); repository.saveAll(List.of(luke, leia, han, chewbacca, yoda, vader, kylo));
repository.usersWithUsernamesStartingWith("l"); repository.findUserByUsername("yoda"); repository.findUserByPostsMessageLike("father"); repository.findOptionalUserByUsername("yoda"); Long count = repository.countUsersByLastnameLike("Sky"); Boolean exists = repository.existsByUsername("vader"); repository.findUserByLastnameLike("Sky"); } }
repos\spring-data-examples-main\mongodb\aot-optimization\src\main\java\example\springdata\aot\CLR.java
1
请完成以下Java代码
private BPartnerQuery buildBPartnerQuery(@NonNull final IdentifierString bpartnerIdentifier) { final IdentifierString.Type type = bpartnerIdentifier.getType(); final BPartnerQuery query; switch (type) { case METASFRESH_ID: query = BPartnerQuery.builder() .bPartnerId(bpartnerIdentifier.asMetasfreshId(BPartnerId::ofRepoId)) .build(); break; case EXTERNAL_ID: query = BPartnerQuery.builder() .externalId(bpartnerIdentifier.asExternalId()) .build(); break; case GLN: query = BPartnerQuery.builder() .gln(bpartnerIdentifier.asGLN()) .build(); break; case VALUE: query = BPartnerQuery.builder() .bpartnerValue(bpartnerIdentifier.asValue()) .build(); break; default: throw new AdempiereException("Invalid bpartnerIdentifier: " + bpartnerIdentifier); } return query;
} @VisibleForTesting public String buildDocumentNo(@NonNull final DocTypeId docTypeId) { final IDocumentNoBuilderFactory documentNoFactory = Services.get(IDocumentNoBuilderFactory.class); final String documentNo = documentNoFactory.forDocType(docTypeId.getRepoId(), /* useDefiniteSequence */false) .setClientId(Env.getClientId()) .setFailOnError(true) .build(); if (documentNo == null) { throw new AdempiereException("Cannot fetch documentNo for " + docTypeId); } return documentNo; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\remittanceadvice\impl\CreateRemittanceAdviceService.java
1
请在Spring Boot框架中完成以下Java代码
public class WEBUI_M_HU_ReturnFromCustomer_Pharma extends WEBUI_M_HU_ReturnFromCustomer { @Autowired private SecurPharmService securPharmService; @Param(mandatory = true, parameterName = WEBUI_M_HU_SecurPharmScan.PARAM_Barcode) private String dataMatrixCode; @Override protected ProcessPreconditionsResolution checkPreconditionsApplicable() { if (!isHUEditorView()) { return ProcessPreconditionsResolution.rejectWithInternalReason("not the HU view"); } if (!streamSelectedHUIds(Select.ONLY_TOPLEVEL).findAny().isPresent()) { return ProcessPreconditionsResolution.reject(msgBL.getTranslatableMsgText(WEBUI_HU_Constants.MSG_WEBUI_ONLY_TOP_LEVEL_HU)); } if (!securPharmService.hasConfig()) {
return ProcessPreconditionsResolution.rejectWithInternalReason("No securpharm config"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final DataMatrixCode dataMatrix = getDataMatrix(); final SecurPharmHUAttributesScanner scanner = securPharmService.newHUScanner(); streamSelectedHUs(Select.ONLY_TOPLEVEL) .forEach(hu -> scanner.scanAndUpdateHUAttributes(dataMatrix, hu)); return super.doIt(); } protected final DataMatrixCode getDataMatrix() { return DataMatrixCode.ofString(dataMatrixCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WEBUI_M_HU_ReturnFromCustomer_Pharma.java
2
请完成以下Java代码
public void postProcessApplicationDeploy(ProcessApplicationInterface processApplication) { counter.incrementAndGet(); } @SuppressWarnings("resource") @Override public void postProcessApplicationUndeploy(ProcessApplicationInterface processApplication) { // some tests deploy multiple PAs. => only clean DB after last PA is undeployed // if the deployment fails for example during parsing the deployment counter was not incremented // so we have to check if the counter is already zero otherwise we go into the negative values // best example is TestWarDeploymentWithBrokenBpmnXml in integration-test-engine test suite if(counter.get() == 0 || counter.decrementAndGet() == 0) { final ProcessEngine defaultProcessEngine = BpmPlatform.getDefaultProcessEngine(); try { logger.log(Level.INFO, "=== Ensure Clean Database ==="); ManagementServiceImpl managementService = (ManagementServiceImpl) defaultProcessEngine.getManagementService(); PurgeReport report = managementService.purge(); if (report.isEmpty()) { logger.log(Level.INFO, "Clean DB and cache."); } else { StringBuilder builder = new StringBuilder(); DatabasePurgeReport databasePurgeReport = report.getDatabasePurgeReport();
if (!databasePurgeReport.isEmpty()) { builder.append(DATABASE_NOT_CLEAN).append(databasePurgeReport.getPurgeReportAsString()); } CachePurgeReport cachePurgeReport = report.getCachePurgeReport(); if (!cachePurgeReport.isEmpty()) { builder.append(CACHE_IS_NOT_CLEAN).append(cachePurgeReport.getPurgeReportAsString()); } logger.log(Level.INFO, builder.toString()); } } catch(Throwable e) { logger.log(Level.SEVERE, "Could not clean DB:", e); } } } }
repos\camunda-bpm-platform-master\qa\ensure-clean-db-plugin\src\main\java\org\camunda\qa\impl\EnsureCleanDbPlugin.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getFinishOrderCount() { return finishOrderCount; } public void setFinishOrderCount(Integer finishOrderCount) { this.finishOrderCount = finishOrderCount; } public BigDecimal getFinishOrderAmount() { return finishOrderAmount; } public void setFinishOrderAmount(BigDecimal finishOrderAmount) {
this.finishOrderAmount = finishOrderAmount; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", finishOrderCount=").append(finishOrderCount); sb.append(", finishOrderAmount=").append(finishOrderAmount); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsMemberTag.java
1
请在Spring Boot框架中完成以下Java代码
public class JSONJavaException { String message; boolean userFriendlyError; @Nullable @JsonInclude(JsonInclude.Include.NON_EMPTY) String stackTrace; @Nullable @JsonInclude(JsonInclude.Include.NON_EMPTY) Map<String, Object> attributes; @Nullable @JsonInclude(JsonInclude.Include.NON_EMPTY) AdIssueId adIssueId; @Nullable public static JSONJavaException ofNullable(@Nullable final Exception exception, @NonNull final JSONOptions jsonOpts) { return exception != null ? of(exception, jsonOpts) : null; } @NonNull public static JSONJavaException of(@NonNull final Exception exception, @NonNull final JSONOptions jsonOpts) { return builder() .message(AdempiereException.extractMessageTrl(exception).translate(jsonOpts.getAdLanguage())) .userFriendlyError(AdempiereException.isUserValidationError(exception)) .stackTrace(Trace.toOneLineStackTraceString(exception)) .attributes(extractAttributes(exception, jsonOpts)) .adIssueId(IssueReportableExceptions.getAdIssueIdOrNull(exception)) .build(); } @Nullable private static Map<String, Object> extractAttributes(@NonNull final Exception exception, @NonNull final JSONOptions jsonOpts)
{ if (exception instanceof AdempiereException) { final Map<String, Object> exceptionAttributes = ((AdempiereException)exception).getParameters(); if (exceptionAttributes == null || exceptionAttributes.isEmpty()) { return null; } return exceptionAttributes.entrySet() .stream() .map(entry -> GuavaCollectors.entry(entry.getKey(), Values.valueToJsonObject(entry.getValue(), jsonOpts, String::valueOf))) .collect(GuavaCollectors.toImmutableMap()); } else { return null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\json\JSONJavaException.java
2
请完成以下Java代码
public class SynchronizedReceiver implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(SynchronizedReceiver.class); private final Data data; private String message; private boolean illegalMonitorStateExceptionOccurred; public SynchronizedReceiver(Data data) { this.data = data; } @Override public void run() { synchronized (data) { try { data.wait(); this.message = data.receive(); } catch (InterruptedException e) {
LOG.error("thread was interrupted", e); Thread.currentThread().interrupt(); } catch (IllegalMonitorStateException e) { LOG.error("illegal monitor state exception occurred", e); illegalMonitorStateExceptionOccurred = true; } } } public boolean hasIllegalMonitorStateExceptionOccurred() { return illegalMonitorStateExceptionOccurred; } public String getMessage() { return message; } }
repos\tutorials-master\core-java-modules\core-java-exceptions-3\src\main\java\com\baeldung\exceptions\illegalmonitorstate\SynchronizedReceiver.java
1
请完成以下Java代码
public void setPriorityRule (java.lang.String PriorityRule) { set_Value (COLUMNNAME_PriorityRule, PriorityRule); } /** Get Priorität. @return Priority of a document */ @Override public java.lang.String getPriorityRule () { return (java.lang.String)get_Value(COLUMNNAME_PriorityRule); } /** Set Verarbeitet. @param Processed Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Verarbeitet. @return Checkbox sagt aus, ob der Beleg verarbeitet wurde. */ @Override public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean)
return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Summe Zeilen. @param TotalLines Total of all document lines */ @Override public void setTotalLines (java.math.BigDecimal TotalLines) { set_Value (COLUMNNAME_TotalLines, TotalLines); } /** Get Summe Zeilen. @return Total of all document lines */ @Override public java.math.BigDecimal getTotalLines () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TotalLines); if (bd == null) return BigDecimal.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Requisition.java
1
请完成以下Java代码
public String getPrintName () { return (String)get_Value(COLUMNNAME_PrintName); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getSeqNo())); } /** Set X Position. @param XPosition Absolute X (horizontal) position in 1/72 of an inch */ public void setXPosition (int XPosition) { set_Value (COLUMNNAME_XPosition, Integer.valueOf(XPosition));
} /** Get X Position. @return Absolute X (horizontal) position in 1/72 of an inch */ public int getXPosition () { Integer ii = (Integer)get_Value(COLUMNNAME_XPosition); if (ii == null) return 0; return ii.intValue(); } /** Set Y Position. @param YPosition Absolute Y (vertical) position in 1/72 of an inch */ public void setYPosition (int YPosition) { set_Value (COLUMNNAME_YPosition, Integer.valueOf(YPosition)); } /** Get Y Position. @return Absolute Y (vertical) position in 1/72 of an inch */ public int getYPosition () { Integer ii = (Integer)get_Value(COLUMNNAME_YPosition); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintLabelLine.java
1
请完成以下Java代码
public Optional<Map<String, Object>> getMessagePayload(DelegateExecution execution) { return messagePayloadMappingProvider.getMessagePayload(execution); } @Override public ThrowMessage createThrowMessage(DelegateExecution execution) { String name = getMessageName(execution); Optional<String> correlationKey = getCorrelationKey(execution); Optional<String> businessKey = Optional.ofNullable(execution.getProcessInstanceBusinessKey()); Optional<Map<String, Object>> payload = getMessagePayload(execution); return ThrowMessage.builder() .name(name) .correlationKey(correlationKey) .businessKey(businessKey) .payload(payload) .build(); } @Override public MessageEventSubscriptionEntity createMessageEventSubscription( CommandContext commandContext, DelegateExecution execution ) { String messageName = getMessageName(execution); Optional<String> correlationKey = getCorrelationKey(execution); correlationKey.ifPresent(key -> assertNoExistingDuplicateEventSubscriptions(messageName, key, commandContext)); MessageEventSubscriptionEntity messageEvent = commandContext .getEventSubscriptionEntityManager() .insertMessageEvent(messageName, ExecutionEntity.class.cast(execution)); correlationKey.ifPresent(messageEvent::setConfiguration); return messageEvent; } public ExpressionManager getExpressionManager() { return expressionManager; } public MessagePayloadMappingProvider getMessagePayloadMappingProvider() { return messagePayloadMappingProvider; } protected String evaluateExpression(String expression, DelegateExecution execution) { return Optional.ofNullable(expressionManager.createExpression(expression)) .map(it -> it.getValue(execution)) .map(Object::toString) .orElseThrow(() -> new ActivitiIllegalArgumentException("Expression '" + expression + "' is null"));
} protected void assertNoExistingDuplicateEventSubscriptions( String messageName, String correlationKey, CommandContext commandContext ) { List<EventSubscriptionEntity> existing = commandContext .getEventSubscriptionEntityManager() .findEventSubscriptionsByName("message", messageName, null); existing .stream() .filter(subscription -> Objects.equals(subscription.getConfiguration(), correlationKey)) .findFirst() .ifPresent(subscription -> { throw new ActivitiIllegalArgumentException( "Duplicate message subscription '" + subscription.getEventName() + "' with correlation key '" + subscription.getConfiguration() + "'" ); }); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\parser\factory\DefaultMessageExecutionContext.java
1
请完成以下Java代码
public class M_InventoryLine_AssignSelectedLines extends JavaProcess { private static final String PARAM_NumberOfCounters = "NumberOfCounters"; private final IInventoryBL inventoryBL = Services.get(IInventoryBL.class); @Param(parameterName = PARAM_NumberOfCounters, mandatory = true) private BigDecimal numberOfCounters; @Override protected String doIt() throws Exception { final List<I_M_InventoryLine> inventoryLines = getSelectedInventoryLines(); inventoryBL.assignToInventoryCounters(inventoryLines, numberOfCounters.intValue()); return MSG_OK; }
private List<I_M_InventoryLine> getSelectedInventoryLines() { final IQueryFilter<I_M_InventoryLine> selectedInventoryLines = getProcessInfo().getQueryFilterOrElseFalse(); final IQueryBL queryBL = Services.get(IQueryBL.class); final IQueryBuilder<I_M_InventoryLine> queryBuilder = queryBL.createQueryBuilder(I_M_InventoryLine.class); final List<I_M_InventoryLine> inventoryLines = queryBuilder .filter(selectedInventoryLines) .addOnlyActiveRecordsFilter() .orderBy(I_M_InventoryLine.COLUMNNAME_M_Locator_ID) .create() .list(I_M_InventoryLine.class); return inventoryLines; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inventory\process\M_InventoryLine_AssignSelectedLines.java
1
请完成以下Java代码
public void updateHUTrxAttribute(@NonNull final MutableHUTransactionAttribute huTrxAttribute, @NonNull final IAttributeValue fromAttributeValue) { assertNotDisposed(); // // Set M_HU final I_M_HU hu = getM_HU(); huTrxAttribute.setReferencedObject(hu); // // Set HU related fields // // NOTE: we assume given "attributeValue" was created by "toAttributeValue" if (fromAttributeValue instanceof HUAttributeValue) { final HUAttributeValue attributeValueImpl = (HUAttributeValue)fromAttributeValue; final I_M_HU_PI_Attribute piAttribute = attributeValueImpl.getM_HU_PI_Attribute(); huTrxAttribute.setPiAttributeId(piAttribute != null ? HuPackingInstructionsAttributeId.ofRepoId(piAttribute.getM_HU_PI_Attribute_ID()) : null); final I_M_HU_Attribute huAttribute = attributeValueImpl.getM_HU_Attribute(); huTrxAttribute.setHuAttribute(huAttribute); } else { throw new AdempiereException("Attribute value " + fromAttributeValue + " is not valid for this storage (" + this + ")"); } } @Override public final UOMType getQtyUOMTypeOrNull() {
final I_M_HU hu = getM_HU(); final IHUStorageDAO huStorageDAO = getHUStorageDAO(); return huStorageDAO.getC_UOMTypeOrNull(hu); } @Override public final BigDecimal getStorageQtyOrZERO() { final IHUStorageFactory huStorageFactory = getAttributeStorageFactory().getHUStorageFactory(); final IHUStorage storage = huStorageFactory.getStorage(getM_HU()); final BigDecimal fullStorageQty = storage.getQtyForProductStorages().toBigDecimal(); return fullStorageQty; } @Override public final boolean isVirtual() { return handlingUnitsBL.isVirtual(getM_HU()); } @Override public Optional<WarehouseId> getWarehouseId() { final I_M_HU hu = getM_HU(); if (hu == null) { return Optional.empty(); } final WarehouseId warehouseId = IHandlingUnitsBL.extractWarehouseIdOrNull(hu); return Optional.ofNullable(warehouseId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\impl\AbstractHUAttributeStorage.java
1
请完成以下Java代码
public static Date getYesterdayEndTime() { return DateUtil.endOfDay(getYesterdayStartTime()); } /** * 明天开始时间 * * @return */ public static Date getTomorrowStartTime() { return DateUtil.beginOfDay(DateUtil.tomorrow()); } /** * 明天结束时间 * * @return */ public static Date getTomorrowEndTime() { return DateUtil.endOfDay(DateUtil.tomorrow()); } /**
* 今天开始时间 * * @return */ public static Date getTodayStartTime() { return DateUtil.beginOfDay(new Date()); } /** * 今天结束时间 * * @return */ public static Date getTodayEndTime() { return DateUtil.endOfDay(new Date()); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\DateRangeUtils.java
1
请完成以下Java代码
public class ConversationAssociationImpl extends BaseElementImpl implements ConversationAssociation { protected static AttributeReference<ConversationNode> innerConversationNodeRefAttribute; protected static AttributeReference<ConversationNode> outerConversationNodeRefAttribute; public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(ConversationAssociation.class, BPMN_ELEMENT_CONVERSATION_ASSOCIATION) .namespaceUri(BPMN20_NS) .extendsType(BaseElement.class) .instanceProvider(new ModelTypeInstanceProvider<ConversationAssociation>() { public ConversationAssociation newInstance(ModelTypeInstanceContext instanceContext) { return new ConversationAssociationImpl(instanceContext); } }); innerConversationNodeRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_INNER_CONVERSATION_NODE_REF) .required() .qNameAttributeReference(ConversationNode.class) .build(); outerConversationNodeRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_OUTER_CONVERSATION_NODE_REF) .required() .qNameAttributeReference(ConversationNode.class) .build(); typeBuilder.build(); } public ConversationAssociationImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public ConversationNode getInnerConversationNode() {
return innerConversationNodeRefAttribute.getReferenceTargetElement(this); } public void setInnerConversationNode(ConversationNode innerConversationNode) { innerConversationNodeRefAttribute.setReferenceTargetElement(this, innerConversationNode); } public ConversationNode getOuterConversationNode() { return outerConversationNodeRefAttribute.getReferenceTargetElement(this); } public void setOuterConversationNode(ConversationNode outerConversationNode) { outerConversationNodeRefAttribute.setReferenceTargetElement(this, outerConversationNode); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ConversationAssociationImpl.java
1
请完成以下Java代码
default org.compiere.model.I_AD_User getById(final int adUserRepoId) { return getById(UserId.ofRepoId(adUserRepoId)); } org.compiere.model.I_AD_User getById(UserId adUserId); <T extends org.compiere.model.I_AD_User> T getByIdInTrx(UserId userId, Class<T> modelClass); default org.compiere.model.I_AD_User getByIdInTrx(final UserId userId) { return getByIdInTrx(userId, org.compiere.model.I_AD_User.class); } org.compiere.model.I_AD_User getByIdInTrx(int adUserId); /** * @return user's full name or <code>?</code> if no found */ String retrieveUserFullName(int userRepoId); String retrieveUserFullName(UserId userId); /** * @param email the mail needs to be a syntactically correct mail-address! */
@Nullable UserId retrieveUserIdByEMail(@Nullable String email, ClientId adClientId); /** * @return all system(login) user IDs */ Set<UserId> retrieveSystemUserIds(); boolean isSystemUser(UserId userId); @Nullable BPartnerId getBPartnerIdByUserId(final UserId userId); @Nullable UserId retrieveUserIdByLogin(String login); void save(I_AD_User user); Optional<I_AD_User> getCounterpartUser( @NonNull UserId sourceUserId, @NonNull OrgId targetOrgId); ImmutableSet<UserId> retrieveUsersByJobId(JobId jobId); }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\api\IUserDAO.java
1
请完成以下Java代码
public List<I_PP_Order_Report> getCreatedReportLines() { return new ArrayList<>(_createdReportLines); } private IContextAware getContext() { return context; } private I_PP_Order getPP_Order() { // not null return ppOrder; } /** * Delete existing {@link I_PP_Order_Report}s lines linked to current manufacturing order. */ public void deleteReportLines() { final I_PP_Order ppOrder = getPP_Order(); queryBL.createQueryBuilder(I_PP_Order_Report.class, getContext()) .addEqualsFilter(org.eevolution.model.I_PP_Order_Report.COLUMNNAME_PP_Order_ID, ppOrder.getPP_Order_ID()) .create() // create query .delete(); // delete matching records _createdReportLines.clear(); _seqNoNext = 10; // reset seqNo } /** * Save given {@link IQualityInspectionLine} (i.e. creates {@link I_PP_Order_Report} lines). * * @param qiLines */ public void save(final Collection<IQualityInspectionLine> qiLines) { if (qiLines == null || qiLines.isEmpty()) { return; } final List<IQualityInspectionLine> qiLinesToSave = new ArrayList<>(qiLines); // // Discard not accepted lines and then sort them if (reportLinesSorter != null) { reportLinesSorter.filterAndSort(qiLinesToSave); } //
// Iterate lines and save one by one for (final IQualityInspectionLine qiLine : qiLinesToSave) { save(qiLine); } } /** * Save given {@link IQualityInspectionLine} (i.e. creates {@link I_PP_Order_Report} line). * * @param qiLine */ private void save(final IQualityInspectionLine qiLine) { Check.assumeNotNull(qiLine, "qiLine not null"); final I_PP_Order ppOrder = getPP_Order(); final int seqNo = _seqNoNext; BigDecimal qty = qiLine.getQty(); if (qty != null && qiLine.isNegateQtyInReport()) { qty = qty.negate(); } // // Create report line final I_PP_Order_Report reportLine = InterfaceWrapperHelper.newInstance(I_PP_Order_Report.class, getContext()); reportLine.setPP_Order(ppOrder); reportLine.setAD_Org_ID(ppOrder.getAD_Org_ID()); reportLine.setSeqNo(seqNo); reportLine.setIsActive(true); // reportLine.setQualityInspectionLineType(qiLine.getQualityInspectionLineType()); reportLine.setProductionMaterialType(qiLine.getProductionMaterialType()); reportLine.setM_Product(qiLine.getM_Product()); reportLine.setName(qiLine.getName()); reportLine.setQty(qty); reportLine.setC_UOM(qiLine.getC_UOM()); reportLine.setPercentage(qiLine.getPercentage()); reportLine.setQtyProjected(qiLine.getQtyProjected()); reportLine.setComponentType(qiLine.getComponentType()); reportLine.setVariantGroup(qiLine.getVariantGroup()); // // Save report line InterfaceWrapperHelper.save(reportLine); _createdReportLines.add(reportLine); _seqNoNext += 10; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\qualityBasedInvoicing\impl\PPOrderReportWriter.java
1
请完成以下Java代码
public int getCarrier_ShipmentOrder_Parcel_ID() { return get_ValueAsInt(COLUMNNAME_Carrier_ShipmentOrder_Parcel_ID); } @Override public void setHeightInCm (final int HeightInCm) { set_Value (COLUMNNAME_HeightInCm, HeightInCm); } @Override public int getHeightInCm() { return get_ValueAsInt(COLUMNNAME_HeightInCm); } @Override public void setLengthInCm (final int LengthInCm) { set_Value (COLUMNNAME_LengthInCm, LengthInCm); } @Override public int getLengthInCm() { return get_ValueAsInt(COLUMNNAME_LengthInCm); } @Override public void setM_Package_ID (final int M_Package_ID) { if (M_Package_ID < 1) set_Value (COLUMNNAME_M_Package_ID, null); else set_Value (COLUMNNAME_M_Package_ID, M_Package_ID); } @Override public int getM_Package_ID() { return get_ValueAsInt(COLUMNNAME_M_Package_ID); } @Override public void setPackageDescription (final @Nullable java.lang.String PackageDescription) { set_Value (COLUMNNAME_PackageDescription, PackageDescription); } @Override public java.lang.String getPackageDescription() { return get_ValueAsString(COLUMNNAME_PackageDescription); } @Override public void setPdfLabelData (final @Nullable byte[] PdfLabelData) { set_Value (COLUMNNAME_PdfLabelData, PdfLabelData);
} @Override public byte[] getPdfLabelData() { return (byte[])get_Value(COLUMNNAME_PdfLabelData); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } @Override public void setWeightInKg (final BigDecimal WeightInKg) { set_Value (COLUMNNAME_WeightInKg, WeightInKg); } @Override public BigDecimal getWeightInKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_WeightInKg); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_Carrier_ShipmentOrder_Parcel.java
1
请完成以下Java代码
public JsonCache getById( @PathVariable("cacheId") final String cacheIdStr, @RequestParam(name = "limit", required = false, defaultValue = "100") final int limit) { assertAuth(); final long cacheId = Long.parseLong(cacheIdStr); final CacheInterface cacheInterface = cacheMgt.getById(cacheId) .orElseThrow(() -> new AdempiereException("No cache found by cacheId=" + cacheId)); if (cacheInterface instanceof CCache) { return JsonCache.of((CCache<?, ?>)cacheInterface, limit); } else { throw new AdempiereException("Cache of type " + cacheInterface.getClass().getSimpleName() + " is not supported"); } } @GetMapping("/byId/{cacheId}/reset") public void resetCacheById(@PathVariable("cacheId") final String cacheIdStr) { assertAuth(); final long cacheId = Long.parseLong(cacheIdStr); final CacheInterface cacheInterface = cacheMgt.getById(cacheId) .orElseThrow(() -> new AdempiereException("No cache found by cacheId=" + cacheId)); cacheInterface.reset(); }
@GetMapping("/remoteCacheInvalidationTableNames") public Set<String> getRemoteCacheInvalidationTableNames() { return cacheMgt.getTableNamesToBroadcast() .stream() .sorted() .collect(ImmutableSet.toImmutableSet()); } @GetMapping("/remoteCacheInvalidationTableNames/add") public void enableRemoteCacheInvalidationForTableName(@RequestParam("tableName") final String tableName) { cacheMgt.enableRemoteCacheInvalidationForTableName(tableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\cache\rest\CacheRestControllerTemplate.java
1
请完成以下Java代码
protected void prepare() { // nothing } @Override protected String doIt() throws Exception { final Iterator<I_C_ValidCombination> accounts = retriveAccounts(); int countAll = 0; int countOK = 0; while (accounts.hasNext()) { final I_C_ValidCombination account = accounts.next(); final boolean updated = updateValueDescription(account); countAll++; if (updated) { countOK++; } } return "@Updated@/@Total@ #" + countOK + "/" + countAll; } private Iterator<I_C_ValidCombination> retriveAccounts() { final IQueryBuilder<I_C_ValidCombination> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(I_C_ValidCombination.class, getCtx(), ITrx.TRXNAME_None) .addOnlyContextClient() .addOnlyActiveRecordsFilter(); queryBuilder.orderBy() .addColumn(I_C_ValidCombination.COLUMNNAME_C_ValidCombination_ID); final Iterator<I_C_ValidCombination> accounts = queryBuilder.create() .iterate(I_C_ValidCombination.class); return accounts;
} /** * * @param account * @return true if updated; false if got errors (which will be logged) */ private boolean updateValueDescription(I_C_ValidCombination account) { DB.saveConstraints(); try { DB.getConstraints().addAllowedTrxNamePrefix(ITrx.TRXNAME_PREFIX_LOCAL); accountBL.setValueDescription(account); InterfaceWrapperHelper.save(account); return true; } catch (Exception e) { addLog(account.getCombination() + ": " + e.getLocalizedMessage()); log.warn(e.getLocalizedMessage(), e); } finally { DB.restoreConstraints(); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\process\C_ValidCombination_UpdateDescriptionForAll.java
1
请完成以下Java代码
public void setCompiler(Compiler compiler) { this.compiler = compiler; } /** * Set the charset used for reading Mustache template files. * @param charset the charset to use for reading template files */ public void setCharset(@Nullable String charset) { this.charset = charset; } @Override public boolean checkResourceExists(Locale locale) throws Exception { return resolveResource() != null; } @Override protected Mono<Void> renderInternal(Map<String, Object> model, @Nullable MediaType contentType, ServerWebExchange exchange) { Resource resource = resolveResource(); if (resource == null) { return Mono .error(new IllegalStateException("Could not find Mustache template with URL [" + getUrl() + "]")); } DataBuffer dataBuffer = exchange.getResponse() .bufferFactory() .allocateBuffer(DefaultDataBufferFactory.DEFAULT_INITIAL_CAPACITY); try (Reader reader = getReader(resource)) { Assert.state(this.compiler != null, "'compiler' must not be null"); Template template = this.compiler.compile(reader); Charset charset = getCharset(contentType).orElseGet(this::getDefaultCharset); try (Writer writer = new OutputStreamWriter(dataBuffer.asOutputStream(), charset)) { template.execute(model, writer); writer.flush(); } } catch (Exception ex) { DataBufferUtils.release(dataBuffer); return Mono.error(ex);
} return exchange.getResponse().writeWith(Flux.just(dataBuffer)); } private @Nullable Resource resolveResource() { ApplicationContext applicationContext = getApplicationContext(); String url = getUrl(); if (applicationContext == null || url == null) { return null; } Resource resource = applicationContext.getResource(url); if (resource == null || !resource.exists()) { return null; } return resource; } private Reader getReader(Resource resource) throws IOException { if (this.charset != null) { return new InputStreamReader(resource.getInputStream(), this.charset); } return new InputStreamReader(resource.getInputStream()); } private Optional<Charset> getCharset(@Nullable MediaType mediaType) { return Optional.ofNullable((mediaType != null) ? mediaType.getCharset() : null); } }
repos\spring-boot-4.0.1\module\spring-boot-mustache\src\main\java\org\springframework\boot\mustache\reactive\view\MustacheView.java
1
请在Spring Boot框架中完成以下Java代码
public class GreetingActor extends UntypedActor { private GreetingService greetingService; public GreetingActor(GreetingService greetingService) { this.greetingService = greetingService; } @Override public void onReceive(Object message) throws Throwable { if (message instanceof Greet) { String name = ((Greet) message).getName(); getSender().tell(greetingService.greet(name), getSelf()); } else { unhandled(message); } }
public static class Greet { private String name; public Greet(String name) { this.name = name; } public String getName() { return name; } } }
repos\tutorials-master\akka-modules\spring-akka\src\main\java\com\baeldung\akka\GreetingActor.java
2
请在Spring Boot框架中完成以下Java代码
public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public Users email(String email) { this.email = email; return this; } /** * Get email * @return email **/ @Schema(example = "m.mueller@it-labs.de", description = "") public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public Users timestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; return this; } /** * Der Zeitstempel der letzten Änderung * @return timestamp **/ @Schema(description = "Der Zeitstempel der letzten Änderung") public OffsetDateTime getTimestamp() { return timestamp; } public void setTimestamp(OffsetDateTime timestamp) { this.timestamp = timestamp; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Users users = (Users) o; return Objects.equals(this._id, users._id) && Objects.equals(this.firstName, users.firstName) && Objects.equals(this.lastName, users.lastName) && Objects.equals(this.email, users.email) && Objects.equals(this.timestamp, users.timestamp); }
@Override public int hashCode() { return Objects.hash(_id, firstName, lastName, email, timestamp); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Users {\n"); sb.append(" _id: ").append(toIndentedString(_id)).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(" timestamp: ").append(toIndentedString(timestamp)).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\Users.java
2
请完成以下Java代码
public void addQuantitiesRecord(@NonNull final ProductWithDemandSupply quantitiesRecord) { final I_C_UOM uom = uomDAO.getById(quantitiesRecord.getUomId()); qtyDemandSalesOrder = addToNullable(qtyDemandSalesOrder, quantitiesRecord.getQtyReserved(), uom); qtySupplyPurchaseOrder = addToNullable(qtySupplyPurchaseOrder, quantitiesRecord.getQtyToMove(), uom); } @NonNull public MaterialCockpitRow createIncludedRow(@NonNull final MainRowWithSubRows mainRowBucket) { final MainRowBucketId productIdAndDate = assumeNotNull( mainRowBucket.getProductIdAndDate(), "productIdAndDate may not be null; mainRowBucket={}", mainRowBucket); return MaterialCockpitRow.countingSubRowBuilder() .lookups(rowLookups) .cache(cache) .date(productIdAndDate.getDate())
.productId(productIdAndDate.getProductId().getRepoId()) .detailsRowAggregationIdentifier(detailsRowAggregationIdentifier) .qtyDemandSalesOrder(qtyDemandSalesOrder) .qtySupplyPurchaseOrder(qtySupplyPurchaseOrder) .qtyStockEstimateCountAtDate(qtyStockEstimateCountAtDate) .qtyStockEstimateTimeAtDate(qtyStockEstimateTimeAtDate) .qtyInventoryCountAtDate(qtyInventoryCountAtDate) .qtyInventoryTimeAtDate(qtyInventoryTimeAtDate) .qtyStockCurrentAtDate(qtyStockCurrentAtDate) .qtyOnHandStock(qtyOnHandStock) .allIncludedCockpitRecordIds(cockpitRecordIds) .allIncludedStockRecordIds(stockRecordIds) .qtyConvertor(qtyConvertorService.getQtyConvertorIfConfigured(productIdAndDate)) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\material\cockpit\rowfactory\CountingSubRowBucket.java
1
请完成以下Spring Boot application配置
server: port: 8080 zuul: prefix: /api routes: greeting-service: path: /greeting/** url: forward:/greeting foos-service: path: /fo
os/** url: http://localhost:8081/spring-zuul-foos-resource/foos
repos\tutorials-master\spring-cloud-modules\spring-cloud-zuul\spring-zuul-post-filter\src\main\resources\application.yml
2
请完成以下Java代码
public class BpmnProperties { public static final PropertyKey<String> TYPE = new PropertyKey<String>("type"); public static final PropertyListKey<EscalationEventDefinition> ESCALATION_EVENT_DEFINITIONS = new PropertyListKey<>("escalationEventDefinitions"); public static final PropertyListKey<ErrorEventDefinition> ERROR_EVENT_DEFINITIONS = new PropertyListKey<>("errorEventDefinitions"); /** * Declaration indexed by activity that is triggered by the event; assumes that there is at most one such declaration per activity. * There is code that relies on this assumption (e.g. when determining which declaration matches a job in the migration logic). */ public static final PropertyMapKey<String, TimerDeclarationImpl> TIMER_DECLARATIONS = new PropertyMapKey<>("timerDeclarations", false); /** * Declaration indexed by activity and listener (id) that is triggered by the event; there can be multiple such declarations per activity but only one per listener. * There is code that relies on this assumption (e.g. when determining which declaration matches a job in the migration logic). */ public static final PropertyMapKey<String, Map<String, TimerDeclarationImpl>> TIMEOUT_LISTENER_DECLARATIONS = new PropertyMapKey<>("timerListenerDeclarations", false); /** * Declaration indexed by activity that is triggered by the event; assumes that there is at most one such declaration per activity. * There is code that relies on this assumption (e.g. when determining which declaration matches a job in the migration logic).
*/ public static final PropertyMapKey<String, EventSubscriptionDeclaration> EVENT_SUBSCRIPTION_DECLARATIONS = new PropertyMapKey<>("eventDefinitions", false); public static final PropertyKey<ActivityImpl> COMPENSATION_BOUNDARY_EVENT = new PropertyKey<>("compensationBoundaryEvent"); public static final PropertyKey<ActivityImpl> INITIAL_ACTIVITY = new PropertyKey<>("initial"); public static final PropertyKey<Boolean> TRIGGERED_BY_EVENT = new PropertyKey<>("triggeredByEvent"); public static final PropertyKey<Boolean> HAS_CONDITIONAL_EVENTS = new PropertyKey<>(PROPERTYNAME_HAS_CONDITIONAL_EVENTS); public static final PropertyKey<ConditionalEventDefinition> CONDITIONAL_EVENT_DEFINITION = new PropertyKey<>("conditionalEventDefinition"); public static final PropertyKey<Map<String, String>> EXTENSION_PROPERTIES = new PropertyKey<>("extensionProperties"); public static final PropertyListKey<CamundaErrorEventDefinition> CAMUNDA_ERROR_EVENT_DEFINITION = new PropertyListKey<>("camundaErrorEventDefinition"); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\helper\BpmnProperties.java
1
请完成以下Java代码
public static final class Builder { private Integer C_BPartner_ID; private Integer M_Product_ID; private Integer M_AttributeSetInstance_ID; private Integer M_HU_PI_Item_Product_ID; private int C_Flatrate_DataEntry_ID = -1; // private Date date; // private BigDecimal qtyPromised = BigDecimal.ZERO; private BigDecimal qtyPromised_TU = BigDecimal.ZERO; private BigDecimal qtyOrdered = BigDecimal.ZERO; private BigDecimal qtyOrdered_TU = BigDecimal.ZERO; private BigDecimal qtyDelivered = BigDecimal.ZERO; private Builder() { super(); } public PMMBalanceChangeEvent build() { return new PMMBalanceChangeEvent(this); } public Builder setC_BPartner_ID(final int C_BPartner_ID) { this.C_BPartner_ID = C_BPartner_ID; return this; } public Builder setM_Product_ID(final int M_Product_ID) { this.M_Product_ID = M_Product_ID; return this; } public Builder setM_AttributeSetInstance_ID(final int M_AttributeSetInstance_ID) { this.M_AttributeSetInstance_ID = M_AttributeSetInstance_ID; return this; } public Builder setM_HU_PI_Item_Product_ID(final int M_HU_PI_Item_Product_ID) { this.M_HU_PI_Item_Product_ID = M_HU_PI_Item_Product_ID;
return this; } public Builder setC_Flatrate_DataEntry_ID(int C_Flatrate_DataEntry_ID) { this.C_Flatrate_DataEntry_ID = C_Flatrate_DataEntry_ID; return this; } public Builder setDate(final Date date) { this.date = date; return this; } public Builder setQtyPromised(final BigDecimal qtyPromised, final BigDecimal qtyPromised_TU) { this.qtyPromised = qtyPromised; this.qtyPromised_TU = qtyPromised_TU; return this; } public Builder setQtyOrdered(final BigDecimal qtyOrdered, final BigDecimal qtyOrdered_TU) { this.qtyOrdered = qtyOrdered; this.qtyOrdered_TU = qtyOrdered_TU; return this; } public Builder setQtyDelivered(BigDecimal qtyDelivered) { this.qtyDelivered = qtyDelivered; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\balance\PMMBalanceChangeEvent.java
1
请完成以下Java代码
public Double getPrice() { return price; } public Book price(Double price) { this.price = price; return this; } public void setPrice(Double price) { this.price = price; } // jhipster-needle-entity-add-getters-setters - JHipster will add getters and setters here, do not remove @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Book book = (Book) o; if (book.getId() == null || getId() == null) { return false; } return Objects.equals(getId(), book.getId()); } @Override public int hashCode() {
return Objects.hashCode(getId()); } @Override public String toString() { return "Book{" + "id=" + getId() + ", title='" + getTitle() + "'" + ", author='" + getAuthor() + "'" + ", published='" + getPublished() + "'" + ", quantity=" + getQuantity() + ", price=" + getPrice() + "}"; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\domain\Book.java
1
请完成以下Java代码
public class WorkflowService { private final WorkflowClient workflowClient; private final Environment environment; public Map<String, Object> startFoodDeliveryWorkflow(FoodDeliveryRequest foodDeliveryRequest) { StartWorkflowRequest request = new StartWorkflowRequest(); request.setName("FoodDeliveryWorkflow"); request.setVersion(1); request.setCorrelationId("api-triggered"); String TASK_DOMAIN_PROPERTY = "conductor.worker.all.domain"; String domain = environment.getProperty(TASK_DOMAIN_PROPERTY, String.class, ""); if (!domain.isEmpty()) { Map<String, String> taskToDomain = new HashMap<>(); taskToDomain.put("*", domain); request.setTaskToDomain(taskToDomain); } Map<String, Object> inputData = new HashMap<>(); inputData.put("customerEmail", foodDeliveryRequest.getCustomerEmail()); inputData.put("customerName", foodDeliveryRequest.getCustomerName()); inputData.put("customerContact", foodDeliveryRequest.getCustomerContact()); inputData.put("restaurantId", foodDeliveryRequest.getRestaurantId()); inputData.put("foodItems", foodDeliveryRequest.getFoodItems()); inputData.put("additionalNotes", foodDeliveryRequest.getAdditionalNotes()); inputData.put("address", foodDeliveryRequest.getAddress()); inputData.put("deliveryInstructions", foodDeliveryRequest.getDeliveryInstructions()); inputData.put("paymentAmount", foodDeliveryRequest.getPaymentAmount());
inputData.put("paymentMethod", foodDeliveryRequest.getPaymentMethod()); request.setInput(inputData); String workflowId = ""; try { workflowId = workflowClient.startWorkflow(request); log.info("Workflow id: {}", workflowId); } catch (Exception ex) { ex.printStackTrace(System.out); return Map.of("error", "Order creation failure", "detail", ex.toString()); } return Map.of("workflowId", workflowId); } }
repos\tutorials-master\microservices-modules\saga-pattern\src\main\java\io\orkes\example\saga\service\WorkflowService.java
1
请在Spring Boot框架中完成以下Java代码
public boolean isSuccess() { return isSuccess; } public void setSuccess(boolean success) { isSuccess = success; } public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } public T getData() { return data;
} public void setData(T data) { this.data = data; } @Override public String toString() { return "Result{" + "isSuccess=" + isSuccess + ", errorCode=" + errorCode + ", message='" + message + '\'' + ", data=" + data + '}'; } }
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Common-Service-Facade\src\main\java\com\gaoxi\rsp\Result.java
2
请完成以下Java代码
public class Customer { @XStreamAlias("fn") private String firstName; private String lastName; private Date dob; public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; }
public void setLastName(String lastName) { this.lastName = lastName; } public Date getDob() { return dob; } public void setDob(Date dob) { this.dob = dob; } @Override public String toString() { return "Customer [firstName=" + firstName + ", lastName=" + lastName + ", dob=" + dob + "]"; } }
repos\tutorials-master\xml-modules\xstream\src\main\java\com\baeldung\annotation\pojo\Customer.java
1
请完成以下Java代码
public User phone(String phone) { this.phone = phone; return this; } /** * Get phone * @return phone **/ @ApiModelProperty(value = "") public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } 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 final class GroupCreator { // services private final GroupRepository groupsRepo; private final GroupCompensationLineCreateRequestFactory compensationLineCreateRequestFactory; private final GroupTemplate groupTemplate; private final BigDecimal qty; @Builder private GroupCreator( @NonNull final GroupRepository groupsRepo, @NonNull final GroupCompensationLineCreateRequestFactory compensationLineCreateRequestFactory, // @NonNull final GroupTemplate groupTemplate, @Nullable final BigDecimal qty) { this.groupsRepo = groupsRepo; this.compensationLineCreateRequestFactory = compensationLineCreateRequestFactory; this.groupTemplate = groupTemplate; this.qty = coalesceNotNull(qty, ONE); } public static class GroupCreatorBuilder { public Group createGroup(@NonNull final Collection<OrderLineId> lineIdsToGroup) { return build().createGroup(lineIdsToGroup, null, null); } public Group createGroup( @NonNull final OrderId orderId, @Nullable final ConditionsId conditionsId) { return build().createGroup(null, orderId, conditionsId); } public void recreateGroup(@NonNull final Group group) {build().recreateGroup(group);} } public Group createGroup( @Nullable final Collection<OrderLineId> lineIdsToGroup, @Nullable final OrderId orderId, @Nullable final ConditionsId contractConditionsId) { final Group group = groupsRepo.retrieveOrCreateGroup( RetrieveOrCreateGroupRequest.builder() .orderId(orderId) .orderLineIds(lineIdsToGroup != null ? ImmutableSet.copyOf(lineIdsToGroup) : ImmutableSet.of()) .newGroupTemplate(groupTemplate)
.newContractConditionsId(contractConditionsId) .qtyMultiplier(qty) .build()); recreateGroup(group); return group; } public void recreateGroup(@NonNull final Group group) { group.removeAllGeneratedLines(); groupTemplate.getCompensationLines() .stream() .filter(compensationLineTemplate -> compensationLineTemplate.isMatching(group)) .map(templateLine -> compensationLineCreateRequestFactory.createGroupCompensationLineCreateRequest(templateLine, group)) .forEach(group::addNewCompensationLine); group.updateAllCompensationLines(); groupsRepo.saveGroup(group); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\compensationGroup\GroupCreator.java
1
请完成以下Java代码
public AdempiereProcessorLog[] getLogs () { ArrayList<MAlertProcessorLog> list = new ArrayList<>(); String sql = "SELECT * " + "FROM AD_AlertProcessorLog " + "WHERE AD_AlertProcessor_ID=? " + "ORDER BY Created DESC"; PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, getAD_AlertProcessor_ID()); rs = pstmt.executeQuery (); while (rs.next ()) list.add (new MAlertProcessorLog (getCtx(), rs, null)); } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } MAlertProcessorLog[] retValue = new MAlertProcessorLog[list.size ()]; list.toArray (retValue); return retValue; } // getLogs /** * Delete old Request Log * @return number of records */ public int deleteLog() { if (getKeepLogDays() < 1) return 0; String sql = "DELETE FROM AD_AlertProcessorLog " + "WHERE AD_AlertProcessor_ID=" + getAD_AlertProcessor_ID() + " AND (Created+" + getKeepLogDays() + ") < now()"; int no = DB.executeUpdateAndSaveErrorOnFail(sql, get_TrxName()); return no; } // deleteLog /** * Get Alerts * @param reload reload data * @return array of alerts */ public MAlert[] getAlerts (boolean reload) { MAlert[] alerts = s_cacheAlerts.get(get_ID()); if (alerts != null && !reload) return alerts;
String sql = "SELECT * FROM AD_Alert " + "WHERE AD_AlertProcessor_ID=? AND IsActive='Y' "; ArrayList<MAlert> list = new ArrayList<>(); PreparedStatement pstmt = null; ResultSet rs = null; try { pstmt = DB.prepareStatement (sql, null); pstmt.setInt (1, getAD_AlertProcessor_ID()); rs = pstmt.executeQuery (); while (rs.next ()) list.add (new MAlert (getCtx(), rs, null)); } catch (Exception e) { log.error(sql, e); } finally { DB.close(rs, pstmt); rs = null; pstmt = null; } // alerts = new MAlert[list.size ()]; list.toArray (alerts); s_cacheAlerts.put(get_ID(), alerts); return alerts; } // getAlerts @Override public boolean saveOutOfTrx() { return save(ITrx.TRXNAME_None); } } // MAlertProcessor
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MAlertProcessor.java
1
请完成以下Java代码
private static BPartnerId getBPartnerId(final IAllocationRequest request) { final Object referencedModel = AllocationUtils.getReferencedModel(request); if (referencedModel == null) { return null; } final Integer bpartnerId = InterfaceWrapperHelper.getValueOrNull(referencedModel, I_M_HU_PI_Item.COLUMNNAME_C_BPartner_ID); return BPartnerId.ofRepoIdOrNull(bpartnerId); } /** * Creates and configures an {@link IHUBuilder} based on the given <code>request</code> (bPartner and date). * * @return HU builder
*/ public static IHUBuilder createHUBuilder(final IAllocationRequest request) { final IHUContext huContext = request.getHuContext(); final IHUBuilder huBuilder = Services.get(IHandlingUnitsDAO.class).createHUBuilder(huContext); huBuilder.setDate(request.getDate()); huBuilder.setBPartnerId(getBPartnerId(request)); // TODO: huBuilder.setC_BPartner_Location if any // TODO: set the HU Storage from context to builder return huBuilder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationUtils.java
1
请完成以下Java代码
public FileValue readValue(ValueFields valueFields, boolean deserializeValue, boolean asTransientValue) { String fileName = valueFields.getTextValue(); if (fileName == null) { // ensure file name is not null fileName = ""; } FileValueBuilder builder = Variables.fileValue(fileName); if (valueFields.getByteArrayValue() != null) { builder.file(valueFields.getByteArrayValue()); } // to ensure the same array size all the time if (valueFields.getTextValue2() != null) { String[] split = Arrays.copyOf(valueFields.getTextValue2().split(MIMETYPE_ENCODING_SEPARATOR, NR_OF_VALUES_IN_TEXTFIELD2), NR_OF_VALUES_IN_TEXTFIELD2); String mimeType = returnNullIfEmptyString(split[0]); String encoding = returnNullIfEmptyString(split[1]); builder.mimeType(mimeType); builder.encoding(encoding); } builder.setTransient(asTransientValue); return builder.create(); }
protected String returnNullIfEmptyString(String s) { if (s.isEmpty()) { return null; } return s; } @Override public String getName() { return valueType.getName(); } @Override protected boolean canWriteValue(TypedValue value) { if (value == null || value.getType() == null) { // untyped value return false; } return value.getType().getName().equals(getName()); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\FileValueSerializer.java
1
请完成以下Java代码
public HUWithExpiryDates getByIdIfWarnDateExceededOrNull( @NonNull final HuId huId, @Nullable final LocalDate expiryWarnDate) { final Timestamp timestamp = TimeUtil.asTimestamp(expiryWarnDate); final I_M_HU_BestBefore_V recordOrdNull = queryBL.createQueryBuilder(I_M_HU_BestBefore_V.class) .addCompareFilter(I_M_HU_BestBefore_V.COLUMN_HU_ExpiredWarnDate, Operator.LESS_OR_EQUAL, timestamp, DateTruncQueryFilterModifier.DAY) .addNotEqualsFilter(I_M_HU_BestBefore_V.COLUMN_HU_Expired, HUAttributeConstants.ATTR_Expired_Value_Expired) .addEqualsFilter(I_M_HU_BestBefore_V.COLUMN_M_HU_ID, huId) .create() .firstOnly(I_M_HU_BestBefore_V.class); return ofRecordOrNull(recordOrdNull); } public HUWithExpiryDates getById(@NonNull final HuId huId) { final I_M_HU_BestBefore_V recordOrdNull = queryBL.createQueryBuilder(I_M_HU_BestBefore_V.class)
.addEqualsFilter(I_M_HU_BestBefore_V.COLUMN_M_HU_ID, huId) .create() .firstOnly(I_M_HU_BestBefore_V.class); return ofRecordOrNull(recordOrdNull); } public Iterator<HuId> getAllWithBestBeforeDate() { return handlingUnitsDAO.createHUQueryBuilder() .addOnlyWithAttributeNotNull(AttributeConstants.ATTR_BestBeforeDate) .addHUStatusesToInclude(huStatusBL.getQtyOnHandStatuses()) .createQuery() .iterateIds(HuId::ofRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\expiry\HUWithExpiryDatesRepository.java
1
请完成以下Java代码
public CaseFileItem getSource() { return sourceRefAttribute.getReferenceTargetElement(this); } public void setSource(CaseFileItem source) { sourceRefAttribute.setReferenceTargetElement(this, source); } public CaseFileItemTransition getStandardEvent() { CaseFileItemTransitionStandardEvent child = standardEventChild.getChild(this); return child.getValue(); } public void setStandardEvent(CaseFileItemTransition standardEvent) { CaseFileItemTransitionStandardEvent child = standardEventChild.getChild(this); child.setValue(standardEvent); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(CaseFileItemOnPart.class, CMMN_ELEMENT_CASE_FILE_ITEM_ON_PART) .extendsType(OnPart.class) .namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<CaseFileItemOnPart>() { public CaseFileItemOnPart newInstance(ModelTypeInstanceContext instanceContext) { return new CaseFileItemOnPartImpl(instanceContext); } }); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .idAttributeReference(CaseFileItem.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); standardEventChild = sequenceBuilder.element(CaseFileItemTransitionStandardEvent.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\CaseFileItemOnPartImpl.java
1
请完成以下Java代码
public class GatewayMetricsFilter implements GlobalFilter, Ordered { private static final Log log = LogFactory.getLog(GatewayMetricsFilter.class); private final MeterRegistry meterRegistry; private GatewayTagsProvider compositeTagsProvider; private final String metricsPrefix; public GatewayMetricsFilter(MeterRegistry meterRegistry, List<GatewayTagsProvider> tagsProviders, String metricsPrefix) { this.meterRegistry = meterRegistry; this.compositeTagsProvider = tagsProviders.stream().reduce(exchange -> Tags.empty(), GatewayTagsProvider::and); if (metricsPrefix.endsWith(".")) { this.metricsPrefix = metricsPrefix.substring(0, metricsPrefix.length() - 1); } else { this.metricsPrefix = metricsPrefix; } } public String getMetricsPrefix() { return metricsPrefix; } @Override public int getOrder() { // start the timer as soon as possible and report the metric event before we write // response to client return NettyWriteResponseFilter.WRITE_RESPONSE_FILTER_ORDER + 1; } @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { Sample sample = Timer.start(meterRegistry); return chain.filter(exchange) .doOnSuccess(aVoid -> endTimerRespectingCommit(exchange, sample))
.doOnError(throwable -> endTimerRespectingCommit(exchange, sample)); } private void endTimerRespectingCommit(ServerWebExchange exchange, Sample sample) { ServerHttpResponse response = exchange.getResponse(); if (response.isCommitted()) { endTimerInner(exchange, sample); } else { response.beforeCommit(() -> { endTimerInner(exchange, sample); return Mono.empty(); }); } } private void endTimerInner(ServerWebExchange exchange, Sample sample) { Tags tags = compositeTagsProvider.apply(exchange); if (log.isTraceEnabled()) { log.trace(metricsPrefix + ".requests tags: " + tags); } sample.stop(meterRegistry.timer(metricsPrefix + ".requests", tags)); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\GatewayMetricsFilter.java
1
请完成以下Java代码
public class ByteArrayFileStream extends ByteArrayStream { private FileChannel fileChannel; public ByteArrayFileStream(byte[] bytes, int bufferSize, FileChannel fileChannel) { super(bytes, bufferSize); this.fileChannel = fileChannel; } public static ByteArrayFileStream createByteArrayFileStream(String path) { try { FileInputStream fileInputStream = new FileInputStream(path); return createByteArrayFileStream(fileInputStream); } catch (Exception e) { Predefine.logger.warning(TextUtility.exceptionToString(e)); return null; } } public static ByteArrayFileStream createByteArrayFileStream(FileInputStream fileInputStream) throws IOException { FileChannel channel = fileInputStream.getChannel(); long size = channel.size(); int bufferSize = (int) Math.min(1048576, size); ByteBuffer byteBuffer = ByteBuffer.allocate(bufferSize); if (channel.read(byteBuffer) == size) { channel.close(); channel = null; } byteBuffer.flip(); byte[] bytes = byteBuffer.array(); return new ByteArrayFileStream(bytes, bufferSize, channel); } @Override public boolean hasMore() { return offset < bufferSize || fileChannel != null; } /** * 确保buffer数组余有size个字节 * @param size */ @Override protected void ensureAvailableBytes(int size) { if (offset + size > bufferSize) {
try { int availableBytes = (int) (fileChannel.size() - fileChannel.position()); ByteBuffer byteBuffer = ByteBuffer.allocate(Math.min(availableBytes, offset)); int readBytes = fileChannel.read(byteBuffer); if (readBytes == availableBytes) { fileChannel.close(); fileChannel = null; } assert readBytes > 0 : "已到达文件尾部!"; byteBuffer.flip(); byte[] bytes = byteBuffer.array(); System.arraycopy(this.bytes, offset, this.bytes, offset - readBytes, bufferSize - offset); System.arraycopy(bytes, 0, this.bytes, bufferSize - readBytes, readBytes); offset -= readBytes; } catch (IOException e) { throw new RuntimeException(e); } } } @Override public void close() { super.close(); try { if (fileChannel == null) return; fileChannel.close(); } catch (IOException e) { Predefine.logger.warning(TextUtility.exceptionToString(e)); } } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\io\ByteArrayFileStream.java
1
请完成以下Java代码
public int getAD_Table_ID() { return get_ValueAsInt(COLUMNNAME_AD_Table_ID); } @Override public void setAD_User_ID (final int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, AD_User_ID); } @Override public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setIsAcknowledged (final boolean IsAcknowledged) { set_Value (COLUMNNAME_IsAcknowledged, IsAcknowledged); } @Override public boolean isAcknowledged() { return get_ValueAsBoolean(COLUMNNAME_IsAcknowledged); } @Override public void setMsgText (final java.lang.String MsgText) { set_Value (COLUMNNAME_MsgText, MsgText); } @Override public java.lang.String getMsgText() { return get_ValueAsString(COLUMNNAME_MsgText); } @Override public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public void setRoot_AD_Table_ID (final int Root_AD_Table_ID) { if (Root_AD_Table_ID < 1) set_Value (COLUMNNAME_Root_AD_Table_ID, null); else set_Value (COLUMNNAME_Root_AD_Table_ID, Root_AD_Table_ID); }
@Override public int getRoot_AD_Table_ID() { return get_ValueAsInt(COLUMNNAME_Root_AD_Table_ID); } @Override public void setRoot_Record_ID (final int Root_Record_ID) { if (Root_Record_ID < 1) set_Value (COLUMNNAME_Root_Record_ID, null); else set_Value (COLUMNNAME_Root_Record_ID, Root_Record_ID); } @Override public int getRoot_Record_ID() { return get_ValueAsInt(COLUMNNAME_Root_Record_ID); } /** * Severity AD_Reference_ID=541949 * Reference name: Severity */ public static final int SEVERITY_AD_Reference_ID=541949; /** Notice = N */ public static final String SEVERITY_Notice = "N"; /** Error = E */ public static final String SEVERITY_Error = "E"; @Override public void setSeverity (final java.lang.String Severity) { set_Value (COLUMNNAME_Severity, Severity); } @Override public java.lang.String getSeverity() { return get_ValueAsString(COLUMNNAME_Severity); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Record_Warning.java
1
请完成以下Java代码
public class Add_Tables_to_DLM extends JavaProcess implements IProcessDefaultParametersProvider { @Param(mandatory = true, parameterName = I_DLM_Partition_Config.COLUMNNAME_DLM_Partition_Config_ID) private I_DLM_Partition_Config configDB; /** * Iterate the {@link I_DLM_Partition_Config_Line}s and handle their talbes one by one. * Runs out of trx because each table is dealt with in its own trx and the overall process might run for some time until all tables were processed. */ @Override @RunOutOfTrx protected String doIt() throws Exception { final IQueryBL queryBL = Services.get(IQueryBL.class); final IDLMService dlmService = Services.get(IDLMService.class); final ITrxManager trxManager = Services.get(ITrxManager.class); final List<I_DLM_Partition_Config_Line> configLinesDB = queryBL.createQueryBuilder(I_DLM_Partition_Config_Line.class, PlainContextAware.newWithThreadInheritedTrx(getCtx())) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DLM_Partition_Config_Line.COLUMN_DLM_Partition_Config_ID, configDB.getDLM_Partition_Config_ID()) .orderBy().addColumn(I_DLM_Partition_Config_Line.COLUMNNAME_DLM_Partition_Config_ID).endOrderBy() .create() .list(); for (final I_DLM_Partition_Config_Line line : configLinesDB) { final I_AD_Table dlm_Referencing_Table = InterfaceWrapperHelper.create(line.getDLM_Referencing_Table(), I_AD_Table.class); if (dlm_Referencing_Table.isDLM()) { Loggables.addLog("Table {} is already DLM'ed. Skipping", dlm_Referencing_Table.getTableName()); continue; }
trxManager.runInNewTrx(new TrxRunnable() { @Override public void run(String localTrxName) throws Exception { dlmService.addTableToDLM(dlm_Referencing_Table); } }); } return MSG_OK; } @Override public Object getParameterDefaultValue(final IProcessDefaultParameter parameter) { final int configId = parameter.getContextAsInt(I_DLM_Partition_Config.COLUMNNAME_DLM_Partition_Config_ID); if (configId > 0) { return configId; } return DEFAULT_VALUE_NOTAVAILABLE; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\process\Add_Tables_to_DLM.java
1
请完成以下Java代码
public class HeaderFooter { /** * Standard Constructor * @param ctx context */ public HeaderFooter (Properties ctx) { m_ctx = ctx; } // HeaderFooter /** Context */ private Properties m_ctx; /** Header/Footer content */ private ArrayList<PrintElement> m_elements = new ArrayList<PrintElement>(); /** Header/Footer content as Array */ private PrintElement[] m_pe = null; /** * Add Print Element to Page * @param element print element */ public void addElement (PrintElement element) { if (element != null) m_elements.add(element); m_pe = null; } // addElement /** * Get Elements * @return array of elements */ public PrintElement[] getElements() { if (m_pe == null) { m_pe = new PrintElement[m_elements.size()]; m_elements.toArray(m_pe); } return m_pe; } // getElements /** * Paint Page Header/Footer on Graphics in Bounds * * @param g2D graphics * @param bounds page bounds * @param isView true if online view (IDs are links) */ public void paint (Graphics2D g2D, Rectangle bounds, boolean isView) {
Point pageStart = new Point(bounds.getLocation()); getElements(); for (int i = 0; i < m_pe.length; i++) m_pe[i].paint(g2D, 0, pageStart, m_ctx, isView); } // paint /** * Get DrillDown value * @param relativePoint relative Point * @return if found NamePait or null */ public MQuery getDrillDown (Point relativePoint) { MQuery retValue = null; for (int i = 0; i < m_elements.size() && retValue == null; i++) { PrintElement element = (PrintElement)m_elements.get(i); retValue = element.getDrillDown (relativePoint, 1); } return retValue; } // getDrillDown } // HeaderFooter
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\HeaderFooter.java
1
请在Spring Boot框架中完成以下Java代码
public Long getMpsWeight() { return mpsWeight; } /** * Sets the value of the mpsWeight property. * * @param value * allowed object is * {@link Long } * */ public void setMpsWeight(Long value) { this.mpsWeight = value; } /** * Gets the value of the mpsExpectedSendingDate property. * * @return * possible object is * {@link String } * */ public String getMpsExpectedSendingDate() { return mpsExpectedSendingDate; } /** * Sets the value of the mpsExpectedSendingDate property. * * @param value * allowed object is * {@link String } * */ public void setMpsExpectedSendingDate(String value) { this.mpsExpectedSendingDate = value; } /** * Gets the value of the mpsExpectedSendingTime property. * * @return * possible object is * {@link String } * */ public String getMpsExpectedSendingTime() { return mpsExpectedSendingTime; } /** * Sets the value of the mpsExpectedSendingTime property. * * @param value * allowed object is * {@link String } * */ public void setMpsExpectedSendingTime(String value) { this.mpsExpectedSendingTime = value; } /** * Gets the value of the sender property.
* * @return * possible object is * {@link Address } * */ public Address getSender() { return sender; } /** * Sets the value of the sender property. * * @param value * allowed object is * {@link Address } * */ public void setSender(Address value) { this.sender = value; } /** * Gets the value of the recipient property. * * @return * possible object is * {@link Address } * */ public Address getRecipient() { return recipient; } /** * Sets the value of the recipient property. * * @param value * allowed object is * {@link Address } * */ public void setRecipient(Address value) { this.recipient = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\GeneralShipmentData.java
2
请完成以下Java代码
public DataFormatException unableToCreateTransformer(Exception cause) { return new DataFormatException(exceptionMessage("007", "Unable to create a transformer to write element"), cause); } public DataFormatException unableToTransformElement(Node element, Exception cause) { return new DataFormatException(exceptionMessage("008", "Unable to transform element '{}:{}'", element.getNamespaceURI(), element.getNodeName()), cause); } public DataFormatException unableToWriteInput(Object parameter, Throwable cause) { return new DataFormatException(exceptionMessage("009", "Unable to write object '{}' to xml element", parameter.toString()), cause); } public DataFormatException unableToDeserialize(Object node, String canonicalClassName, Throwable cause) { return new DataFormatException( exceptionMessage("010", "Cannot deserialize '{}...' to java class '{}'", node.toString(), canonicalClassName), cause); } public DataFormatException unableToCreateMarshaller(Throwable cause) { return new DataFormatException(exceptionMessage("011", "Cannot create marshaller"), cause);
} public DataFormatException unableToCreateContext(Throwable cause) { return new DataFormatException(exceptionMessage("012", "Cannot create context"), cause); } public DataFormatException unableToCreateUnmarshaller(Throwable cause) { return new DataFormatException(exceptionMessage("013", "Cannot create unmarshaller"), cause); } public DataFormatException classNotFound(String classname, ClassNotFoundException cause) { return new DataFormatException(exceptionMessage("014", "Class {} not found ", classname), cause); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\xml\DomXmlLogger.java
1
请完成以下Java代码
public void setPackVerificationMessage (java.lang.String PackVerificationMessage) { set_Value (COLUMNNAME_PackVerificationMessage, PackVerificationMessage); } /** Get Verification Message. @return Verification Message */ @Override public java.lang.String getPackVerificationMessage () { return (java.lang.String)get_Value(COLUMNNAME_PackVerificationMessage); } /** Set Produktcode. @param ProductCode Produktcode */ @Override public void setProductCode (java.lang.String ProductCode) { set_ValueNoCheck (COLUMNNAME_ProductCode, ProductCode); } /** Get Produktcode. @return Produktcode */ @Override public java.lang.String getProductCode () { return (java.lang.String)get_Value(COLUMNNAME_ProductCode); } /** Set Kodierungskennzeichen. @param ProductCodeType Kodierungskennzeichen */ @Override public void setProductCodeType (java.lang.String ProductCodeType) { set_ValueNoCheck (COLUMNNAME_ProductCodeType, ProductCodeType); }
/** Get Kodierungskennzeichen. @return Kodierungskennzeichen */ @Override public java.lang.String getProductCodeType () { return (java.lang.String)get_Value(COLUMNNAME_ProductCodeType); } /** * SerialNumber AD_Reference_ID=110 * Reference name: AD_User */ public static final int SERIALNUMBER_AD_Reference_ID=110; /** Set Seriennummer. @param SerialNumber Seriennummer */ @Override public void setSerialNumber (java.lang.String SerialNumber) { set_ValueNoCheck (COLUMNNAME_SerialNumber, SerialNumber); } /** Get Seriennummer. @return Seriennummer */ @Override public java.lang.String getSerialNumber () { return (java.lang.String)get_Value(COLUMNNAME_SerialNumber); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.securpharm\src\main\java-gen\de\metas\vertical\pharma\securpharm\model\X_M_Securpharm_Productdata_Result.java
1
请完成以下Java代码
public String outputFile(TableInfo tableInfo) { // Mapper String xmlUrl = projectPath + "/src/main/resources/mapper/" + module + "/" + tableInfo.getEntityName() + "Mapper" + StringPool.DOT_XML; System.out.println("xml path:"+xmlUrl); return xmlUrl; } }); cfg.setFileOutConfigList(focList); mpg.setCfg(cfg); // templateConfig TemplateConfig templateConfig = new TemplateConfig(); templateConfig.setXml(null); mpg.setTemplate(templateConfig); // StrategyConfig StrategyConfig strategy = new StrategyConfig(); strategy.setNaming(NamingStrategy.underline_to_camel);
strategy.setColumnNaming(NamingStrategy.underline_to_camel); strategy.setEntityLombokModel(true); strategy.setRestControllerStyle(true); // common file //strategy.setSuperEntityColumns("id"); strategy.setInclude(scanner("tablename,multi can be seperated ,").split(",")); strategy.setControllerMappingHyphenStyle(true); strategy.setTablePrefix(pc.getModuleName() + "_"); //isAnnotationEnable strategy.setEntityTableFieldAnnotationEnable(true); mpg.setStrategy(strategy); mpg.setTemplateEngine(new FreemarkerTemplateEngine()); mpg.execute(); } }
repos\springboot-demo-master\dynamic-datasource\src\main\java\com\et\dynamic\datasource\GeneratorCode.java
1
请完成以下Java代码
public boolean hasParameter(final String parameterName) { return false; } @Override public Object getParameterAsObject(final String parameterName) { return null; } @Override public String getParameterAsString(final String parameterName) { return null; } @Override public int getParameterAsInt(final String parameterName, final int defaultValue) { return defaultValue; } @Override public <T extends RepoIdAware> T getParameterAsId(String parameterName, Class<T> type) { return null; } @Override public boolean getParameterAsBool(final String parameterName) { return false; } @Nullable @Override public Boolean getParameterAsBoolean(final String parameterName, @Nullable final Boolean defaultValue) { return defaultValue; } @Override public Timestamp getParameterAsTimestamp(final String parameterName) { return null; } @Override public LocalDate getParameterAsLocalDate(final String parameterName) { return null; } @Override
public ZonedDateTime getParameterAsZonedDateTime(final String parameterName) { return null; } @Nullable @Override public Instant getParameterAsInstant(final String parameterName) { return null; } @Override public BigDecimal getParameterAsBigDecimal(final String paraCheckNetamttoinvoice) { return null; } /** * Returns an empty list. */ @Override public Collection<String> getParameterNames() { return ImmutableList.of(); } @Override public <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType) { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\NullParams.java
1
请在Spring Boot框架中完成以下Java代码
public class GrpcSslConfigurer extends AbstractSslConfigurer<NettyChannelBuilder, ManagedChannel> { public GrpcSslConfigurer(HttpClientProperties.Ssl sslProperties, SslBundles bundles) { super(sslProperties, bundles); } @Override public ManagedChannel configureSsl(NettyChannelBuilder NettyChannelBuilder) throws SSLException { return NettyChannelBuilder.useTransportSecurity().sslContext(getSslContext()).build(); } private SslContext getSslContext() throws SSLException { final SslContextBuilder sslContextBuilder = GrpcSslContexts.forClient(); final HttpClientProperties.Ssl ssl = getSslProperties(); boolean useInsecureTrustManager = ssl.isUseInsecureTrustManager(); SslBundle bundle = getBundle(); if (useInsecureTrustManager) { sslContextBuilder.trustManager(InsecureTrustManagerFactory.INSTANCE.getTrustManagers()[0]);
} if (!useInsecureTrustManager && ssl.getTrustedX509Certificates().size() > 0) { sslContextBuilder.trustManager(getTrustedX509CertificatesForTrustManager()); } else if (bundle != null) { sslContextBuilder.trustManager(bundle.getManagers().getTrustManagerFactory()); } if (bundle != null) { sslContextBuilder.keyManager(bundle.getManagers().getKeyManagerFactory()); } else { sslContextBuilder.keyManager(getKeyManagerFactory()); } return sslContextBuilder.build(); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\GrpcSslConfigurer.java
2
请完成以下Java代码
public static class KeyValue { private final String key; private final String value; public KeyValue(String key, String value) { this.key = key; this.value = value; } public String getKey() { return key; } public String getValue() {
return value; } @Override public String toString() { return new ToStringCreator(this).append("name", key).append("value", value).toString(); } public static KeyValue valueOf(String s) { String[] tokens = StringUtils.tokenizeToStringArray(s, ":", true, true); Assert.isTrue(tokens.length == 2, () -> "String must be two tokens delimited by colon, but was " + s); return new KeyValue(tokens[0], tokens[1]); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\common\KeyValues.java
1
请完成以下Java代码
public void setC_Invoice_ID (int C_Invoice_ID) { if (C_Invoice_ID < 1) set_Value (COLUMNNAME_C_Invoice_ID, null); else set_Value (COLUMNNAME_C_Invoice_ID, Integer.valueOf(C_Invoice_ID)); } /** Get Rechnung. @return Invoice Identifier */ @Override public int getC_Invoice_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Zahlungsaufforderung. @param C_Payment_Request_ID Zahlungsaufforderung */ @Override public void setC_Payment_Request_ID (int C_Payment_Request_ID) { if (C_Payment_Request_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Payment_Request_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Payment_Request_ID, Integer.valueOf(C_Payment_Request_ID)); } /** Get Zahlungsaufforderung. @return Zahlungsaufforderung */ @Override public int getC_Payment_Request_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Payment_Request_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Eingelesene Zeichenkette. @param FullPaymentString Im Fall von ESR oder anderen von Zahlschein gelesenen Zahlungsaufforderungen ist dies der komplette vom Schein eingelesene String */ @Override public void setFullPaymentString (java.lang.String FullPaymentString) { set_Value (COLUMNNAME_FullPaymentString, FullPaymentString); } /** Get Eingelesene Zeichenkette.
@return Im Fall von ESR oder anderen von Zahlschein gelesenen Zahlungsaufforderungen ist dies der komplette vom Schein eingelesene String */ @Override public java.lang.String getFullPaymentString () { return (java.lang.String)get_Value(COLUMNNAME_FullPaymentString); } /** Set Sales Transaction. @param IsSOTrx This is a Sales Transaction */ @Override public void setIsSOTrx (boolean IsSOTrx) { set_Value (COLUMNNAME_IsSOTrx, Boolean.valueOf(IsSOTrx)); } /** Get Sales Transaction. @return This is a Sales Transaction */ @Override public boolean isSOTrx () { Object oo = get_Value(COLUMNNAME_IsSOTrx); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Referenz. @param Reference Bezug für diesen Eintrag */ @Override public void setReference (java.lang.String Reference) { set_Value (COLUMNNAME_Reference, Reference); } /** Get Referenz. @return Bezug für diesen Eintrag */ @Override public java.lang.String getReference () { return (java.lang.String)get_Value(COLUMNNAME_Reference); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_Payment_Request.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, Meter> getMeter() { return this.meter; } /** * Per-meter settings. */ public static class Meter { /** * Maximum number of buckets to be used for exponential histograms, if configured. * This has no effect on explicit bucket histograms. */ private @Nullable Integer maxBucketCount; /** * Histogram type when histogram publishing is enabled. */ private @Nullable HistogramFlavor histogramFlavor;
public @Nullable Integer getMaxBucketCount() { return this.maxBucketCount; } public void setMaxBucketCount(@Nullable Integer maxBucketCount) { this.maxBucketCount = maxBucketCount; } public @Nullable HistogramFlavor getHistogramFlavor() { return this.histogramFlavor; } public void setHistogramFlavor(@Nullable HistogramFlavor histogramFlavor) { this.histogramFlavor = histogramFlavor; } } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\otlp\OtlpMetricsProperties.java
2
请在Spring Boot框架中完成以下Java代码
public List<String> getTrustedX509Certificates() { return trustedX509Certificates; } public void setTrustedX509Certificates(List<String> trustedX509) { this.trustedX509Certificates = trustedX509; } public boolean isUseInsecureTrustManager() { return useInsecureTrustManager; } public void setUseInsecureTrustManager(boolean useInsecureTrustManager) { this.useInsecureTrustManager = useInsecureTrustManager; } public Duration getHandshakeTimeout() { return handshakeTimeout; } public void setHandshakeTimeout(Duration handshakeTimeout) { this.handshakeTimeout = handshakeTimeout; } public Duration getCloseNotifyFlushTimeout() { return closeNotifyFlushTimeout; } public void setCloseNotifyFlushTimeout(Duration closeNotifyFlushTimeout) { this.closeNotifyFlushTimeout = closeNotifyFlushTimeout; } public Duration getCloseNotifyReadTimeout() { return closeNotifyReadTimeout; } public void setCloseNotifyReadTimeout(Duration closeNotifyReadTimeout) { this.closeNotifyReadTimeout = closeNotifyReadTimeout; } public String getSslBundle() { return sslBundle; } public void setSslBundle(String sslBundle) { this.sslBundle = sslBundle; } @Override public String toString() { return new ToStringCreator(this).append("useInsecureTrustManager", useInsecureTrustManager) .append("trustedX509Certificates", trustedX509Certificates) .append("handshakeTimeout", handshakeTimeout) .append("closeNotifyFlushTimeout", closeNotifyFlushTimeout) .append("closeNotifyReadTimeout", closeNotifyReadTimeout)
.toString(); } } public static class Websocket { /** Max frame payload length. */ private Integer maxFramePayloadLength; /** Proxy ping frames to downstream services, defaults to true. */ private boolean proxyPing = true; public Integer getMaxFramePayloadLength() { return this.maxFramePayloadLength; } public void setMaxFramePayloadLength(Integer maxFramePayloadLength) { this.maxFramePayloadLength = maxFramePayloadLength; } public boolean isProxyPing() { return proxyPing; } public void setProxyPing(boolean proxyPing) { this.proxyPing = proxyPing; } @Override public String toString() { return new ToStringCreator(this).append("maxFramePayloadLength", maxFramePayloadLength) .append("proxyPing", proxyPing) .toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientProperties.java
2
请完成以下Java代码
public String getId() { return id; } public void setId(String id) { this.id = id; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getEmail() { return email; }
public void setEmail(String email) { this.email = email; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } @Override public String toString() { return ToStringBuilder.reflectionToString(this); } }
repos\spring-boot-leaning-master\1.x\第16课:综合实战用户管理系统\user-manage\src\main\java\com\neo\param\UserParam.java
1
请完成以下Java代码
public List<BookDTO> getAllBooks() { log.debug("REST request to get all Books"); return bookService.findAll(); } /** * GET /books/:id : get the "id" book. * * @param id the id of the bookDTO to retrieve * @return the ResponseEntity with status 200 (OK) and with body the bookDTO, or with status 404 (Not Found) */ @GetMapping("/books/{id}") public ResponseEntity<BookDTO> getBook(@PathVariable Long id) { log.debug("REST request to get Book : {}", id); Optional<BookDTO> bookDTO = bookService.findOne(id); return ResponseUtil.wrapOrNotFound(bookDTO); } /**
* DELETE /books/:id : delete the "id" book. * * @param id the id of the bookDTO to delete * @return the ResponseEntity with status 200 (OK) */ @DeleteMapping("/books/{id}") public ResponseEntity<Void> deleteBook(@PathVariable Long id) { log.debug("REST request to delete Book : {}", id); bookService.delete(id); return ResponseEntity.ok().headers(HeaderUtil.createEntityDeletionAlert(ENTITY_NAME, id.toString())).build(); } @GetMapping("/books/purchase/{id}") public ResponseEntity<BookDTO> purchase(@PathVariable Long id) { Optional<BookDTO> bookDTO = bookService.purchase(id); return ResponseUtil.wrapOrNotFound(bookDTO); } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\web\rest\BookResource.java
1
请完成以下Java代码
public void setTitle(String value) { set(2, value); } /** * Getter for <code>public.Book.title</code>. */ public String getTitle() { return (String) get(2); } /** * Setter for <code>public.Book.description</code>. */ public void setDescription(String value) { set(3, value); } /** * Getter for <code>public.Book.description</code>. */ public String getDescription() { return (String) get(3); } /** * Setter for <code>public.Book.store_id</code>. */ public void setStoreId(Integer value) { set(4, value); } /** * Getter for <code>public.Book.store_id</code>. */ public Integer getStoreId() { return (Integer) get(4); } // -------------------------------------------------------------------------
// Primary key information // ------------------------------------------------------------------------- @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached BookRecord */ public BookRecord() { super(Book.BOOK); } /** * Create a detached, initialised BookRecord */ public BookRecord(Integer id, Integer authorId, String title, String description, Integer storeId) { super(Book.BOOK); setId(id); setAuthorId(authorId); setTitle(title); setDescription(description); setStoreId(storeId); resetChangedOnNotNull(); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\records\BookRecord.java
1
请完成以下Java代码
public int getC_CountryArea_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_CountryArea_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Suchschlüssel. @param Value
Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public void setValue (java.lang.String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Suchschlüssel. @return Suchschlüssel für den Eintrag im erforderlichen Format - muss eindeutig sein */ @Override public java.lang.String getValue () { return (java.lang.String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_CountryArea.java
1
请完成以下Java代码
public List<Long> getPzn() { if (pzn == null) { pzn = new ArrayList<Long>(); } return this.pzn; } /** * Gets the value of the pznBlock property. * * @return * possible object is * {@link Long } * */ public Long getPznBlock() { return pznBlock; } /** * Sets the value of the pznBlock property. * * @param value * allowed object is * {@link Long } * */ public void setPznBlock(Long value) { this.pznBlock = value; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } *
*/ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\VerfuegbarkeitsanfrageBulk.java
1
请完成以下Java代码
private WebuiHUTransformCommandResult action_SplitTU_To_NewLU( final HUEditorRow tuRow, final I_M_HU_PI_Item huPIItem, final QtyTU qtyTU, final boolean isOwnPackingMaterials) { final List<I_M_HU> createdHUs = newHUTransformation().tuToNewLUs(tuRow.getM_HU(), qtyTU, huPIItem, isOwnPackingMaterials).getLURecords(); final ImmutableSet<HuId> huIdsToAddToView = createdHUs.stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); return WebuiHUTransformCommandResult.builder() .huIdsCreated(huIdsToAddToView) .huIdsToAddToView(huIdsToAddToView) .huIdChanged(tuRow.getHURowId().getTopLevelHUId()) .fullViewInvalidation(true) // because it might be that the TU is inside an LU of which we don't know the ID .build(); } /** * Split a given number of TUs from current selected TU line to new TUs. */ private WebuiHUTransformCommandResult action_SplitTU_To_NewTUs(final HUEditorRow tuRow, final QtyTU qtyTU) { final IHandlingUnitsBL handlingUnitsBL = Services.get(IHandlingUnitsBL.class); // TODO: if qtyTU is the "maximum", then don't do anything, but show a user message final I_M_HU fromTU = tuRow.getM_HU();
final I_M_HU fromTopLevelHU = handlingUnitsBL.getTopLevelParent(fromTU); final List<I_M_HU> createdHUs = newHUTransformation().tuToNewTUs(fromTU, qtyTU).getAllTURecords(); final ImmutableSet<HuId> huIdsToAddToView = createdHUs.stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); final WebuiHUTransformCommandResultBuilder resultBuilder = WebuiHUTransformCommandResult.builder() .huIdsToAddToView(huIdsToAddToView) .huIdsCreated(huIdsToAddToView); if (handlingUnitsBL.isDestroyedRefreshFirst(fromTopLevelHU)) { resultBuilder.huIdToRemoveFromView(HuId.ofRepoId(fromTopLevelHU.getM_HU_ID())); } else { resultBuilder.huIdChanged(HuId.ofRepoId(fromTopLevelHU.getM_HU_ID())); } return resultBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\process\WebuiHUTransformCommand.java
1
请完成以下Java代码
private I_M_Movement getMovementHeaderOrNull() { return movementHeader; } private void addOrUpdateMovementLine(@NonNull final IHUProductStorage productStorage) { // Skip it if product storage is empty if (productStorage.isEmpty()) { return; } final ProductId productId = productStorage.getProductId(); final I_M_MovementLine movementLine = getOrCreateMovementLine(productId); final I_C_UOM productUOM = productBL.getStockUOM(productId); final BigDecimal qtyToMove = productStorage.getQty(productUOM).toBigDecimal(); // // Adjust movement line's qty to move final BigDecimal movementLine_Qty_Old = movementLine.getMovementQty(); final BigDecimal movementLine_Qty_New = movementLine_Qty_Old.add(qtyToMove); movementLine.setMovementQty(movementLine_Qty_New); // Make sure movement line it's saved movementDAO.save(movementLine); // Assign the HU to movement line { final I_M_HU hu = productStorage.getM_HU(); final boolean isTransferPackingMaterials = huIdsWithPackingMaterialsTransferred.addHuId(productStorage.getHuId()); huAssignmentBL.assignHU(movementLine, hu, isTransferPackingMaterials, ITrx.TRXNAME_ThreadInherited); } } private I_M_MovementLine getOrCreateMovementLine(final ProductId productId) { return movementLines.computeIfAbsent(productId, this::newMovementLine); } @NonNull private I_M_MovementLine newMovementLine(final ProductId productId) { final I_M_Movement movement = getOrCreateMovementHeader(); I_M_MovementLine movementLine = InterfaceWrapperHelper.newInstance(I_M_MovementLine.class, movement); movementLine.setAD_Org_ID(movement.getAD_Org_ID()); movementLine.setM_Movement_ID(movement.getM_Movement_ID());
movementLine.setIsPackagingMaterial(false); movementLine.setM_Product_ID(productId.getRepoId()); movementLine.setM_Locator_ID(locatorFromId.getRepoId()); movementLine.setM_LocatorTo_ID(request.getToLocatorId().getRepoId()); // // Reference if (request.getDdOrderLineId() != null) { movementLine.setDD_OrderLine_ID(request.getDdOrderLineId().getDdOrderLineId().getRepoId()); } // NOTE: we are not saving the movement line return movementLine; } private void assertTopLevelHUs(final Collection<I_M_HU> hus) { for (final I_M_HU hu : hus) { if (!handlingUnitsBL.isTopLevel(hu)) { throw new HUException("@M_HU_ID@ @TopLevel@=@N@: " + hu); } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\movement\generate\HUMovementGenerator.java
1
请完成以下Java代码
public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setTaxAmt (final BigDecimal TaxAmt) { set_ValueNoCheck (COLUMNNAME_TaxAmt, TaxAmt); } @Override public BigDecimal getTaxAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxAmt); return bd != null ? bd : BigDecimal.ZERO;
} @Override public void setTaxBaseAmt (final BigDecimal TaxBaseAmt) { set_ValueNoCheck (COLUMNNAME_TaxBaseAmt, TaxBaseAmt); } @Override public BigDecimal getTaxBaseAmt() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_TaxBaseAmt); 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_C_InvoiceTax.java
1
请完成以下Java代码
public void setIsInterface (boolean IsInterface) { set_Value (COLUMNNAME_IsInterface, Boolean.valueOf(IsInterface)); } /** Get Interface. @return Interface */ @Override public boolean isInterface () { Object oo = get_Value(COLUMNNAME_IsInterface); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Name.
@param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\javaclasses\model\X_AD_JavaClass.java
1
请完成以下Java代码
class CacheEvaluationContext extends MethodBasedEvaluationContext { private final Set<String> unavailableVariables = new HashSet<String>(1); CacheEvaluationContext(Object rootObject, Method method, Object[] arguments, ParameterNameDiscoverer parameterNameDiscoverer) { super(rootObject, method, arguments, parameterNameDiscoverer); } /** * Add the specified variable name as unavailable for that context. * Any expression trying to access this variable should lead to an exception. * <p>This permits the validation of expressions that could potentially a * variable even when such variable isn't available yet. Any expression * trying to use that variable should therefore fail to evaluate. */
public void addUnavailableVariable(String name) { this.unavailableVariables.add(name); } /** * Load the param information only when needed. */ @Override public Object lookupVariable(String name) { if (this.unavailableVariables.contains(name)) { throw new VariableNotAvailableException(name); } return super.lookupVariable(name); } }
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\expression\CacheEvaluationContext.java
1
请完成以下Java代码
public HuIdsFilterList acceptAll() { return HuIdsFilterList.ALL; } @Override public HuIdsFilterList acceptAllBut(@NonNull final Set<HuId> alwaysIncludeHUIds, @NonNull final Set<HuId> excludeHUIds) { if (excludeHUIds.isEmpty()) { return HuIdsFilterList.ALL; } else { return null; // cannot compute } } @Override public HuIdsFilterList acceptNone() { return HuIdsFilterList.NONE; } @Override public HuIdsFilterList acceptOnly(@NonNull final HuIdsFilterList fixedHUIds, @NonNull final Set<HuId> alwaysIncludeHUIds) { return fixedHUIds; } @Override public HuIdsFilterList huQuery(@NonNull final IHUQueryBuilder initialHUQueryCopy, @NonNull final Set<HuId> alwaysIncludeHUIds, @NonNull final Set<HuId> excludeHUIds) { return null; // cannot compute } }); } public boolean isPossibleHighVolume(final int highVolumeThreshold) { final Integer estimatedSize = estimateSize(); return estimatedSize == null || estimatedSize > highVolumeThreshold; } @Nullable private Integer estimateSize() { return getFixedHUIds().map(HuIdsFilterList::estimateSize).orElse(null); } interface CaseConverter<T> { T acceptAll(); T acceptAllBut(@NonNull Set<HuId> alwaysIncludeHUIds, @NonNull Set<HuId> excludeHUIds); T acceptNone(); T acceptOnly(@NonNull HuIdsFilterList fixedHUIds, @NonNull Set<HuId> alwaysIncludeHUIds); T huQuery(@NonNull IHUQueryBuilder initialHUQueryCopy, @NonNull Set<HuId> alwaysIncludeHUIds, @NonNull Set<HuId> excludeHUIds); }
public synchronized <T> T convert(@NonNull final CaseConverter<T> converter) { if (initialHUQuery == null) { if (initialHUIds == null) { throw new IllegalStateException("initialHUIds shall not be null for " + this); } else if (initialHUIds.isAll()) { if (mustHUIds.isEmpty() && shallNotHUIds.isEmpty()) { return converter.acceptAll(); } else { return converter.acceptAllBut(ImmutableSet.copyOf(mustHUIds), ImmutableSet.copyOf(shallNotHUIds)); } } else { final ImmutableSet<HuId> fixedHUIds = Stream.concat( initialHUIds.stream(), mustHUIds.stream()) .distinct() .filter(huId -> !shallNotHUIds.contains(huId)) // not excluded .collect(ImmutableSet.toImmutableSet()); if (fixedHUIds.isEmpty()) { return converter.acceptNone(); } else { return converter.acceptOnly(HuIdsFilterList.of(fixedHUIds), ImmutableSet.copyOf(mustHUIds)); } } } else { return converter.huQuery(initialHUQuery.copy(), ImmutableSet.copyOf(mustHUIds), ImmutableSet.copyOf(shallNotHUIds)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\filter\HUIdsFilterData.java
1
请完成以下Spring Boot application配置
com: baeldung: twilio: account-sid: ${TWILIO_ACCOUNT_SID} auth-token: ${TWILIO_AUTH_TOKEN} messaging-sid: ${TWILIO_MESSAGING_SID} new-article-
notification: content-sid: ${NEW_ARTICLE_NOTIFICATION_CONTENT_SID}
repos\tutorials-master\saas-modules\twilio-whatsapp\src\main\resources\application.yaml
2
请完成以下Java代码
public BigDecimal getOverUnderAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_OverUnderAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Remaining Amt. @param RemainingAmt Remaining Amount */ public void setRemainingAmt (BigDecimal RemainingAmt) { throw new IllegalArgumentException ("RemainingAmt is virtual column"); } /** Get Remaining Amt. @return Remaining Amount */ public BigDecimal getRemainingAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RemainingAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Write-off Amount. @param WriteOffAmt Amount to write-off */
public void setWriteOffAmt (BigDecimal WriteOffAmt) { set_Value (COLUMNNAME_WriteOffAmt, WriteOffAmt); } /** Get Write-off Amount. @return Amount to write-off */ public BigDecimal getWriteOffAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_WriteOffAmt); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaymentAllocate.java
1
请完成以下Java代码
private void get(Table table) throws IOException { System.out.println("\n*** GET example ~fetching the data in Family1:Qualifier1~ ***"); Get g = new Get(row1); Result r = table.get(g); byte[] value = r.getValue(family1.getBytes(), qualifier1); System.out.println("Fetched value: " + Bytes.toString(value)); assert Arrays.equals(cellData, value); System.out.println("Done. "); } private void put(Admin admin, Table table) throws IOException { System.out.println("\n*** PUT example ~inserting \"cell-data\" into Family1:Qualifier1 of Table1 ~ ***"); // Row1 => Family1:Qualifier1, Family1:Qualifier2 Put p = new Put(row1); p.addImmutable(family1.getBytes(), qualifier1, cellData); p.addImmutable(family1.getBytes(), qualifier2, cellData); table.put(p); // Row2 => Family1:Qualifier1, Family2:Qualifier3 p = new Put(row2); p.addImmutable(family1.getBytes(), qualifier1, cellData); p.addImmutable(family2.getBytes(), qualifier3, cellData); table.put(p); // Row3 => Family1:Qualifier1, Family2:Qualifier3 p = new Put(row3); p.addImmutable(family1.getBytes(), qualifier1, cellData); p.addImmutable(family2.getBytes(), qualifier3, cellData); table.put(p); admin.disableTable(table1); try { HColumnDescriptor desc = new HColumnDescriptor(row1); admin.addColumn(table1, desc); System.out.println("Success."); } catch (Exception e) { System.out.println("Failed."); System.out.println(e.getMessage()); } finally { admin.enableTable(table1); } System.out.println("Done. "); } public void run(Configuration config) throws IOException { try (Connection connection = ConnectionFactory.createConnection(config)) { Admin admin = connection.getAdmin(); if (INITIALIZE_AT_FIRST) { deleteTable(admin);
} if (!admin.tableExists(table1)) { createTable(admin); } Table table = connection.getTable(table1); put(admin, table); get(table); scan(table); filters(table); delete(table); } } private void scan(Table table) throws IOException { System.out.println("\n*** SCAN example ~fetching data in Family1:Qualifier1 ~ ***"); Scan scan = new Scan(); scan.addColumn(family1.getBytes(), qualifier1); try (ResultScanner scanner = table.getScanner(scan)) { for (Result result : scanner) System.out.println("Found row: " + result); } System.out.println("Done."); } }
repos\tutorials-master\persistence-modules\hbase\src\main\java\com\baeldung\hbase\HBaseClientOperations.java
1
请完成以下Java代码
public FormalExpression newInstance(ModelTypeInstanceContext instanceContext) { return new FormalExpressionImpl(instanceContext); } }); languageAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_LANGUAGE) .build(); evaluatesToTypeRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_EVALUATES_TO_TYPE_REF) .qNameAttributeReference(ItemDefinition.class) .build(); typeBuilder.build(); } public FormalExpressionImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public String getLanguage() {
return languageAttribute.getValue(this); } public void setLanguage(String language) { languageAttribute.setValue(this, language); } public ItemDefinition getEvaluatesToType() { return evaluatesToTypeRefAttribute.getReferenceTargetElement(this); } public void setEvaluatesToType(ItemDefinition evaluatesToType) { evaluatesToTypeRefAttribute.setReferenceTargetElement(this, evaluatesToType); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\FormalExpressionImpl.java
1
请完成以下Java代码
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException { this.applicationContext = applicationContext; } public void setBeanName(String name) { this.beanName = name; } @Override public Map<String, String> getProperties() { return properties; } public void setProperties(Map<String, String> properties) { this.properties = properties; } public ApplicationContext getApplicationContext() { return applicationContext; } @Override public void onApplicationEvent(ApplicationContextEvent event) { try { // we only want to listen for context events of the main application // context, not its children if (event.getSource().equals(applicationContext)) { if (event instanceof ContextRefreshedEvent && !isDeployed) { // deploy the process application afterPropertiesSet(); } else if (event instanceof ContextClosedEvent) { // undeploy the process application destroy(); } else { // ignore } }
} catch (Exception e) { throw new RuntimeException(e); } } public void start() { deploy(); } public void stop() { undeploy(); } public void afterPropertiesSet() throws Exception { // for backwards compatibility start(); } public void destroy() throws Exception { // for backwards compatibility stop(); } }
repos\camunda-bpm-platform-master\engine-spring\core\src\main\java\org\camunda\bpm\engine\spring\application\SpringProcessApplication.java
1
请完成以下Java代码
public PageData<NotificationRule> findByTenantId(UUID tenantId, PageLink pageLink) { return DaoUtil.toPageData(notificationRuleRepository.findByTenantId(tenantId, DaoUtil.toPageable(pageLink))); } @Override public NotificationRuleId getExternalIdByInternal(NotificationRuleId internalId) { return DaoUtil.toEntityId(notificationRuleRepository.getExternalIdByInternal(internalId.getId()), NotificationRuleId::new); } @Override public PageData<NotificationRule> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findByTenantId(tenantId.getId(), pageLink); } @Override
protected Class<NotificationRuleEntity> getEntityClass() { return NotificationRuleEntity.class; } @Override protected JpaRepository<NotificationRuleEntity, UUID> getRepository() { return notificationRuleRepository; } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_RULE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\notification\JpaNotificationRuleDao.java
1
请完成以下Java代码
public static List<EngineInfo> getCmmnEngineInfos() { return cmmnEngineInfos; } /** * Get initialization results. Only info will we available for cmmn engines which were added in the {@link CmmnEngines#init()}. No {@link EngineInfo} is available for engines which were registered * programmatically. */ public static EngineInfo getCmmnEngineInfo(String cmmnEngineName) { return cmmnEngineInfosByName.get(cmmnEngineName); } public static CmmnEngine getDefaultCmmnEngine() { return getCmmnEngine(NAME_DEFAULT); } /** * Obtain a cmmn engine by name. * * @param cmmnEngineName * is the name of the cmmn engine or null for the default cmmn engine. */ public static CmmnEngine getCmmnEngine(String cmmnEngineName) { if (!isInitialized()) { init(); } return cmmnEngines.get(cmmnEngineName); } /** * retries to initialize a cmmn engine that previously failed. */ public static EngineInfo retry(String resourceUrl) { LOGGER.debug("retying initializing of resource {}", resourceUrl); try { return initCmmnEngineFromResource(new URL(resourceUrl)); } catch (MalformedURLException e) { throw new FlowableException("invalid url: " + resourceUrl, e); } } /** * provides access to cmmn engine to application clients in a managed server environment. */ public static Map<String, CmmnEngine> getCmmnEngines() { return cmmnEngines; } /** * closes all cmmn engines. This method should be called when the server shuts down. */ public static synchronized void destroy() { if (isInitialized()) { Map<String, CmmnEngine> engines = new HashMap<>(cmmnEngines); cmmnEngines = new HashMap<>();
for (String cmmnEngineName : engines.keySet()) { CmmnEngine cmmnEngine = engines.get(cmmnEngineName); try { cmmnEngine.close(); } catch (Exception e) { LOGGER.error("exception while closing {}", (cmmnEngineName == null ? "the default cmmn engine" : "cmmn engine " + cmmnEngineName), e); } } cmmnEngineInfosByName.clear(); cmmnEngineInfosByResourceUrl.clear(); cmmnEngineInfos.clear(); setInitialized(false); } } public static boolean isInitialized() { return isInitialized; } public static void setInitialized(boolean isInitialized) { CmmnEngines.isInitialized = isInitialized; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\CmmnEngines.java
1
请完成以下Java代码
public class Store { @Id private String id; private String name; public Store() { } public Store(String name) { super(); this.name = name; } 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; } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-mongodb-2\src\main\java\com\baeldung\boot\collection\name\data\Store.java
1
请完成以下Java代码
public class UserDetailVO { /** * 用户编号 */ private Integer id; /** * 账号 */ private String username; /** * 密码(明文) * * ps:生产环境下,千万不要明文噢 */ private String password; /** * 性别 */ private Integer gender; /** * 创建时间 */ private Date createTime; /** * 是否删除 */ @TableLogic private Integer deleted; /** * 租户编号 */ private Integer tenantId; public Integer getId() { return id; } public UserDetailVO setId(Integer id) { this.id = id; return this; } public String getUsername() { return username; } public UserDetailVO setUsername(String username) { this.username = username; return this; } public String getPassword() { return password; }
public UserDetailVO setPassword(String password) { this.password = password; return this; } public Integer getGender() { return gender; } public UserDetailVO setGender(Integer gender) { this.gender = gender; return this; } public Date getCreateTime() { return createTime; } public UserDetailVO setCreateTime(Date createTime) { this.createTime = createTime; return this; } public Integer getDeleted() { return deleted; } public UserDetailVO setDeleted(Integer deleted) { this.deleted = deleted; return this; } public Integer getTenantId() { return tenantId; } public UserDetailVO setTenantId(Integer tenantId) { this.tenantId = tenantId; return this; } @Override public String toString() { return "UserDetailVO{" + "id=" + id + ", username='" + username + '\'' + ", password='" + password + '\'' + ", gender=" + gender + ", createTime=" + createTime + ", deleted=" + deleted + ", tenantId=" + tenantId + '}'; } }
repos\SpringBoot-Labs-master\lab-12-mybatis\lab-12-mybatis-plus-tenant\src\main\java\cn\iocoder\springboot\lab12\mybatis\vo\UserDetailVO.java
1
请完成以下Java代码
public int hashCode() { return Objects.hash( super.hashCode(), id, name, processDefinitionId, processDefinitionKey, initiator, startDate, completedDate, businessKey, status, parentId, processDefinitionVersion, processDefinitionName ); } @Override public String toString() { return ( "ProcessInstance{" + "id='" + id + '\'' + ", name='" + name + '\'' + ", processDefinitionId='" + processDefinitionId + '\'' + ", processDefinitionKey='" + processDefinitionKey + '\'' + ", parentId='" +
parentId + '\'' + ", initiator='" + initiator + '\'' + ", startDate=" + startDate + ", completedDate=" + completedDate + ", businessKey='" + businessKey + '\'' + ", status=" + status + ", processDefinitionVersion='" + processDefinitionVersion + '\'' + ", processDefinitionName='" + processDefinitionName + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-model-impl\src\main\java\org\activiti\api\runtime\model\impl\ProcessInstanceImpl.java
1
请完成以下Java代码
public void setAD_Process_Para_ID (int AD_Process_Para_ID) { if (AD_Process_Para_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Process_Para_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Process_Para_ID, Integer.valueOf(AD_Process_Para_ID)); } /** Get Prozess-Parameter. @return Prozess-Parameter */ @Override public int getAD_Process_Para_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Process_Para_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_Scheduler getAD_Scheduler() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_Scheduler_ID, org.compiere.model.I_AD_Scheduler.class); } @Override public void setAD_Scheduler(org.compiere.model.I_AD_Scheduler AD_Scheduler) { set_ValueFromPO(COLUMNNAME_AD_Scheduler_ID, org.compiere.model.I_AD_Scheduler.class, AD_Scheduler); } /** Set Ablaufsteuerung. @param AD_Scheduler_ID Schedule Processes */ @Override public void setAD_Scheduler_ID (int AD_Scheduler_ID) { if (AD_Scheduler_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_Scheduler_ID, Integer.valueOf(AD_Scheduler_ID)); } /** Get Ablaufsteuerung. @return Schedule Processes */ @Override public int getAD_Scheduler_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_Scheduler_ID); if (ii == null) return 0; return ii.intValue();
} /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Default Parameter. @param ParameterDefault Default value of the parameter */ @Override public void setParameterDefault (java.lang.String ParameterDefault) { set_Value (COLUMNNAME_ParameterDefault, ParameterDefault); } /** Get Default Parameter. @return Default value of the parameter */ @Override public java.lang.String getParameterDefault () { return (java.lang.String)get_Value(COLUMNNAME_ParameterDefault); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Scheduler_Para.java
1
请完成以下Java代码
public <T> void warnUp(final Collection<T> objects, Function<T, ProductId> productIdMapper) { final ImmutableSet<ProductId> productIds = objects.stream().map(productIdMapper).collect(ImmutableSet.toImmutableSet()); getByIds(productIds); } public ProductInfo getById(@NonNull final ProductId productId) { final Collection<ProductInfo> productInfos = getByIds(ImmutableSet.of(productId)); return CollectionUtils.singleElement(productInfos); } private Collection<ProductInfo> getByIds(final Set<ProductId> productIds) { return CollectionUtils.getAllOrLoad(byId, productIds, this::retrieveProductInfos); } private Map<ProductId, ProductInfo> retrieveProductInfos(final Set<ProductId> productIds) {
return productBL.getByIds(productIds) .stream() .map(ProductsLoadingCache::fromRecord) .collect(ImmutableMap.toImmutableMap(ProductInfo::getProductId, productInfo -> productInfo)); } private static ProductInfo fromRecord(final I_M_Product product) { final ProductId productId = ProductId.ofRepoId(product.getM_Product_ID()); final IModelTranslationMap trls = InterfaceWrapperHelper.getModelTranslationMap(product); return ProductInfo.builder() .productId(productId) .productNo(product.getValue()) .productName(trls.getColumnTrl(I_M_Product.COLUMNNAME_Name, product.getName())) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inventory.mobileui\src\main\java\de\metas\inventory\mobileui\deps\products\ProductsLoadingCache.java
1
请完成以下Java代码
public class ActorGsonDeserializer implements JsonDeserializer<ActorGson> { private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX"); @Override public ActorGson deserialize(JsonElement json, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException { final JsonObject jsonObject = json.getAsJsonObject(); final JsonElement jsonImdbId = jsonObject.get("imdbId"); final JsonElement jsonDateOfBirth = jsonObject.get("dateOfBirth"); final JsonArray jsonFilmography = jsonObject.getAsJsonArray("filmography"); final ArrayList<String> filmList = new ArrayList<String>(); if (jsonFilmography != null) {
for (int i = 0; i < jsonFilmography.size(); i++) { filmList.add(jsonFilmography.get(i).getAsString()); } } ActorGson actorGson = null; try { actorGson = new ActorGson(jsonImdbId.getAsString(), sdf.parse(jsonDateOfBirth.getAsString()), filmList); } catch (final ParseException e) { // TODO Auto-generated catch block e.printStackTrace(); } return actorGson; } }
repos\tutorials-master\json-modules\gson\src\main\java\com\baeldung\gson\serialization\ActorGsonDeserializer.java
1
请在Spring Boot框架中完成以下Java代码
public class AuthenticationFilter implements Filter { private static final String HEADER_AUTH_TOKEN = "X-Auth-Token"; private final AuthenticationManager authenticationManager; public AuthenticationFilter(@NotNull final AuthenticationManager authenticationManager) { this.authenticationManager = authenticationManager; } @Override public void doFilter( @NotNull final ServletRequest servletRequest, @NonNull final ServletResponse servletResponse, @NonNull final FilterChain filterChain) throws IOException { final HttpServletRequest httpRequest = (HttpServletRequest)(servletRequest); final HttpServletResponse httpResponse = (HttpServletResponse)(servletResponse);
final String token = httpRequest.getHeader(HEADER_AUTH_TOKEN); try { final PreAuthenticatedAuthenticationToken preAuthenticatedAuthenticationToken = new PreAuthenticatedAuthenticationToken(token, null); final Authentication authentication = authenticationManager.authenticate(preAuthenticatedAuthenticationToken); SecurityContextHolder.getContext().setAuthentication(authentication); filterChain.doFilter(httpRequest, httpResponse); } catch (final Exception authenticationException) { SecurityContextHolder.clearContext(); httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, authenticationException.getMessage()); } } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\core\src\main\java\de\metas\camel\externalsystems\core\restapi\auth\AuthenticationFilter.java
2
请完成以下Java代码
protected boolean beforeDelete() { // Clean own index MIndex.cleanUp(get_TrxName(), getAD_Client_ID(), get_Table_ID(), get_ID()); // Clean ElementIndex MContainerElement[] theseElements = getAllElements(); if (theseElements!=null) { for (int i=0;i<theseElements.length;i++) { theseElements[i].delete(false); } } // StringBuffer sb = new StringBuffer ("DELETE FROM AD_TreeNodeCMC ") .append (" WHERE Node_ID=").append (get_ID ()).append ( " AND AD_Tree_ID=").append (getAD_Tree_ID ()); int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString (), get_TrxName ()); if (no > 0) log.debug("#" + no + " - TreeType=CMC"); else log.warn("#" + no + " - TreeType=CMC"); return no > 0; } /** * After Delete * * @param success * @return deleted */ @Override protected boolean afterDelete (boolean success) { if (!success) return success; // StringBuffer sb = new StringBuffer ("DELETE FROM AD_TreeNodeCMC ") .append (" WHERE Node_ID=").append (get_IDOld ()).append ( " AND AD_Tree_ID=").append (getAD_Tree_ID ()); int no = DB.executeUpdateAndSaveErrorOnFail(sb.toString (), get_TrxName ()); // If 0 than there is nothing to delete which is okay. if (no > 0)
log.debug("#" + no + " - TreeType=CMC"); else log.warn("#" + no + " - TreeType=CMC"); return true; } // afterDelete /** * reIndex * @param newRecord */ public void reIndex(boolean newRecord) { String [] toBeIndexed = new String[8]; toBeIndexed[0] = this.getName(); toBeIndexed[1] = this.getDescription(); toBeIndexed[2] = this.getRelativeURL(); toBeIndexed[3] = this.getMeta_Author(); toBeIndexed[4] = this.getMeta_Copyright(); toBeIndexed[5] = this.getMeta_Description(); toBeIndexed[6] = this.getMeta_Keywords(); toBeIndexed[7] = this.getMeta_Publisher(); MIndex.reIndex (newRecord, toBeIndexed, getCtx(), getAD_Client_ID(), get_Table_ID(), get_ID(), getCM_WebProject_ID(), this.getUpdated()); MContainerElement[] theseElements = getAllElements(); if (theseElements!=null) for (int i=0;i<theseElements.length;i++) theseElements[i].reIndex (false); } // reIndex } // MContainer
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MContainer.java
1
请在Spring Boot框架中完成以下Java代码
boolean addIfAbsent(ItemMetadata metadata) { ItemMetadata existing = find(metadata.getName()); if (existing != null) { return false; } add(metadata); return true; } void add(ItemHint itemHint) { this.metadataHints.add(itemHint); } boolean hasSimilarGroup(ItemMetadata metadata) { if (!metadata.isOfItemType(ItemMetadata.ItemType.GROUP)) { throw new IllegalStateException("item " + metadata + " must be a group"); } for (ItemMetadata existing : this.metadataItems) { if (existing.isOfItemType(ItemMetadata.ItemType.GROUP) && existing.getName().equals(metadata.getName()) && existing.getType().equals(metadata.getType())) { return true; } } return false; } ConfigurationMetadata getMetadata() { ConfigurationMetadata metadata = new ConfigurationMetadata(); for (ItemMetadata item : this.metadataItems) { metadata.add(item); } for (ItemHint metadataHint : this.metadataHints) { metadata.add(metadataHint);
} if (this.previousMetadata != null) { List<ItemMetadata> items = this.previousMetadata.getItems(); for (ItemMetadata item : items) { if (this.mergeRequired.test(item)) { metadata.addIfMissing(item); } } } return metadata; } private ItemMetadata find(String name) { return this.metadataItems.stream() .filter((candidate) -> name.equals(candidate.getName())) .findFirst() .orElse(null); } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\MetadataCollector.java
2
请完成以下Java代码
public void eraseCredentials() { super.eraseCredentials(); this.credentials = null; } public Builder<?> toBuilder() { return new Builder<>(this); } /** * A builder of {@link CasServiceTicketAuthenticationToken} instances * * @since 7.0 */ public static class Builder<B extends Builder<B>> extends AbstractAuthenticationBuilder<B> { private String principal; private @Nullable Object credentials; protected Builder(CasServiceTicketAuthenticationToken token) { super(token); this.principal = token.identifier; this.credentials = token.credentials; } @Override public B principal(@Nullable Object principal) { Assert.isInstanceOf(String.class, principal, "principal must be of type String"); this.principal = (String) principal; return (B) this;
} @Override public B credentials(@Nullable Object credentials) { Assert.notNull(credentials, "credentials cannot be null"); this.credentials = credentials; return (B) this; } @Override public CasServiceTicketAuthenticationToken build() { return new CasServiceTicketAuthenticationToken(this); } } }
repos\spring-security-main\cas\src\main\java\org\springframework\security\cas\authentication\CasServiceTicketAuthenticationToken.java
1
请完成以下Java代码
protected PlanItemInstanceEntityManager getPlanItemInstanceEntityManager() { return cmmnEngineConfiguration.getPlanItemInstanceEntityManager(); } protected SentryPartInstanceEntityManager getSentryPartInstanceEntityManager() { return cmmnEngineConfiguration.getSentryPartInstanceEntityManager(); } protected MilestoneInstanceEntityManager getMilestoneInstanceEntityManager() { return cmmnEngineConfiguration.getMilestoneInstanceEntityManager(); } protected HistoricCaseInstanceEntityManager getHistoricCaseInstanceEntityManager() { return cmmnEngineConfiguration.getHistoricCaseInstanceEntityManager(); } protected HistoricMilestoneInstanceEntityManager getHistoricMilestoneInstanceEntityManager() { return cmmnEngineConfiguration.getHistoricMilestoneInstanceEntityManager(); } protected HistoricPlanItemInstanceEntityManager getHistoricPlanItemInstanceEntityManager() { return cmmnEngineConfiguration.getHistoricPlanItemInstanceEntityManager(); } protected VariableInstanceEntityManager getVariableInstanceEntityManager() { return cmmnEngineConfiguration.getVariableServiceConfiguration().getVariableInstanceEntityManager(); } protected HistoricVariableInstanceEntityManager getHistoricVariableInstanceEntityManager() { return cmmnEngineConfiguration.getVariableServiceConfiguration().getHistoricVariableInstanceEntityManager(); } protected IdentityLinkEntityManager getIdentityLinkEntityManager() { return cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getIdentityLinkEntityManager(); } protected HistoricIdentityLinkEntityManager getHistoricIdentityLinkEntityManager() { return cmmnEngineConfiguration.getIdentityLinkServiceConfiguration().getHistoricIdentityLinkEntityManager();
} protected EntityLinkEntityManager getEntityLinkEntityManager() { return cmmnEngineConfiguration.getEntityLinkServiceConfiguration().getEntityLinkEntityManager(); } protected HistoricEntityLinkEntityManager getHistoricEntityLinkEntityManager() { return cmmnEngineConfiguration.getEntityLinkServiceConfiguration().getHistoricEntityLinkEntityManager(); } protected TaskEntityManager getTaskEntityManager() { return cmmnEngineConfiguration.getTaskServiceConfiguration().getTaskEntityManager(); } protected HistoricTaskLogEntryEntityManager getHistoricTaskLogEntryEntityManager() { return cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskLogEntryEntityManager(); } protected HistoricTaskInstanceEntityManager getHistoricTaskInstanceEntityManager() { return cmmnEngineConfiguration.getTaskServiceConfiguration().getHistoricTaskInstanceEntityManager(); } protected CmmnEngineConfiguration getCmmnEngineConfiguration() { return cmmnEngineConfiguration; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\AbstractCmmnManager.java
1
请完成以下Java代码
public class EntitiesRelatedEntityIdAsyncLoader { public static ListenableFuture<EntityId> findEntityAsync( TbContext ctx, EntityId originator, RelationsQuery relationsQuery ) { var relationService = ctx.getRelationService(); var query = buildQuery(originator, relationsQuery); var relationListFuture = relationService.findByQuery(ctx.getTenantId(), query); if (relationsQuery.getDirection() == EntitySearchDirection.FROM) { return Futures.transformAsync(relationListFuture, relationList -> CollectionUtils.isNotEmpty(relationList) ? Futures.immediateFuture(relationList.get(0).getTo()) : Futures.immediateFuture(null), ctx.getDbCallbackExecutor()); } else if (relationsQuery.getDirection() == EntitySearchDirection.TO) { return Futures.transformAsync(relationListFuture, relationList -> CollectionUtils.isNotEmpty(relationList) ? Futures.immediateFuture(relationList.get(0).getFrom()) : Futures.immediateFuture(null), ctx.getDbCallbackExecutor()); }
return Futures.immediateFailedFuture(new IllegalStateException("Unknown direction")); } private static EntityRelationsQuery buildQuery(EntityId originator, RelationsQuery relationsQuery) { var query = new EntityRelationsQuery(); var parameters = new RelationsSearchParameters( originator, relationsQuery.getDirection(), relationsQuery.getMaxLevel(), relationsQuery.isFetchLastLevelOnly() ); query.setParameters(parameters); query.setFilters(relationsQuery.getFilters()); return query; } }
repos\thingsboard-master\rule-engine\rule-engine-components\src\main\java\org\thingsboard\rule\engine\util\EntitiesRelatedEntityIdAsyncLoader.java
1
请完成以下Java代码
public List<BestellungAuftrag> getAuftraege() { if (auftraege == null) { auftraege = new ArrayList<BestellungAuftrag>(); } return this.auftraege; } /** * Gets the value of the id property. * * @return * possible object is * {@link String } * */ public String getId() { return id; } /** * Sets the value of the id property. * * @param value * allowed object is * {@link String } * */ public void setId(String value) { this.id = value; }
/** * Gets the value of the bestellSupportId property. * */ public int getBestellSupportId() { return bestellSupportId; } /** * Sets the value of the bestellSupportId property. * */ public void setBestellSupportId(int value) { this.bestellSupportId = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v1\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v1\Bestellung.java
1
请完成以下Java代码
public class HUInvoiceHistoryDAO extends AbstractInvoiceHistoryDAO { @Override public String buildStorageInvoiceHistorySQL(final boolean showDetail, final int warehouseId, final int asiId) { final StringBuilder sql = new StringBuilder("SELECT ") .append("s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyOnHand).append(", ") .append("s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyReserved).append(", ") .append("s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyOrdered).append(", ") .append("s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_HUStorageASIKey).append(", ") .append("s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_HUStorageASIKey).append(", ") .append("w.").append(org.compiere.model.I_M_Warehouse.COLUMNNAME_Name).append(", ") .append("l.").append(org.compiere.model.I_M_Locator.COLUMNNAME_Value).append(" "); sql.append("FROM ").append(I_RV_M_HU_Storage_InvoiceHistory.Table_Name).append(" s") .append(" LEFT JOIN ").append(org.compiere.model.I_M_Locator.Table_Name).append(" l ON (s.M_Locator_ID=l.M_Locator_ID)") .append(" LEFT JOIN ").append(org.compiere.model.I_M_Warehouse.Table_Name).append(" w ON (l.M_Warehouse_ID=w.M_Warehouse_ID) ") .append("WHERE M_Product_ID=?");
if (warehouseId != 0) { sql.append(" AND (1=1 OR l.M_Warehouse_ID=?)"); // Note the 1=1; We're mocking the warehouse filter to preserve legacy code and not screw with the prepared statement } if (asiId > 0) { sql.append(" OR GenerateHUStorageASIKey(?)=s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_HUStorageASIKey); // ASI dummy (keep original query by ASI) } sql.append(" AND (s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyOnHand).append("<>0") .append(" OR s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyReserved).append("<>0") .append(" OR s.").append(I_RV_M_HU_Storage_InvoiceHistory.COLUMNNAME_QtyOrdered).append("<>0)"); return sql.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\org\compiere\apps\search\dao\impl\HUInvoiceHistoryDAO.java
1