instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
protected boolean hasLoopCharacteristics() { return hasMultiInstanceCharacteristics(); } protected boolean hasMultiInstanceCharacteristics() { return multiInstanceActivityBehavior != null; } public MultiInstanceActivityBehavior getMultiInstanceActivityBehavior() { return multiInstanceActivityBehavior; } public void setMultiInstanceActivityBehavior(MultiInstanceActivityBehavior multiInstanceActivityBehavior) { this.multiInstanceActivityBehavior = multiInstanceActivityBehavior; } @Override public void signal(ActivityExecution execution, String signalName, Object signalData) throws Exception { if ("compensationDone".equals(signalName)) { signalCompensationDone(execution, signalData); } else { super.signal(execution, signalName, signalData); } }
protected void signalCompensationDone(ActivityExecution execution, Object signalData) { // default behavior is to join compensating executions and propagate the signal if all executions // have compensated // join compensating executions if (execution.getExecutions().isEmpty()) { if (execution.getParent() != null) { ActivityExecution parent = execution.getParent(); ((InterpretableExecution) execution).remove(); ((InterpretableExecution) parent).signal("compensationDone", signalData); } } else { ((ExecutionEntity) execution).forceUpdate(); } } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\bpmn\behavior\AbstractBpmnActivityBehavior.java
1
请完成以下Java代码
public String getBldgNb() { return bldgNb; } /** * Sets the value of the bldgNb property. * * @param value * allowed object is * {@link String } * */ public void setBldgNb(String value) { this.bldgNb = value; } /** * Gets the value of the pstCd property. * * @return * possible object is * {@link String } * */ public String getPstCd() { return pstCd; } /** * Sets the value of the pstCd property. * * @param value * allowed object is * {@link String } * */ public void setPstCd(String value) { this.pstCd = value; } /** * Gets the value of the twnNm property. * * @return * possible object is * {@link String } * */ public String getTwnNm() { return twnNm; } /** * Sets the value of the twnNm property. * * @param value * allowed object is * {@link String } * */ public void setTwnNm(String value) { this.twnNm = value; } /** * Gets the value of the ctrySubDvsn property. * * @return * possible object is * {@link String } * */ public String getCtrySubDvsn() { return ctrySubDvsn; } /** * Sets the value of the ctrySubDvsn property. *
* @param value * allowed object is * {@link String } * */ public void setCtrySubDvsn(String value) { this.ctrySubDvsn = value; } /** * Gets the value of the ctry property. * * @return * possible object is * {@link String } * */ public String getCtry() { return ctry; } /** * Sets the value of the ctry property. * * @param value * allowed object is * {@link String } * */ public void setCtry(String value) { this.ctry = value; } /** * Gets the value of the adrLine property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the adrLine property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAdrLine().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAdrLine() { if (adrLine == null) { adrLine = new ArrayList<String>(); } return this.adrLine; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\PostalAddress6.java
1
请完成以下Java代码
public static void main(String[] args) throws InterruptedException, IOException { JvmMetrics.builder().register(); HTTPServer server = HTTPServer.builder() .port(9400) .buildAndStart(); Counter requestCounter = Counter.builder() .name("http_requests_total") .help("Total number of HTTP requests") .labelNames("method", "status") .register(); requestCounter.labelValues("GET", "200").inc(); Gauge memoryUsage = Gauge.builder() .name("memory_usage_bytes") .help("Current memory usage in bytes") .register(); memoryUsage.set(5000000); Histogram requestLatency = Histogram.builder() .name("http_request_latency_seconds") .help("Tracks HTTP request latency in seconds") .labelNames("method") .register(); Random random = new Random(); for (int i = 0; i < 100; i++) { double latency = 0.1 + (3 * random.nextDouble()); requestLatency.labelValues("GET").observe(latency); } Summary requestDuration = Summary.builder()
.name("http_request_duration_seconds") .help("Tracks the duration of HTTP requests in seconds") .quantile(0.5, 0.05) .quantile(0.9, 0.01) .register(); for (int i = 0; i < 100; i++) { double duration = 0.05 + (2 * random.nextDouble()); requestDuration.observe(duration); } Info appInfo = Info.builder() .name("app_info") .help("Application version information") .labelNames("version", "build") .register(); appInfo.addLabelValues("1.0.0", "12345"); StateSet stateSet = StateSet.builder() .name("feature_flags") .help("Feature flags") .labelNames("env") .states("feature1") .register(); stateSet.labelValues("dev").setFalse("feature1"); System.out.println("HTTPServer listening on http://localhost:" + server.getPort() + "/metrics"); Thread.currentThread().join(); } }
repos\tutorials-master\metrics\src\main\java\com\baeldung\metrics\prometheus\PrometheusApp.java
1
请在Spring Boot框架中完成以下Java代码
public int getSSLPort() { return sslPort; } public void setSSLPort(int sslPort) { this.sslPort = sslPort; } 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 getDefaultFrom() { return defaultFrom; } public void setDefaultFrom(String defaultFrom) { this.defaultFrom = defaultFrom; } public String getForceTo() { return forceTo; } public void setForceTo(String forceTo) { this.forceTo = forceTo;
} public Charset getDefaultCharset() { return defaultCharset; } public void setDefaultCharset(Charset defaultCharset) { this.defaultCharset = defaultCharset; } public boolean isUseSsl() { return useSsl; } public void setUseSsl(boolean useSsl) { this.useSsl = useSsl; } public boolean isUseTls() { return useTls; } public void setUseTls(boolean useTls) { this.useTls = useTls; } }
repos\flowable-engine-main\modules\flowable-spring-boot\flowable-spring-boot-starters\flowable-spring-boot-autoconfigure\src\main\java\org\flowable\spring\boot\FlowableMailProperties.java
2
请完成以下Java代码
default <T extends RepoIdAware> T getParameterAsId(@NonNull String parameterName, @NonNull Class<T> type, @Nullable T defaultValueIfNull) { final T id = getParameterAsId(parameterName, type); return id != null ? id : defaultValueIfNull; } @NonNull default <T extends RepoIdAware> T getParameterAsIdNotNull(@NonNull String parameterName, @NonNull Class<T> type) { final T id = getParameterAsId(parameterName, type); if (id == null) { throw Check.mkEx("Parameter " + parameterName + " is not set"); } return id; } /** * @return boolean value or <code>false</code> if parameter is missing */ boolean getParameterAsBool(String parameterName); @Nullable Boolean getParameterAsBoolean(String parameterName, @Nullable Boolean defaultValue); /** * @return timestamp value or <code>null</code> if parameter is missing */ @Nullable Timestamp getParameterAsTimestamp(String parameterName); /** * @return local date value or <code>null</code> if parameter is missing */ @Nullable LocalDate getParameterAsLocalDate(String parameterName); @Nullable ZonedDateTime getParameterAsZonedDateTime(String parameterName); @Nullable Instant getParameterAsInstant(String parameterName); /** * @return {@link BigDecimal} value or <code>null</code> if parameter is missing or cannot be converted to {@link BigDecimal} */ BigDecimal getParameterAsBigDecimal(String parameterName);
default <T extends Enum<T>> Optional<T> getParameterAsEnum(final String parameterName, final Class<T> enumType) { final String value = getParameterAsString(parameterName); return value != null ? Optional.of(ReferenceListAwareEnums.ofEnumCode(value, enumType)) : Optional.empty(); } @Nullable default Boolean getParameterAsBoolean(@NonNull final String parameterName) { final Object value = getParameterAsObject(parameterName); if (value == null) { return null; } return StringUtils.toBoolean(value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\api\IParams.java
1
请在Spring Boot框架中完成以下Java代码
public Result<String> clearAllUnReadMessage(){ sysAnnouncementService.clearAllUnReadMessage(); return Result.ok("清除未读消息成功"); } /** * 添加访问次数 * @param id * @return */ @RequestMapping(value = "/addVisitsNumber", method = RequestMethod.GET) public Result<?> addVisitsNumber(@RequestParam(name="id",required=true) String id) { int count = oConvertUtils.getInt(redisUtil.get(ANNO_CACHE_KEY+id),0) + 1; redisUtil.set(ANNO_CACHE_KEY+id, count); if (count % 5 == 0) { cachedThreadPool.execute(() -> { sysAnnouncementService.updateVisitsNum(id, count); }); // 重置访问次数 redisUtil.del(ANNO_CACHE_KEY+id); } return Result.ok("公告消息访问次数+1次"); } /** * 批量下载文件 * @param id * @param request * @param response */ @GetMapping("/downLoadFiles") public void downLoadFiles(@RequestParam(name="id") String id, HttpServletRequest request, HttpServletResponse response){ sysAnnouncementService.downLoadFiles(id,request,response); } /**
* 根据异常信息确定友好的错误提示 */ private String determineErrorMessage(Exception e) { String errorMsg = e.getMessage(); if (isSpecialCharacterError(errorMsg)) { return SPECIAL_CHAR_ERROR; } else if (isContentTooLongError(errorMsg)) { return CONTENT_TOO_LONG_ERROR; } else { return DEFAULT_ERROR; } } /** * 判断是否为特殊字符错误 */ private boolean isSpecialCharacterError(String errorMsg) { return errorMsg != null && errorMsg.contains("Incorrect string value") && errorMsg.contains("column 'msg_content'"); } /** * 判断是否为内容过长错误 */ private boolean isContentTooLongError(String errorMsg) { return errorMsg != null && errorMsg.contains("Data too long for column 'msg_content'"); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\controller\SysAnnouncementController.java
2
请完成以下Java代码
public class EmailValidator { /** * Validate email using apache commons validator * * @param email email address for validation */ public static boolean validate(@Nullable final String email) { return validate(email, null); } /** * @param clazz optional, may be {@code null}. If a class is given and the given {@code email} is not valid, * then this method instantiates and throws an exception with message {@code "@EmailNotValid@"}. */ public static boolean validate(@Nullable final String email, @Nullable final Class<? extends RuntimeException> clazz) { final boolean emailValid = isValid(email); if (!emailValid && clazz != null) { // initiate and throw our exception
try { throw clazz.getConstructor(String.class).newInstance("@EmailNotValid@"); } catch (final InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException | SecurityException e) { throw new RuntimeException("Unable to instantiate a " + clazz + " exception", e); } } return emailValid; } public static boolean isValid(@Nullable final String email) { return org.apache.commons.validator.routines.EmailValidator.getInstance().isValid(email); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\org\adempiere\util\email\EmailValidator.java
1
请完成以下Java代码
public void setProductValue (final @Nullable java.lang.String ProductValue) { set_ValueNoCheck (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setSKU (final @Nullable java.lang.String SKU) { set_ValueNoCheck (COLUMNNAME_SKU, SKU); }
@Override public java.lang.String getSKU() { return get_ValueAsString(COLUMNNAME_SKU); } @Override public void setUPC (final @Nullable java.lang.String UPC) { set_ValueNoCheck (COLUMNNAME_UPC, UPC); } @Override public java.lang.String getUPC() { return get_ValueAsString(COLUMNNAME_UPC); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Details_v.java
1
请完成以下Java代码
public String getEndanwenderFehlertext() { return endanwenderFehlertext; } /** * Sets the value of the endanwenderFehlertext property. * * @param value * allowed object is * {@link String } * */ public void setEndanwenderFehlertext(String value) { this.endanwenderFehlertext = value; } /** * Gets the value of the technischerFehlertext property. * * @return * possible object is
* {@link String } * */ public String getTechnischerFehlertext() { return technischerFehlertext; } /** * Sets the value of the technischerFehlertext property. * * @param value * allowed object is * {@link String } * */ public void setTechnischerFehlertext(String value) { this.technischerFehlertext = 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\Msv3FaultInfo.java
1
请完成以下Java代码
public class SmsHomeBrand implements Serializable { private Long id; private Long brandId; private String brandName; private Integer recommendStatus; private Integer sort; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Long getBrandId() { return brandId; } public void setBrandId(Long brandId) { this.brandId = brandId; } public String getBrandName() { return brandName; } public void setBrandName(String brandName) { this.brandName = brandName; } public Integer getRecommendStatus() { return recommendStatus; }
public void setRecommendStatus(Integer recommendStatus) { this.recommendStatus = recommendStatus; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } @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(", brandId=").append(brandId); sb.append(", brandName=").append(brandName); sb.append(", recommendStatus=").append(recommendStatus); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsHomeBrand.java
1
请完成以下Java代码
public String getAddressLine1() { return addressLine1; } public String getAddressLine2() { return addressLine2; } public String getCity() { return city; } public String getCountry() { return country; } public int getZipCode() { return zipCode; } public void setAddressLine1(String addressLine1) { this.addressLine1 = addressLine1; } public void setAddressLine2(String addressLine2) { this.addressLine2 = addressLine2; } public void setCity(String city) { this.city = city; } public void setCountry(String country) { this.country = country; } public void setZipCode(int zipCode) { this.zipCode = zipCode;
} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Address address = (Address) o; return zipCode == address.zipCode && Objects.equals(addressLine1, address.addressLine1) && Objects.equals(addressLine2, address.addressLine2) && Objects.equals(city, address.city) && Objects.equals(country, address.country); } @Override public int hashCode() { return Objects.hash(addressLine1, addressLine2, city, country, zipCode); } }
repos\tutorials-master\persistence-modules\hibernate-annotations\src\main\java\com\baeldung\hibernate\customtypes\Address.java
1
请完成以下Java代码
public class BearerAuthenticationReader implements GrpcAuthenticationReader { private static final String PREFIX = BEARER_AUTH_PREFIX.toLowerCase(); private static final int PREFIX_LENGTH = PREFIX.length(); private Function<String, Authentication> tokenWrapper; /** * Creates a new BearerAuthenticationReader with the given wrapper function. * <p> * <b>Example-Usage:</b> * </p> * * For spring-security-web: * * <pre> * <code>new BearerAuthenticationReader(token -&gt; new PreAuthenticatedAuthenticationToken(token, null))</code> * </pre> * * For spring-security-oauth2-resource-server: * * <pre> * <code>new BearerAuthenticationReader(token -&gt; new BearerTokenAuthenticationToken(token))</code> * </pre> * * @param tokenWrapper The function used to convert the token (without bearer prefix) into an {@link Authentication} * object. */ public BearerAuthenticationReader(Function<String, Authentication> tokenWrapper) { Assert.notNull(tokenWrapper, "tokenWrapper cannot be null"); this.tokenWrapper = tokenWrapper; }
@Override public Authentication readAuthentication(final ServerCall<?, ?> call, final Metadata headers) { final String header = headers.get(AUTHORIZATION_HEADER); if (header == null || !header.toLowerCase().startsWith(PREFIX)) { log.debug("No bearer auth header found"); return null; } // Cut away the "bearer " prefix final String accessToken = header.substring(PREFIX_LENGTH); // Not authenticated yet, token needs to be processed return tokenWrapper.apply(accessToken); } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\authentication\BearerAuthenticationReader.java
1
请完成以下Java代码
public static MAccount getAccount (int C_Charge_ID, AcctSchemaId acctSchemaId, BigDecimal amount) { if (C_Charge_ID == 0 || acctSchemaId == null) return null; String acctName = X_C_Charge_Acct.COLUMNNAME_Ch_Expense_Acct; // Expense (positive amt) if (amount != null && amount.signum() < 0) acctName = X_C_Charge_Acct.COLUMNNAME_Ch_Revenue_Acct; // Revenue (negative amt) String sql = "SELECT "+acctName+" FROM C_Charge_Acct WHERE C_Charge_ID=? AND C_AcctSchema_ID=?"; int Account_ID = DB.getSQLValueEx(null, sql, C_Charge_ID, acctSchemaId); // No account if (Account_ID <= 0) { s_log.error("NO account for C_Charge_ID=" + C_Charge_ID); return null; } // Return Account MAccount acct = Services.get(IAccountDAO.class).getById(Account_ID); return acct; } // getAccount /** * Get MCharge from Cache * @param ctx context * @param C_Charge_ID id * @return MCharge */ public static MCharge get (Properties ctx, int C_Charge_ID) { Integer key = new Integer (C_Charge_ID); MCharge retValue = s_cache.get (key); if (retValue != null) return retValue; retValue = new MCharge (ctx, C_Charge_ID, null); if (retValue.get_ID() != 0) s_cache.put (key, retValue); return retValue; } // get /** Cache */ private static CCache<Integer, MCharge> s_cache = new CCache<> ("C_Charge", 10); /** Static Logger */ private static Logger s_log = LogManager.getLogger(MCharge.class); /************************************************************************** * Standard Constructor * @param ctx context * @param C_Charge_ID id * @param trxName transaction */ public MCharge (Properties ctx, int C_Charge_ID, String trxName) { super (ctx, C_Charge_ID, trxName);
if (C_Charge_ID == 0) { setChargeAmt (Env.ZERO); setIsSameCurrency (false); setIsSameTax (false); setIsTaxIncluded (false); // N // setName (null); // setC_TaxCategory_ID (0); } } // MCharge /** * Load Constructor * @param ctx ctx * @param rs result set * @param trxName transaction */ public MCharge (Properties ctx, ResultSet rs, String trxName) { super(ctx, rs, trxName); } // MCharge /** * After Save * @param newRecord new * @param success success * @return success */ @Override protected boolean afterSave (boolean newRecord, boolean success) { if (newRecord && success) insert_Accounting("C_Charge_Acct", "C_AcctSchema_Default", null); return success; } // afterSave /** * Before Delete * @return true */ @Override protected boolean beforeDelete () { return delete_Accounting("C_Charge_Acct"); } // beforeDelete } // MCharge
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\model\MCharge.java
1
请完成以下Java代码
public class SetCacheDirectivesByMaxAgeAfterCacheExchangeMutator implements AfterCacheExchangeMutator { final Pattern MAX_AGE_PATTERN = Pattern.compile("(?:,|^)\\s*max-age=(\\d+)"); @Override public void accept(ServerWebExchange exchange, CachedResponse cachedResponse) { Optional<Integer> maxAge = Optional.ofNullable(exchange.getResponse().getHeaders().getCacheControl()) .map(MAX_AGE_PATTERN::matcher) .filter(Matcher::find) .map(matcher -> matcher.group(1)) .map(Integer::parseInt); if (maxAge.isPresent()) { if (maxAge.get() > 0) { removeNoCacheHeaders(exchange); } else { keepNoCacheHeaders(exchange); } } } private void keepNoCacheHeaders(ServerWebExchange exchange) { // at least it contains 'max-age' so we can append items with commas safely String cacheControl = exchange.getResponse().getHeaders().getCacheControl();
StringBuilder newCacheControl = new StringBuilder(cacheControl); if (!cacheControl.contains("no-cache")) { newCacheControl.append(",no-cache"); } if (!cacheControl.contains("must-revalidate")) { newCacheControl.append(",must-revalidate"); } exchange.getResponse().getHeaders().setCacheControl(newCacheControl.toString()); } private void removeNoCacheHeaders(ServerWebExchange exchange) { String cacheControl = exchange.getResponse().getHeaders().getCacheControl(); List<String> cacheControlValues = Arrays.asList(cacheControl.split("\\s*,\\s*")); String newCacheControl = cacheControlValues.stream() .filter(s -> !s.matches("must-revalidate|no-cache|no-store")) .collect(Collectors.joining(",")); exchange.getResponse().getHeaders().setCacheControl(newCacheControl); } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\postprocessor\SetCacheDirectivesByMaxAgeAfterCacheExchangeMutator.java
1
请完成以下Java代码
public List<String> downloadAttachments(Message message) throws IOException, MessagingException { List<String> downloadedAttachments = new ArrayList<String>(); Multipart multiPart = (Multipart) message.getContent(); int numberOfParts = multiPart.getCount(); for (int partCount = 0; partCount < numberOfParts; partCount++) { MimeBodyPart part = (MimeBodyPart) multiPart.getBodyPart(partCount); if (Part.ATTACHMENT.equalsIgnoreCase(part.getDisposition())) { String file = part.getFileName(); part.saveFile(downloadDirectory + File.separator + part.getFileName()); downloadedAttachments.add(file); } } return downloadedAttachments; } public Store setSessionStoreProperties(String userName, String password, Properties properties) throws MessagingException { Session session = Session.getDefaultInstance(properties); Store store = session.getStore("pop3"); store.connect(userName, password); return store; } public Properties setMailServerProperties(String host, String port) { Properties properties = new Properties(); properties.put("mail.pop3.host", host); properties.put("mail.pop3.port", port);
properties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.setProperty("mail.pop3.socketFactory.fallback", "false"); properties.setProperty("mail.pop3.socketFactory.port", String.valueOf(port)); return properties; } public static void main(String[] args) { String host = "pop.gmail.com"; String port = "995"; String userName = "your_email"; String password = "your_password"; String saveDirectory = "valid_folder_path"; DownloadEmailAttachments receiver = new DownloadEmailAttachments(); receiver.setSaveDirectory(saveDirectory); try { receiver.downloadEmailAttachments(host, port, userName, password); } catch (NoSuchProviderException ex) { System.out.println("No provider for pop3."); ex.printStackTrace(); } catch (MessagingException ex) { System.out.println("Could not connect to the message store"); ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }
repos\tutorials-master\core-java-modules\core-java-networking-3\src\main\java\com\baeldung\downloadattachments\DownloadEmailAttachments.java
1
请完成以下Java代码
public class StringDictionaryMaker { /** * 加载词典 * @param path * @param separator * @return */ public static StringDictionary load(String path, String separator) { StringDictionary dictionary = new StringDictionary(separator); if (dictionary.load(path)) return dictionary; return null; } /** * 加载词典 * @param path * @return */ public static StringDictionary load(String path) { return load(path, "="); } /** * 合并词典,第一个为主词典 * @param args * @return */ public static StringDictionary combine(StringDictionary... args) { StringDictionary[] dictionaries = args.clone();
StringDictionary mainDictionary = dictionaries[0]; for (int i = 1; i < dictionaries.length; ++i) { mainDictionary.combine(dictionaries[i]); } return mainDictionary; } public static StringDictionary combine(String... args) { String[] pathArray = args.clone(); List<StringDictionary> dictionaryList = new LinkedList<StringDictionary>(); for (String path : pathArray) { StringDictionary dictionary = load(path); if (dictionary == null) continue; dictionaryList.add(dictionary); } return combine(dictionaryList.toArray(new StringDictionary[0])); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\dictionary\StringDictionaryMaker.java
1
请完成以下Java代码
public class AppendCharAtPositionX { public String addCharUsingCharArray(String str, char ch, int position) { validate(str, position); int len = str.length(); char[] updatedArr = new char[len + 1]; str.getChars(0, position, updatedArr, 0); updatedArr[position] = ch; str.getChars(position, len, updatedArr, position + 1); return new String(updatedArr); } public String addCharUsingSubstring(String str, char ch, int position) { validate(str, position); return str.substring(0, position) + ch + str.substring(position); } public String addCharUsingStringBuilder(String str, char ch, int position) { validate(str, position);
StringBuilder sb = new StringBuilder(str); sb.insert(position, ch); return sb.toString(); } private void validate(String str, int position) { if (str == null) { throw new IllegalArgumentException("Str should not be null"); } int len = str.length(); if (position < 0 || position > len) { throw new IllegalArgumentException("position[" + position + "] should be " + "in the range 0.." + len + " for string " + str); } } }
repos\tutorials-master\core-java-modules\core-java-string-algorithms-2\src\main\java\com\baeldung\addchar\AppendCharAtPositionX.java
1
请完成以下Java代码
public static boolean equalsByCompareTo(@Nullable final BigDecimal value1, @Nullable final BigDecimal value2) { //noinspection NumberEquality return (value1 == value2) || (value1 != null && value1.compareTo(value2) == 0); } @SafeVarargs public static int firstNonZero(final Supplier<Integer>... suppliers) { if (suppliers == null || suppliers.length == 0) { return 0; } for (final Supplier<Integer> supplier : suppliers) { if (supplier == null) { continue;
} final Integer value = supplier.get(); if (value != null && value != 0) { return value; } } return 0; } @NonNull public static BigDecimal roundTo5Cent(@NonNull final BigDecimal initialValue) { final BigDecimal multiplyBy20 = initialValue.multiply(TWENTY); final BigDecimal intPart = multiplyBy20.setScale(0, RoundingMode.HALF_UP); return intPart.divide(TWENTY); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util\src\main\java\de\metas\util\NumberUtils.java
1
请完成以下Java代码
public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } // /** PaymentRule AD_Reference_ID=214 */ // public static final int PAYMENTRULE_AD_Reference_ID=214; // /** Credit Card = C */ // public static final String PAYMENTRULE_CreditCard = "C"; // /** Check = K */ // public static final String PAYMENTRULE_Check = "K"; // /** Direct Deposit = A */ // public static final String PAYMENTRULE_DirectDeposit = "A"; // /** Direct Debit = D */ // public static final String PAYMENTRULE_DirectDebit = "D"; // /** Account = T */ // public static final String PAYMENTRULE_Account = "T"; // /** Cash = X */ // public static final String PAYMENTRULE_Cash = "X"; /** Set Payment Rule. @param PaymentRule How you pay the invoice */ @Override public void setPaymentRule (String PaymentRule) { set_Value (COLUMNNAME_PaymentRule, PaymentRule); } /** Get Payment Rule. @return How you pay the invoice */ @Override public String getPaymentRule () { return (String)get_Value(COLUMNNAME_PaymentRule); } /** Set Processed. @param Processed The document has been processed */ @Override public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ @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 Process Now. @param Processing Process Now */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing));
} /** Get Process Now. @return Process Now */ @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 Search Key. @param Value Search key for the record in the format required - must be unique */ @Override public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ @Override public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Payroll.java
1
请在Spring Boot框架中完成以下Java代码
public int hashCode() { return Objects.hash(amount, refundDate, refundId, refundReferenceId); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class LineItemRefund {\n"); sb.append(" amount: ").append(toIndentedString(amount)).append("\n"); sb.append(" refundDate: ").append(toIndentedString(refundDate)).append("\n"); sb.append(" refundId: ").append(toIndentedString(refundId)).append("\n"); sb.append(" refundReferenceId: ").append(toIndentedString(refundReferenceId)).append("\n"); sb.append("}"); return sb.toString();
} /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\LineItemRefund.java
2
请完成以下Java代码
public class RestJsonConverter { private static final String KEY = "key"; private static final String VALUE = "value"; private static final String LAST_UPDATE_TS = "lastUpdateTs"; private static final String TS = "ts"; private static final String CAN_T_PARSE_VALUE = "Can't parse value: "; public static List<AttributeKvEntry> toAttributes(List<JsonNode> attributes) { if (!CollectionUtils.isEmpty(attributes)) { return attributes.stream().map(attr -> { KvEntry entry = parseValue(attr.get(KEY).asText(), attr.get(VALUE)); return new BaseAttributeKvEntry(entry, attr.get(LAST_UPDATE_TS).asLong()); } ).collect(Collectors.toList()); } else { return Collections.emptyList(); } } public static List<TsKvEntry> toTimeseries(Map<String, List<JsonNode>> timeseries) { if (!CollectionUtils.isEmpty(timeseries)) { List<TsKvEntry> result = new ArrayList<>(); timeseries.forEach((key, values) -> result.addAll(values.stream().map(ts -> { KvEntry entry = parseValue(key, ts.get(VALUE)); return new BasicTsKvEntry(ts.get(TS).asLong(), entry); } ).toList()) ); return result; } else { return Collections.emptyList(); } }
private static KvEntry parseValue(String key, JsonNode value) { if (!value.isContainerNode()) { if (value.isBoolean()) { return new BooleanDataEntry(key, value.asBoolean()); } else if (value.isNumber()) { return parseNumericValue(key, value); } else if (value.isTextual()) { return new StringDataEntry(key, value.asText()); } else { throw new RuntimeException(CAN_T_PARSE_VALUE + value); } } else { return new JsonDataEntry(key, value.toString()); } } private static KvEntry parseNumericValue(String key, JsonNode value) { if (value.isFloatingPointNumber()) { return new DoubleDataEntry(key, value.asDouble()); } else { try { long longValue = Long.parseLong(value.toString()); return new LongDataEntry(key, longValue); } catch (NumberFormatException e) { throw new IllegalArgumentException("Big integer values are not supported!"); } } } }
repos\thingsboard-master\rest-client\src\main\java\org\thingsboard\rest\client\utils\RestJsonConverter.java
1
请完成以下Java代码
final class ObjectToInstantConverter implements GenericConverter { @Override public Set<ConvertiblePair> getConvertibleTypes() { return Collections.singleton(new ConvertiblePair(Object.class, Instant.class)); } @Override public Object convert(Object source, TypeDescriptor sourceType, TypeDescriptor targetType) { if (source == null) { return null; } if (source instanceof Instant) { return source; } if (source instanceof Date) { return ((Date) source).toInstant(); } if (source instanceof Number) {
return Instant.ofEpochSecond(((Number) source).longValue()); } try { return Instant.ofEpochSecond(Long.parseLong(source.toString())); } catch (Exception ex) { // Ignore } try { return Instant.parse(source.toString()); } catch (Exception ex) { // Ignore } return null; } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\converter\ObjectToInstantConverter.java
1
请完成以下Java代码
public SignalEventListenerInstanceQuery stageInstanceId(String stageInstanceId) { innerQuery.stageInstanceId(stageInstanceId); return this; } @Override public SignalEventListenerInstanceQuery stateAvailable() { innerQuery.planItemInstanceStateAvailable(); return this; } @Override public SignalEventListenerInstanceQuery stateSuspended() { innerQuery.planItemInstanceState(PlanItemInstanceState.SUSPENDED); return this; } @Override public SignalEventListenerInstanceQuery orderByName() { innerQuery.orderByName(); return this; } @Override public SignalEventListenerInstanceQuery asc() { innerQuery.asc(); return this; } @Override public SignalEventListenerInstanceQuery desc() { innerQuery.desc(); return this; } @Override public SignalEventListenerInstanceQuery orderBy(QueryProperty property) { innerQuery.orderBy(property); return this; } @Override public SignalEventListenerInstanceQuery orderBy(QueryProperty property, NullHandlingOnOrder nullHandlingOnOrder) { innerQuery.orderBy(property, nullHandlingOnOrder); return this; } @Override public long count() { return innerQuery.count();
} @Override public SignalEventListenerInstance singleResult() { PlanItemInstance instance = innerQuery.singleResult(); return SignalEventListenerInstanceImpl.fromPlanItemInstance(instance); } @Override public List<SignalEventListenerInstance> list() { return convertPlanItemInstances(innerQuery.list()); } @Override public List<SignalEventListenerInstance> listPage(int firstResult, int maxResults) { return convertPlanItemInstances(innerQuery.listPage(firstResult, maxResults)); } protected List<SignalEventListenerInstance> convertPlanItemInstances(List<PlanItemInstance> instances) { if (instances == null) { return null; } return instances.stream().map(SignalEventListenerInstanceImpl::fromPlanItemInstance).collect(Collectors.toList()); } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\runtime\SignalEventListenerInstanceQueryImpl.java
1
请完成以下Java代码
/* package */ boolean isEmpty() { return (gridLayout == null || !gridLayout.hasElements()) && (singleRowLayout == null || singleRowLayout.isEmpty()); } public Builder queryOnActivate(final boolean queryOnActivate) { this.queryOnActivate = queryOnActivate; return this; } public Builder quickInputSupport(@Nullable final QuickInputSupportDescriptor quickInputSupport) { this.quickInputSupport = quickInputSupport; return this; } @Nullable public QuickInputSupportDescriptor getQuickInputSupport() { return quickInputSupport; } public Builder caption(@NonNull final ITranslatableString caption) { this.caption = caption; return this; } public Builder description(@NonNull final ITranslatableString description) {
this.description = description; return this; } public Builder addSubTabLayout(@NonNull final DocumentLayoutDetailDescriptor subTabLayout) { this.subTabLayouts.add(subTabLayout); return this; } public Builder addAllSubTabLayouts(@NonNull final List<DocumentLayoutDetailDescriptor> subTabLayouts) { this.subTabLayouts.addAll(subTabLayouts); return this; } public Builder newRecordInputMode(@NonNull final IncludedTabNewRecordInputMode newRecordInputMode) { this.newRecordInputMode = newRecordInputMode; return this; } private IncludedTabNewRecordInputMode getNewRecordInputModeEffective() { final boolean hasQuickInputSupport = getQuickInputSupport() != null; return newRecordInputMode.orCompatibleIfAllowQuickInputIs(hasQuickInputSupport); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\DocumentLayoutDetailDescriptor.java
1
请完成以下Java代码
public void onGetAttributesResponse(GetAttributeResponseMsg msg) { responseWriter.setResult(new ResponseEntity<>(JsonConverter.toJson(msg).toString(), HttpStatus.OK)); } @Override public void onAttributeUpdate(UUID sessionId, AttributeUpdateNotificationMsg msg) { log.trace("[{}] Received attributes update notification to device", sessionId); responseWriter.setResult(new ResponseEntity<>(JsonConverter.toJson(msg).toString(), HttpStatus.OK)); } @Override public void onRemoteSessionCloseCommand(UUID sessionId, SessionCloseNotificationProto sessionCloseNotification) { log.trace("[{}] Received the remote command to close the session: {}", sessionId, sessionCloseNotification.getMessage()); responseWriter.setResult(new ResponseEntity<>(HttpStatus.REQUEST_TIMEOUT)); } @Override public void onToDeviceRpcRequest(UUID sessionId, ToDeviceRpcRequestMsg msg) { log.trace("[{}] Received RPC command to device", sessionId); responseWriter.setResult(new ResponseEntity<>(JsonConverter.toJson(msg, true).toString(), HttpStatus.OK)); transportService.process(sessionInfo, msg, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY); } @Override public void onToServerRpcResponse(ToServerRpcResponseMsg msg) { responseWriter.setResult(new ResponseEntity<>(JsonConverter.toJson(msg).toString(), HttpStatus.OK));
} @Override public void onDeviceDeleted(DeviceId deviceId) { UUID sessionId = new UUID(sessionInfo.getSessionIdMSB(), sessionInfo.getSessionIdLSB()); log.trace("[{}] Received device deleted notification for device with id: {}",sessionId, deviceId); responseWriter.setResult(new ResponseEntity<>("Device was deleted!", HttpStatus.FORBIDDEN)); } } private static MediaType parseMediaType(String contentType) { try { return MediaType.parseMediaType(contentType); } catch (Exception e) { return MediaType.APPLICATION_OCTET_STREAM; } } @Override public String getName() { return DataConstants.HTTP_TRANSPORT_NAME; } }
repos\thingsboard-master\common\transport\http\src\main\java\org\thingsboard\server\transport\http\DeviceApiController.java
1
请完成以下Java代码
public class EmptyMapInitializer { public static Map<String, String> articleMap; static { articleMap = new HashMap<>(); } public static Map<String, String> createEmptyMap() { return Collections.emptyMap(); } public void createMapUsingConstructors() { Map hashMap = new HashMap(); Map linkedHashMap = new LinkedHashMap(); Map treeMap = new TreeMap(); } public Map<String, String> createEmptyMapUsingMapsObject() { Map<String, String> emptyMap = Maps.newHashMap(); return emptyMap; } public Map createGenericEmptyMapUsingGuavaMapsObject() { Map genericEmptyMap = Maps.<String, Integer>newHashMap(); return genericEmptyMap; } public static Map<String, String> createMapUsingGuava() { Map<String, String> emptyMapUsingGuava = Maps.newHashMap(ImmutableMap.of()); return emptyMapUsingGuava;
} public static Map<String, String> createImmutableMapUsingGuava() { Map<String, String> emptyImmutableMapUsingGuava = ImmutableMap.of(); return emptyImmutableMapUsingGuava; } public SortedMap<String, String> createEmptySortedMap() { SortedMap<String, String> sortedMap = Collections.emptySortedMap(); return sortedMap; } public NavigableMap<String, String> createEmptyNavigableMap() { NavigableMap<String, String> navigableMap = Collections.emptyNavigableMap(); return navigableMap; } }
repos\tutorials-master\core-java-modules\core-java-collections-maps-3\src\main\java\com\baeldung\map\emptymap\EmptyMapInitializer.java
1
请完成以下Java代码
public class EventSource<ET> implements Iterator<ET>, IAutoCloseable { private static final String COLUMNNAME_Processed = "Processed"; // services protected final transient IQueryBL queryBL = Services.get(IQueryBL.class); protected final transient ILockManager lockManager = Services.get(ILockManager.class); // Params private final Properties ctx; private final Class<ET> eventTypeClass; // State private final AtomicBoolean _closed = new AtomicBoolean(false); private ILock _lock; private Iterator<ET> _iterator; public EventSource( @NonNull final Properties ctx, @NonNull final Class<ET> eventTypeClass) { this.ctx = ctx; this.eventTypeClass = eventTypeClass; } @Override public ET next() { return getCreateIterator().next(); } @Override public boolean hasNext() { return getCreateIterator().hasNext(); } @Override public void remove() { getCreateIterator().remove(); } private void assertNotClosed() { Check.assume(!_closed.get(), "Source is not already closed"); } private Iterator<ET> getCreateIterator() { assertNotClosed(); if (_iterator == null) { final ILock lock = getOrAcquireLock(); final Object contextProvider = PlainContextAware.newWithThreadInheritedTrx(ctx); _iterator = queryBL.createQueryBuilder(eventTypeClass, contextProvider) .filter(lockManager.getLockedByFilter(eventTypeClass, lock)) .addOnlyActiveRecordsFilter() // .orderBy() .addColumn(InterfaceWrapperHelper.getKeyColumnName(eventTypeClass)) .endOrderBy() // .create() .iterate(eventTypeClass); } return _iterator; }
private ILock getOrAcquireLock() { assertNotClosed(); if (_lock == null) { final IQueryFilter<ET> filter = createFilter(); final LockOwner lockOwner = LockOwner.newOwner(getClass().getSimpleName()); _lock = lockManager.lock() .setOwner(lockOwner) .setAutoCleanup(true) .setFailIfNothingLocked(false) .setRecordsByFilter(eventTypeClass, filter) .acquire(); } return _lock; } protected IQueryFilter<ET> createFilter() { return queryBL.createCompositeQueryFilter(eventTypeClass) .addOnlyActiveRecordsFilter() .addOnlyContextClient(ctx) .addEqualsFilter(COLUMNNAME_Processed, false) .addFilter(lockManager.getNotLockedFilter(eventTypeClass)); } @Override public void close() { // Mark this source as closed if (_closed.getAndSet(true)) { // already closed return; } // // Unlock all if (_lock != null) { _lock.close(); _lock = null; } // // Close iterator if (_iterator != null) { IteratorUtils.closeQuietly(_iterator); _iterator = null; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java\de\metas\procurement\base\event\impl\EventSource.java
1
请完成以下Java代码
private boolean existsFunction(final String functionName) throws SQLException { // FIXME I get following error => returning always false // ===========> AD_Index_Create.process: // com.mchange.v2.c3p0.impl.NewProxyDatabaseMetaData.getFunctions(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/sql/ResultSet; // [20] // java.lang.AbstractMethodError: // com.mchange.v2.c3p0.impl.NewProxyDatabaseMetaData.getFunctions(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/sql/ResultSet; // at // org.adempiere.process.AD_Index_Create.existsFunction(AD_Index_Create.java:162) return true; /* * final DatabaseMetaData md = Trx.get(get_TrxName(), * true).getConnection().getMetaData(); if * (md.storesUpperCaseIdentifiers()) functionName = * functionName.toUpperCase(); else if (md.storesLowerCaseIdentifiers()) * functionName = functionName.toLowerCase(); final String catalog = * "REFERENCE"; final String schema = null; ResultSet rs = null; try { * rs = md.getFunctions(catalog, schema, functionName); while(rs.next()) * { String name = rs.getString("FUNCTION_NAME"); if * (name.equalsIgnoreCase(functionName)) return true; } } finally { * DB.close(rs); rs = null; } return false; */ } private void executeDDL(final String sql, final String trxName) { executeDDL(sql, false, trxName); } private void executeDDL(final String sql, final boolean ignoreError, final String trxName) { if (ignoreError) { if (DB.executeUpdateAndSaveErrorOnFail(sql, trxName) != -1) { addLog(sql + ";"); } } else { DB.executeUpdateAndThrowExceptionOnFail(sql, trxName); addLog(sql + ";"); } } private static final boolean equalsIgnoreCase(final String s, final String s2) { if (s == s2) { return true; } if (s == null || s2 == null) { return false; } return s.trim().equalsIgnoreCase(s2.trim()); }
private static final boolean equalsIgnoreCase(final Set<String> a1, final Set<String> a2) { if (a1 == a2) { return true; } if (a1 == null || a2 == null) { return false; } if (a1.size() != a2.size()) { return false; } return Objects.equals(toUpperCase(a1), toUpperCase(a2)); } private static Set<String> toUpperCase(final Set<String> set) { return set.stream().map(String::toUpperCase).collect(ImmutableSet.toImmutableSet()); } private static class DBIndex { public String name; public boolean isUnique = true; public Set<String> columnNames; public String filterCondition = null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\adempiere\process\AD_Index_Create.java
1
请在Spring Boot框架中完成以下Java代码
protected BatchServiceConfiguration getService() { return this; } // init // ///////////////////////////////////////////////////////////////////// public void init() { configuratorsBeforeInit(); initDataManagers(); initEntityManagers(); configuratorsAfterInit(); } // Data managers /////////////////////////////////////////////////////////// public void initDataManagers() { if (batchDataManager == null) { batchDataManager = new MybatisBatchDataManager(this); } if (batchPartDataManager == null) { batchPartDataManager = new MybatisBatchPartDataManager(this); } } public void initEntityManagers() { if (batchEntityManager == null) { batchEntityManager = new BatchEntityManagerImpl(this, batchDataManager); } if (batchPartEntityManager == null) { batchPartEntityManager = new BatchPartEntityManagerImpl(this, batchPartDataManager); } } // getters and setters // ////////////////////////////////////////////////////// public BatchServiceConfiguration getIdentityLinkServiceConfiguration() { return this; } public BatchService getBatchService() { return batchService; } public BatchServiceConfiguration setBatchService(BatchService batchService) { this.batchService = batchService; return this; } public BatchDataManager getBatchDataManager() { return batchDataManager; } public BatchServiceConfiguration setBatchDataManager(BatchDataManager batchDataManager) {
this.batchDataManager = batchDataManager; return this; } public BatchPartDataManager getBatchPartDataManager() { return batchPartDataManager; } public BatchServiceConfiguration setBatchPartDataManager(BatchPartDataManager batchPartDataManager) { this.batchPartDataManager = batchPartDataManager; return this; } public BatchEntityManager getBatchEntityManager() { return batchEntityManager; } public BatchServiceConfiguration setBatchEntityManager(BatchEntityManager batchEntityManager) { this.batchEntityManager = batchEntityManager; return this; } public BatchPartEntityManager getBatchPartEntityManager() { return batchPartEntityManager; } public BatchServiceConfiguration setBatchPartEntityManager(BatchPartEntityManager batchPartEntityManager) { this.batchPartEntityManager = batchPartEntityManager; return this; } @Override public ObjectMapper getObjectMapper() { return objectMapper; } @Override public BatchServiceConfiguration setObjectMapper(ObjectMapper objectMapper) { this.objectMapper = objectMapper; return this; } }
repos\flowable-engine-main\modules\flowable-batch-service\src\main\java\org\flowable\batch\service\BatchServiceConfiguration.java
2
请完成以下Java代码
private PackageableRow createPackageableRow(final ViewId viewId, final Packageable packageable) { final Quantity qtyPickedOrDelivered = packageable.getQtyPickedOrDelivered(); final Optional<OrderLineId> orderLineId = Optional.ofNullable(packageable.getSalesOrderLineIdOrNull()); return PackageableRow.builder() .shipmentScheduleId(packageable.getShipmentScheduleId()) .salesOrderLineId(orderLineId) .viewId(viewId) // .order(orderLookup.get().findById(packageable.getSalesOrderId())) .product(productLookup.get().findById(packageable.getProductId())) .bpartner(bpartnerLookup.get().findById(packageable.getCustomerId())) .preparationDate(packageable.getPreparationDate().toZonedDateTime(orgDAO::getTimeZone)) // .qtyOrdered(packageable.getQtyOrdered()) .qtyPicked(qtyPickedOrDelivered) // .build();
} public PackageableRowsData createRowsData( @NonNull final ViewId viewId, @NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { if (shipmentScheduleIds.isEmpty()) { return PackageableRowsData.EMPTY; } final Set<ShipmentScheduleId> shipmentScheduleIdsCopy = ImmutableSet.copyOf(shipmentScheduleIds); return PackageableRowsData.ofSupplier(() -> retrieveRowsByShipmentScheduleIds(viewId, shipmentScheduleIdsCopy)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\picking\packageable\PackageableRowsRepository.java
1
请完成以下Java代码
public String getDescription(final String adLanguage) { return description.translate(adLanguage); } public KPIField getGroupByField() { final KPIField groupByField = getGroupByFieldOrNull(); if (groupByField == null) { throw new IllegalStateException("KPI has no group by field defined"); } return groupByField; } @Nullable public KPIField getGroupByFieldOrNull() { return groupByField; } public boolean hasCompareOffset() { return compareOffset != null; } public Set<CtxName> getRequiredContextParameters() { if (elasticsearchDatasource != null) { return elasticsearchDatasource.getRequiredContextParameters(); } else if (sqlDatasource != null) { return sqlDatasource.getRequiredContextParameters(); }
else { throw new AdempiereException("Unknown datasource type: " + datasourceType); } } public boolean isZoomToDetailsAvailable() { return sqlDatasource != null; } @NonNull public SQLDatasourceDescriptor getSqlDatasourceNotNull() { return Check.assumeNotNull(getSqlDatasource(), "Not an SQL data source: {}", this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\kpi\descriptor\KPI.java
1
请在Spring Boot框架中完成以下Java代码
private EndpointLinksResolver getLinksResolver(Collection<ExposableWebEndpoint> webEndpoints, Collection<org.springframework.boot.actuate.endpoint.web.ExposableServletEndpoint> servletEndpoints) { List<ExposableEndpoint<?>> endpoints = new ArrayList<>(webEndpoints.size() + servletEndpoints.size()); endpoints.addAll(webEndpoints); endpoints.addAll(servletEndpoints); return new EndpointLinksResolver(endpoints, this.basePath); } private void register(Collection<Resource> resources, ResourceConfig config) { config.registerResources(new HashSet<>(resources)); } } class JerseyAdditionalHealthEndpointPathsManagementResourcesRegistrar implements ManagementContextResourceConfigCustomizer { private final @Nullable ExposableWebEndpoint healthEndpoint; private final HealthEndpointGroups groups; JerseyAdditionalHealthEndpointPathsManagementResourcesRegistrar(@Nullable ExposableWebEndpoint healthEndpoint, HealthEndpointGroups groups) { this.healthEndpoint = healthEndpoint; this.groups = groups; } @Override public void customize(ResourceConfig config) { if (this.healthEndpoint != null) { register(config, this.healthEndpoint); } } private void register(ResourceConfig config, ExposableWebEndpoint healthEndpoint) { EndpointMapping mapping = new EndpointMapping(""); JerseyHealthEndpointAdditionalPathResourceFactory resourceFactory = new JerseyHealthEndpointAdditionalPathResourceFactory( WebServerNamespace.MANAGEMENT, this.groups); Collection<Resource> endpointResources = resourceFactory .createEndpointResources(mapping, Collections.singletonList(healthEndpoint)) .stream() .filter(Objects::nonNull) .toList();
register(endpointResources, config); } private void register(Collection<Resource> resources, ResourceConfig config) { config.registerResources(new HashSet<>(resources)); } } /** * {@link ContextResolver} used to obtain the {@link ObjectMapper} that should be used * for {@link OperationResponseBody} instances. */ @SuppressWarnings("removal") @Priority(Priorities.USER - 100) private static final class EndpointJackson2ObjectMapperContextResolver implements ContextResolver<ObjectMapper> { private final org.springframework.boot.actuate.endpoint.jackson.EndpointJackson2ObjectMapper mapper; private EndpointJackson2ObjectMapperContextResolver( org.springframework.boot.actuate.endpoint.jackson.EndpointJackson2ObjectMapper mapper) { this.mapper = mapper; } @Override public @Nullable ObjectMapper getContext(Class<?> type) { return OperationResponseBody.class.isAssignableFrom(type) ? this.mapper.get() : null; } } }
repos\spring-boot-4.0.1\module\spring-boot-jersey\src\main\java\org\springframework\boot\jersey\autoconfigure\actuate\web\JerseyWebEndpointManagementContextConfiguration.java
2
请完成以下Java代码
public class ChatEndpoint { private Session session; private static final Set<ChatEndpoint> chatEndpoints = new CopyOnWriteArraySet<>(); private static HashMap<String, String> users = new HashMap<>(); @OnOpen public void onOpen(Session session, @PathParam("username") String username) { this.session = session; chatEndpoints.add(this); users.put(session.getId(), username); Message message = new Message(); message.setFrom(username); message.setContent("Connected!"); broadcast(message); } @OnMessage public void onMessage(Session session, Message message) { message.setFrom(users.get(session.getId())); broadcast(message); } @OnClose public void onClose(Session session) { chatEndpoints.remove(this); Message message = new Message(); message.setFrom(users.get(session.getId())); message.setContent("Disconnected!"); broadcast(message); } @OnError public void onError(Session session, Throwable throwable) { // Do error handling here
} private static void broadcast(Message message) { chatEndpoints.forEach(endpoint -> { synchronized (endpoint) { try { endpoint.session.getBasicRemote() .sendObject(message); } catch (IOException | EncodeException e) { e.printStackTrace(); } } }); } }
repos\tutorials-master\core-java-modules\java-websocket\src\main\java\com\baeldung\websocket\ChatEndpoint.java
1
请在Spring Boot框架中完成以下Java代码
static class GsonHttpMessageConverterConfiguration { @Bean @Order(0) @ConditionalOnMissingBean(GsonHttpMessageConverter.class) GsonHttpConvertersCustomizer gsonHttpMessageConvertersCustomizer(Gson gson) { return new GsonHttpConvertersCustomizer(gson); } } static class GsonHttpConvertersCustomizer implements ClientHttpMessageConvertersCustomizer, ServerHttpMessageConvertersCustomizer { private final GsonHttpMessageConverter converter; GsonHttpConvertersCustomizer(Gson gson) { this.converter = new GsonHttpMessageConverter(gson); } @Override public void customize(ClientBuilder builder) { builder.withJsonConverter(this.converter); } @Override public void customize(ServerBuilder builder) { builder.withJsonConverter(this.converter); } } private static class PreferGsonOrJacksonAndJsonbUnavailableCondition extends AnyNestedCondition { PreferGsonOrJacksonAndJsonbUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "gson") static class GsonPreferred { } @Conditional(JacksonAndJsonbUnavailableCondition.class) static class JacksonJsonbUnavailable {
} } private static class JacksonAndJsonbUnavailableCondition extends NoneNestedConditions { JacksonAndJsonbUnavailableCondition() { super(ConfigurationPhase.REGISTER_BEAN); } @ConditionalOnBean(JacksonHttpMessageConvertersConfiguration.JacksonJsonHttpMessageConvertersCustomizer.class) static class JacksonAvailable { } @SuppressWarnings("removal") @ConditionalOnBean(Jackson2HttpMessageConvertersConfiguration.Jackson2JsonMessageConvertersCustomizer.class) static class Jackson2Available { } @ConditionalOnProperty(name = HttpMessageConvertersAutoConfiguration.PREFERRED_MAPPER_PROPERTY, havingValue = "jsonb") static class JsonbPreferred { } } }
repos\spring-boot-main\module\spring-boot-http-converter\src\main\java\org\springframework\boot\http\converter\autoconfigure\GsonHttpMessageConvertersConfiguration.java
2
请完成以下Java代码
public CLabel createEditorLabel() { return swingEditorFactory.getLabel(gridField); } @Override public Object convertValueToFieldType(final Object valueObj) { return UserQueryFieldHelper.parseValueObjectByColumnDisplayType(valueObj, getDisplayType(), getColumnName()); } @Override public String getValueDisplay(final Object value) { String infoDisplay = value == null ? "" : value.toString(); if (isLookup()) { final Lookup lookup = getLookup(); if (lookup != null) { infoDisplay = lookup.getDisplay(value); } } else if (getDisplayType() == DisplayType.YesNo) { final IMsgBL msgBL = Services.get(IMsgBL.class); infoDisplay = msgBL.getMsg(Env.getCtx(), infoDisplay); } return infoDisplay; } @Override public boolean matchesColumnName(final String columnName) { if (columnName == null || columnName.isEmpty()) { return false; } if (columnName.equals(getColumnName()))
{ return true; } if (gridField.isVirtualColumn()) { if (columnName.equals(gridField.getColumnSQL(false))) { return true; } if (columnName.equals(gridField.getColumnSQL(true))) { return true; } } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\search\FindPanelSearchField.java
1
请完成以下Java代码
private Mono<Void> handleUninitialized(ServerHttpRequest request, ServerHttpResponse response) { throw new IllegalStateException("The HttpHandler has not yet been initialized"); } @Override public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { return this.delegate.handle(request, response); } void initializeHandler() { this.delegate = this.lazyInit ? new LazyHttpHandler(this.handlerSupplier) : this.handlerSupplier.get(); } HttpHandler getHandler() { return this.delegate; } } /** * {@link HttpHandler} that initializes its delegate on first request.
*/ private static final class LazyHttpHandler implements HttpHandler { private final Mono<HttpHandler> delegate; private LazyHttpHandler(Supplier<HttpHandler> handlerSupplier) { this.delegate = Mono.fromSupplier(handlerSupplier); } @Override public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response) { return this.delegate.flatMap((handler) -> handler.handle(request, response)); } } }
repos\spring-boot-4.0.1\module\spring-boot-web-server\src\main\java\org\springframework\boot\web\server\reactive\context\WebServerManager.java
1
请完成以下Java代码
public void execute() { trxManager.runInThreadInheritedTrx(this::executeInTrx); } private void executeInTrx() { trxManager.assertThreadInheritedTrxExists(); loadState(); validateState(); // // generate movement InTransit -> Pick From Locator moveBackTheHU(); deleteSchedule(); } private void moveBackTheHU() { MoveHUCommand.builder() .huQRCodesService(huqrCodesService) .requestItems(ImmutableSet.of(MoveHURequestItem.ofHUIdAndQRCode(HUIdAndQRCode.ofHuId(schedule.getPickFromHUId())))) .targetQRCode(getTargetQRCode()) .build() .execute(); } private void loadState() { schedule = ddOrderMoveScheduleRepository.getById(scheduleId); } private void validateState() { if (!schedule.isPickedFrom()) { throw new AdempiereException("Not picked"); } if (schedule.isDropTo()) { throw new AdempiereException("Already dropped!"); } }
private void deleteSchedule() { schedule.removePickedHUs(); ddOrderMoveScheduleRepository.save(schedule); ddOrderMoveScheduleRepository.deleteNotStarted(schedule.getId()); } private ScannedCode getTargetQRCode() { if (unpickToTargetQRCode != null) { return unpickToTargetQRCode.toScannedCode(); } else { return warehouseBL.getLocatorQRCode(schedule.getPickFromLocatorId()).toScannedCode(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\distribution\ddorder\movement\schedule\commands\unpick\DDOrderUnpickCommand.java
1
请完成以下Java代码
public class DataAssociation { protected String source; protected Expression sourceExpression; protected String target; protected String variables; protected Expression businessKeyExpression; protected DataAssociation(String source, String target) { this.source = source; this.target = target; } protected DataAssociation(Expression sourceExpression, String target) { this.sourceExpression = sourceExpression; this.target = target; } protected DataAssociation(String variables) { this.variables = variables; } protected DataAssociation(Expression businessKeyExpression) { this.businessKeyExpression = businessKeyExpression; } public String getSource() {
return source; } public String getTarget() { return target; } public Expression getSourceExpression() { return sourceExpression; } public String getVariables() { return variables; } public Expression getBusinessKeyExpression() { return businessKeyExpression; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\DataAssociation.java
1
请在Spring Boot框架中完成以下Java代码
public boolean jwtTokenRefresh(String token, String userName, String passWord) { String cacheToken = String.valueOf(redisUtil.get(CommonConstant.PREFIX_USER_TOKEN + token)); if (oConvertUtils.isNotEmpty(cacheToken)) { // 校验token有效性 if (!JwtUtil.verify(cacheToken, userName, passWord)) { // 从token中解析客户端类型,保持续期时使用相同的客户端类型 String clientType = JwtUtil.getClientType(token); String newAuthorization = JwtUtil.sign(userName, passWord, clientType); // 根据客户端类型设置对应的缓存有效时间 long expireTime = CommonConstant.CLIENT_TYPE_APP.equalsIgnoreCase(clientType) ? JwtUtil.APP_EXPIRE_TIME * 2 / 1000 : JwtUtil.EXPIRE_TIME * 2 / 1000; redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, newAuthorization); redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, expireTime); log.debug("——————————用户在线操作,更新token保证不掉线—————————jwtTokenRefresh——————— "+ token); } // else { // // 设置超时时间 // redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, cacheToken); // redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME / 1000);
// } return true; } //redis中不存在此TOEKN,说明token非法返回false return false; } /** * 清除当前用户的权限认证缓存 * * @param principals 权限信息 */ @Override public void clearCache(PrincipalCollection principals) { super.clearCache(principals); // 代码逻辑说明: 【TV360X-1320】分配权限必须退出重新登录才生效,造成很多用户困扰--- super.clearCachedAuthorizationInfo(principals); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\config\shiro\ShiroRealm.java
2
请在Spring Boot框架中完成以下Java代码
private static ITranslatableString extractNameTrl(@NonNull final I_Mobile_Application record, @NonNull final ImmutableList<I_Mobile_Application_Trl> recordTrls) { final HashMap<String, String> trlMap = new HashMap<>(); for (final I_Mobile_Application_Trl recordTrl : recordTrls) { final String adLanguage = recordTrl.getAD_Language(); final String nameTrl = recordTrl.isUseCustomization() ? StringUtils.trimBlankToOptional(recordTrl.getName_Customized()).orElseGet(recordTrl::getName) : recordTrl.getName(); trlMap.put(adLanguage, nameTrl); } return TranslatableStrings.ofMap(trlMap, record.getName()); } private static @NotNull MobileApplicationRepoId extractId(final I_Mobile_Application record) {return MobileApplicationRepoId.ofRepoId(record.getMobile_Application_ID());} private static @NotNull MobileApplicationRepoId extractId(final I_Mobile_Application_Trl recordTrl) {return MobileApplicationRepoId.ofRepoId(recordTrl.getMobile_Application_ID());} private static MobileApplicationRepoId extractId(final I_Mobile_Application_Action record) {return MobileApplicationRepoId.ofRepoId(record.getMobile_Application_ID());} public void updateMobileApplicationTrl(final MobileApplicationRepoId mobileApplicationRepoId, @NonNull final String adLanguage) { DB.executeFunctionCallEx( ITrx.TRXNAME_ThreadInherited, addUpdateFunctionCall(FUNCTION_update_Mobile_Application_TRLs, mobileApplicationRepoId, adLanguage), null); } @SuppressWarnings("SameParameterValue") private String addUpdateFunctionCall(final String functionCall, final MobileApplicationRepoId mobileApplicationRepoId, final String adLanguage) { return MigrationScriptFileLoggerHolder.DDL_PREFIX + " select " + functionCall + "(" + mobileApplicationRepoId.getRepoId() + "," + DB.TO_STRING(adLanguage) + ") "; } // //
// // // private static class MobileApplicationInfoMap { @NonNull private final ImmutableList<MobileApplicationInfo> list; @NonNull private final ImmutableMap<MobileApplicationId, MobileApplicationInfo> byApplicationId; private MobileApplicationInfoMap(@NonNull final List<MobileApplicationInfo> list) { this.list = ImmutableList.copyOf(list); this.byApplicationId = Maps.uniqueIndex(list, MobileApplicationInfo::getId); } public MobileApplicationInfo getById(final MobileApplicationId applicationId) { final MobileApplicationInfo applicationInfo = byApplicationId.get(applicationId); if (applicationInfo == null) { throw new AdempiereException("No application info found for " + applicationId); } return applicationInfo; } public List<MobileApplicationInfo> toList() { return list; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\mobile\application\repository\MobileApplicationInfoRepository.java
2
请在Spring Boot框架中完成以下Java代码
public class ServiceController { private final Calculations calculations; private final CalculationWebClient calculationWebClient; public ServiceController(Calculations calculations, CalculationWebClient calculationWebClient) { this.calculations = calculations; this.calculationWebClient = calculationWebClient; } @Observed( name = "demo.controller.endpoints" ) @GetMapping("calculate/{input}") Result calculate(@PathVariable int input, @RequestParam(required = false) Integer input2) { if (input < 1 || input > 30) { throw new IllegalArgumentException("PathVariable input1 must be between [1,30]"); } if (input2 != null) { if (input2 < 1 || input2 > 30) { throw new IllegalArgumentException("RequestParam input2 must be null or between [1,30]"); } } int result1 = calculations.fibonacci(input); int result2 = 0; if (input2 != null) { result2 = calculationWebClient.fibonacci(input2); } return new Result(true, result1, result2); } @Observed(
name = "demo.controller.endpoints" ) @GetMapping("calculate2/{input}") int calculate2(@PathVariable int input) { if (input < 1 || input > 30) { throw new IllegalArgumentException("PathVariable input must be between [1,30]"); } return calculations.fibonacci(input); } @Observed( name = "demo.controller.sleep", contextualName = "observed sleep endpoint", lowCardinalityKeyValues = { "class", "ServiceController" } ) @GetMapping("sleep/{input}") public Mono<Integer> sleep(@PathVariable int input) { if (input < 0) { input = 0; } return Mono.delay(Duration.ofMillis(input)).then(Mono.just(input)); } }
repos\spring-boot3-demo-master\src\main\java\com\giraone\sb3\demo\controller\ServiceController.java
2
请在Spring Boot框架中完成以下Java代码
public class PermissionException extends BizException { private static final long serialVersionUID = -5371846727040729628L; private static final Logger logger = LoggerFactory.getLogger(PermissionException.class); /** 该用户没有分配菜单权限 */ public static final Integer PERMISSION_USER_NOT_MENU = 1001; /** 根据角色查询菜单出现错误 **/ public static final Integer PERMISSION_QUERY_MENU_BY_ROLE_ERROR = 1002; /** 分配菜单权限时,角色不能为空 **/ public static final Integer PERMISSION_ASSIGN_MENU_ROLE_NULL = 1003; /** 对接龙果平台用户体系异常 **/ public static final Integer RONCOO_NETWORK_EXCEPTION = 1004; public PermissionException() { } public PermissionException(int code, String msgFormat, Object... args) { super(code, msgFormat, args); } public PermissionException(int code, String msg) { super(code, msg);
} /** * 实例化异常 * * @param msgFormat * @param args * @return */ public PermissionException newInstance(String msgFormat, Object... args) { return new PermissionException(this.code, msgFormat, args); } public PermissionException print() { logger.info("==>BizException, code:" + this.code + ", msg:" + this.msg); return this; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\exception\PermissionException.java
2
请完成以下Java代码
public class Source { private String name; private int age; public Source() { } public Source(String name, int age) { super(); this.name = name; this.age = age; } public String getName() { return name;
} public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } }
repos\tutorials-master\libraries-data\src\main\java\com\baeldung\dozer\Source.java
1
请完成以下Java代码
public class DirectoryScriptScanner extends AbstractRecursiveScriptScanner { private final IFileRef rootFileRef; private final File[] children; private int currentIndex; public DirectoryScriptScanner(final IFileRef fileRef) { super(fileRef.getScriptScanner()); rootFileRef = fileRef; children = retrieveChildren(fileRef); currentIndex = -1; } /** * Convenient constructor * * @param file */ public DirectoryScriptScanner(final File file) { this(new FileRef(file)); } private static final File[] retrieveChildren(final IFileRef fileRef) { final File file = fileRef.getFile(); if (file == null) { return new File[] {}; } if (!file.isDirectory()) { return new File[] {}; } final File[] children = file.listFiles(); if (children == null) { return new File[] {}; } Arrays.sort(children); // make sure the files are sorted lexicographically return children; } @Override protected IScriptScanner retrieveNextChildScriptScanner() {
while (currentIndex < children.length - 1) { currentIndex++; final File child = children[currentIndex]; final IScriptScanner childScanner = createScriptScanner(child); if (childScanner != null) { return childScanner; } } return null; } private IScriptScanner createScriptScanner(final File file) { final FileRef fileRef = new FileRef(this, rootFileRef, file); final IScriptScanner scanner = getScriptScannerFactoryToUse().createScriptScanner(fileRef); return scanner; } @Override public String toString() { return "DirectoryScriptScanner [rootFileRef=" + rootFileRef + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.migration\de.metas.migration.base\src\main\java\de\metas\migration\scanner\impl\DirectoryScriptScanner.java
1
请在Spring Boot框架中完成以下Java代码
public void setFrom(final PackingItemParts from) { partsMap.clear(); partsMap.putAll(from.partsMap); } public Optional<Quantity> getQtySum() { return map(PackingItemPart::getQty) .reduce(Quantity::add); } public List<PackingItemPart> toList() { return ImmutableList.copyOf(partsMap.values()); } public I_C_UOM getCommonUOM() { //validate that all qtys have the same UOM mapReduce(part -> part.getQty().getUomId()) .orElseThrow(()-> new AdempiereException("Missing I_C_UOM!") .appendParametersToMessage() .setParameter("Parts", this)); return toList().get(0).getQty().getUOM(); } @Override public Iterator<PackingItemPart> iterator()
{ return toList().iterator(); } public void clear() { partsMap.clear(); } public void addQtys(final PackingItemParts partsToAdd) { partsToAdd.toList() .forEach(this::addQty); } private void addQty(final PackingItemPart part) { partsMap.compute(part.getId(), (id, existingPart) -> existingPart != null ? existingPart.addQty(part.getQty()) : part); } public void removePart(final PackingItemPart part) { partsMap.remove(part.getId(), part); } public void updatePart(@NonNull final PackingItemPart part) { partsMap.put(part.getId(), part); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\picking\service\PackingItemParts.java
2
请完成以下Java代码
private static JsonWorkPackageStatus toJsonForWorkPackage(final I_C_Queue_WorkPackage workPackageRecord) { return JsonWorkPackageStatus.builder() .error(workPackageRecord.getErrorMsg()) .enqueued(TimeUtil.asInstant(workPackageRecord.getCreated())) .readyForProcessing(workPackageRecord.isReadyForProcessing()) .metasfreshId(JsonMetasfreshId.of(workPackageRecord.getC_Queue_WorkPackage_ID())) .build(); } private List<JsonPurchaseOrder> retrievePurchaseOrderInfo(final PurchaseCandidateId candidate) { final Collection<OrderId> orderIds = purchaseCandidateRepo.getOrderIdsForPurchaseCandidates(candidate); return Services.get(IOrderDAO.class).getByIds(orderIds) .stream() .map(this::toJsonOrder) .collect(ImmutableList.toImmutableList()); } @NonNull private JsonPurchaseCandidate.JsonPurchaseCandidateBuilder preparePurchaseCandidateStatus(@NonNull final PurchaseCandidate candidate) { return JsonPurchaseCandidate.builder() .externalSystemCode(poJsonConverters.getExternalSystemTypeById(candidate)) .externalHeaderId(JsonExternalIds.ofOrNull(candidate.getExternalHeaderId())) .externalLineId(JsonExternalIds.ofOrNull(candidate.getExternalLineId())) .purchaseDateOrdered(candidate.getPurchaseDateOrdered()) .purchaseDatePromised(candidate.getPurchaseDatePromised()) .metasfreshId(JsonMetasfreshId.of(candidate.getId().getRepoId())) .externalPurchaseOrderUrl(candidate.getExternalPurchaseOrderUrl()) .processed(candidate.isProcessed()); } private JsonPurchaseOrder toJsonOrder(@NonNull final I_C_Order order)
{ final boolean hasArchive = hasArchive(order); final ZoneId timeZone = orgDAO.getTimeZone(OrgId.ofRepoId(order.getAD_Org_ID())); return JsonPurchaseOrder.builder() .dateOrdered(TimeUtil.asZonedDateTime(order.getDateOrdered(), timeZone)) .datePromised(TimeUtil.asZonedDateTime(order.getDatePromised(), timeZone)) .docStatus(order.getDocStatus()) .documentNo(order.getDocumentNo()) .metasfreshId(JsonMetasfreshId.of(order.getC_Order_ID())) .pdfAvailable(hasArchive) .build(); } private boolean hasArchive(final I_C_Order order) { return archiveBL.getLastArchive(TableRecordReference.of(I_C_Order.Table_Name, order.getC_Order_ID())).isPresent(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\order\PurchaseCandidatesStatusService.java
1
请完成以下Java代码
public void removePausesAroundDate( @NonNull final I_C_Flatrate_Term term, @NonNull final Timestamp date) { new RemovePauses(this).removePausesAroundTimeframe(term, date, date); resetCache(BPartnerId.ofRepoId(term.getBill_BPartner_ID()), FlatrateDataId.ofRepoId(term.getC_Flatrate_Data_ID())); } public void removeAllPauses(final I_C_Flatrate_Term term) { final Timestamp distantPast = TimeUtil.getDay(1970, 1, 1); final Timestamp distantFuture = TimeUtil.getDay(9999, 12, 31); new RemovePauses(this).removePausesAroundTimeframe(term, distantPast, distantFuture); resetCache(BPartnerId.ofRepoId(term.getBill_BPartner_ID()), FlatrateDataId.ofRepoId(term.getC_Flatrate_Data_ID())); } public final List<I_C_SubscriptionProgress> retrieveNextSPsAndLogIfEmpty( @NonNull final I_C_Flatrate_Term term, @NonNull final Timestamp pauseFrom) { final ISubscriptionDAO subscriptionDAO = Services.get(ISubscriptionDAO.class); final SubscriptionProgressQuery query = SubscriptionProgressQuery.builder() .term(term) .eventDateNotBefore(pauseFrom) .build(); final List<I_C_SubscriptionProgress> sps = subscriptionDAO.retrieveSubscriptionProgresses(query);
if (sps.isEmpty()) { final IMsgBL msgBL = Services.get(IMsgBL.class); Loggables.addLog(msgBL.getMsg(Env.getCtx(), MSG_NO_SPS_AFTER_DATE_1P, new Object[] { pauseFrom })); } return sps; } /** * This is needed because no direct parent-child relationship can be established between these tables, as the {@code I_C_SubscriptionProgress} tabs would want to show * records for which the C_BPartner_ID in context is either the recipient or the contract holder. */ private static void resetCache(@NonNull final BPartnerId bpartnerId, @NonNull final FlatrateDataId flatrateDataId) { final ModelCacheInvalidationService modelCacheInvalidationService = ModelCacheInvalidationService.get(); modelCacheInvalidationService.invalidate( CacheInvalidateMultiRequest.of( CacheInvalidateRequest.allChildRecords(I_C_Flatrate_Data.Table_Name, flatrateDataId, I_C_SubscriptionProgress.Table_Name), CacheInvalidateRequest.allChildRecords(I_C_BPartner.Table_Name, bpartnerId, I_C_SubscriptionProgress.Table_Name)), ModelCacheInvalidationTiming.AFTER_CHANGE ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\subscription\impl\SubscriptionService.java
1
请在Spring Boot框架中完成以下Java代码
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements IDictService { @Override public IPage<DictVO> selectDictPage(IPage<DictVO> page, DictVO dict) { return page.setRecords(baseMapper.selectDictPage(page, dict)); } @Override public List<DictVO> tree() { return ForestNodeMerger.merge(baseMapper.tree()); } @Override @Cacheable(cacheNames = DICT_VALUE, key = "#code+'_'+#dictKey") public String getValue(String code, Integer dictKey) { return Func.toStr(baseMapper.getValue(code, dictKey), StringPool.EMPTY); } @Override @Cacheable(cacheNames = DICT_LIST, key = "#code")
public List<Dict> getList(String code) { return baseMapper.getList(code); } @Override @CacheEvict(cacheNames = {DICT_LIST, DICT_VALUE}, allEntries = true) public boolean submit(Dict dict) { LambdaQueryWrapper<Dict> lqw = Wrappers.<Dict>query().lambda().eq(Dict::getCode, dict.getCode()).eq(Dict::getDictKey, dict.getDictKey()); Long cnt = baseMapper.selectCount((Func.isEmpty(dict.getId())) ? lqw : lqw.notIn(Dict::getId, dict.getId())); if (cnt > 0) { throw new ServiceException("当前字典键值已存在!"); } return saveOrUpdate(dict); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\service\impl\DictServiceImpl.java
2
请在Spring Boot框架中完成以下Java代码
public String getMerchantNo() { return merchantNo; } /** 商户编号 **/ public void setMerchantNo(String merchantNo) { this.merchantNo = merchantNo == null ? null : merchantNo.trim(); } /** 商户订单号 **/ public String getMerchantOrderNo() { return merchantOrderNo; } /** 商户订单号 **/
public void setMerchantOrderNo(String merchantOrderNo) { this.merchantOrderNo = merchantOrderNo == null ? null : merchantOrderNo.trim(); } /** HTTP状态 **/ public Integer getHttpStatus() { return httpStatus; } /** HTTP状态 **/ public void setHttpStatus(Integer httpStatus) { this.httpStatus = httpStatus; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\entity\RpNotifyRecordLog.java
2
请完成以下Java代码
public boolean isClosed() { return closed.get(); } @Override public void close() { // If it was already closed, do nothing (method contract). if (isClosed()) { return; } unlockAll(); } private void assertHasRealOwner() { final LockOwner owner = getOwner(); Check.assume(owner.isRealOwner(), "lock {} shall have an owner", this); }
@Override public ILockAutoCloseable asAutoCloseable() { return new LockAutoCloseable(this); } @Override public ILockAutoCloseable asAutocloseableOnTrxClose(final String trxName) { return new LockAutoCloseableOnTrxClose(this, trxName); } @Override public boolean isLocked(final Object model) { final int adTableId = InterfaceWrapperHelper.getModelTableId(model); final int recordId = InterfaceWrapperHelper.getId(model); return getLockDatabase().isLocked(adTableId, recordId, getOwner()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.async\src\main\java\de\metas\lock\api\impl\Lock.java
1
请完成以下Java代码
public String getStartedBy() { return startedBy; } public String getSuperProcessInstanceId() { return superProcessInstanceId; } public boolean isExcludeSubprocesses() { return excludeSubprocesses; } public List<String> getProcessKeyNotIn() { return processKeyNotIn; } public Date getStartedAfter() { return startedAfter; } public Date getStartedBefore() { return startedBefore; } public Date getFinishedAfter() { return finishedAfter; } public Date getFinishedBefore() { return finishedBefore; } public String getInvolvedUser() { return involvedUser; } public String getName() { return name; } public String getNameLike() { return nameLike; } public static long getSerialversionuid() { return serialVersionUID; } public String getDeploymentId() { return deploymentId; } public List<String> getDeploymentIds() { return deploymentIds; } public boolean isFinished() { return finished; } public boolean isUnfinished() { return unfinished; } public boolean isDeleted() { return deleted; } public boolean isNotDeleted() { return notDeleted; } public boolean isIncludeProcessVariables() { return includeProcessVariables; }
public boolean isWithException() { return withJobException; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } public String getNameLikeIgnoreCase() { return nameLikeIgnoreCase; } public List<HistoricProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } public List<String> getInvolvedGroups() { return involvedGroups; } public HistoricProcessInstanceQuery involvedGroupsIn(List<String> involvedGroups) { if (involvedGroups == null || involvedGroups.isEmpty()) { throw new ActivitiIllegalArgumentException("Involved groups list is null or empty."); } if (inOrStatement) { this.currentOrQueryObject.involvedGroups = involvedGroups; } else { this.involvedGroups = involvedGroups; } return this; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\HistoricProcessInstanceQueryImpl.java
1
请完成以下Java代码
public void setBasedOnPreviousValue(boolean basedOnPreviousValue) { this.basedOnPreviousValue = basedOnPreviousValue; } @Override public String toString() { return new ToStringCreator(this).append("firstBackoff", firstBackoff) .append("maxBackoff", maxBackoff) .append("factor", factor) .append("basedOnPreviousValue", basedOnPreviousValue) .toString(); } } public static class JitterConfig { private double randomFactor = 0.5; public void validate() { Assert.isTrue(randomFactor >= 0 && randomFactor <= 1, "random factor must be between 0 and 1 (default 0.5)"); } public JitterConfig() { } public JitterConfig(double randomFactor) { this.randomFactor = randomFactor; }
public double getRandomFactor() { return randomFactor; } public void setRandomFactor(double randomFactor) { this.randomFactor = randomFactor; } @Override public String toString() { return new ToStringCreator(this).append("randomFactor", randomFactor).toString(); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\RetryGatewayFilterFactory.java
1
请完成以下Java代码
public ViewId getInitialViewId() { return initialViewId != null ? initialViewId : getViewId(); } @Override public ViewId getParentViewId() { return initialViewId; } public Optional<OrderId> getOrderId() { return rowsData.getOrder().map(Order::getOrderId); } public Optional<BPartnerId> getBpartnerId() { return rowsData.getBpartnerId(); } public SOTrx getSoTrx() { return rowsData.getSoTrx(); } public CurrencyId getCurrencyId() { return rowsData.getCurrencyId(); } public Set<ProductId> getProductIds() { return rowsData.getProductIds(); } public Optional<PriceListVersionId> getSinglePriceListVersionId() { return rowsData.getSinglePriceListVersionId(); } public Optional<PriceListVersionId> getBasePriceListVersionId() { return rowsData.getBasePriceListVersionId(); } public PriceListVersionId getBasePriceListVersionIdOrFail() { return rowsData.getBasePriceListVersionId() .orElseThrow(() -> new AdempiereException("@NotFound@ @M_Pricelist_Version_Base_ID@")); } public List<ProductsProposalRow> getAllRows()
{ return ImmutableList.copyOf(getRows()); } public void addOrUpdateRows(@NonNull final List<ProductsProposalRowAddRequest> requests) { rowsData.addOrUpdateRows(requests); invalidateAll(); } public void patchViewRow(@NonNull final DocumentId rowId, @NonNull final ProductsProposalRowChangeRequest request) { rowsData.patchRow(rowId, request); } public void removeRowsByIds(final Set<DocumentId> rowIds) { rowsData.removeRowsByIds(rowIds); invalidateAll(); } public ProductsProposalView filter(final ProductsProposalViewFilter filter) { rowsData.filter(filter); return this; } @Override public DocumentFilterList getFilters() { return ProductsProposalViewFilters.toDocumentFilters(rowsData.getFilter()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\products_proposal\view\ProductsProposalView.java
1
请完成以下Java代码
public boolean isHttpOkOnValidationErrors() { return this.httpOkOnValidationErrors; } /** * Set whether this HTTP handler should use HTTP 200 OK responses if an error occurs before * the GraphQL request execution phase starts. * @param httpOkOnValidationErrors whether "HTTP 200 OK" responses should always be used * @since 1.4.0 * @deprecated since 1.4, will be made {@code false} permanently in a future release * @see #isHttpOkOnValidationErrors */ @Deprecated(since = "1.4.0", forRemoval = true) public void setHttpOkOnValidationErrors(boolean httpOkOnValidationErrors) { this.httpOkOnValidationErrors = httpOkOnValidationErrors; } protected Mono<ServerResponse> prepareResponse(ServerRequest request, WebGraphQlResponse response) { MediaType responseMediaType = selectResponseMediaType(request); HttpStatus responseStatus = selectResponseStatus(response, responseMediaType); ServerResponse.BodyBuilder builder = ServerResponse.status(responseStatus); builder.headers((headers) -> headers.putAll(response.getResponseHeaders())); builder.contentType(responseMediaType); return builder.bodyValue(encodeResponseIfNecessary(response)); } protected HttpStatus selectResponseStatus(WebGraphQlResponse response, MediaType responseMediaType) { if (!isHttpOkOnValidationErrors() && !response.getExecutionResult().isDataPresent() && MediaTypes.APPLICATION_GRAPHQL_RESPONSE.equals(responseMediaType)) {
return HttpStatus.BAD_REQUEST; } return HttpStatus.OK; } private static MediaType selectResponseMediaType(ServerRequest serverRequest) { ServerRequest.Headers headers = serverRequest.headers(); List<MediaType> acceptedMediaTypes; try { acceptedMediaTypes = headers.accept(); } catch (InvalidMediaTypeException ex) { throw new NotAcceptableStatusException("Could not parse " + "Accept header [" + headers.firstHeader(HttpHeaders.ACCEPT) + "]: " + ex.getMessage()); } for (MediaType accepted : acceptedMediaTypes) { if (SUPPORTED_MEDIA_TYPES.contains(accepted)) { return accepted; } } return MediaType.APPLICATION_JSON; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\server\webflux\GraphQlHttpHandler.java
1
请完成以下Java代码
protected void compute() { if (((upperBound + 1) - lowerBound) > granularity) { ForkJoinTask.invokeAll(subTasks()); } else { findPrimeNumbers(); } } void findPrimeNumbers() { for (int num = lowerBound; num <= upperBound; num++) { if (isPrime(num)) { noOfPrimeNumbers.getAndIncrement(); } } } private boolean isPrime(int number) { if (number == 2) { return true; } if (number == 1 || number % 2 == 0) {
return false; } int noOfNaturalNumbers = 0; for (int i = 1; i <= number; i++) { if (number % i == 0) { noOfNaturalNumbers++; } } return noOfNaturalNumbers == 2; } public int noOfPrimeNumbers() { return noOfPrimeNumbers.intValue(); } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-3\src\main\java\com\baeldung\workstealing\PrimeNumbers.java
1
请完成以下Java代码
protected void internalDbSchemaCreate() { // User and Group tables can already have been created by the process engine in an earlier version if (isIdmGroupTablePresent()) { schemaUpdate(); } else { super.internalDbSchemaCreate(); } } @Override protected boolean isUpdateNeeded() { boolean propertyTablePresent = isTablePresent(IDM_PROPERTY_TABLE); if (!propertyTablePresent) { return isIdmGroupTablePresent(); } return true; } public boolean isIdmGroupTablePresent() { return isTablePresent("ACT_ID_GROUP"); } @Override public void schemaCheckVersion() { try { String dbVersion = getSchemaVersion(); if (!IdmEngine.VERSION.equals(dbVersion)) { throw new FlowableWrongDbException(IdmEngine.VERSION, dbVersion); } String errorMessage = null; if (!isTablePresent(IDM_PROPERTY_TABLE)) { errorMessage = addMissingComponent(errorMessage, "engine"); }
if (errorMessage != null) { throw new FlowableException("Flowable IDM database problem: " + errorMessage); } } catch (Exception e) { if (isMissingTablesException(e)) { throw new FlowableException( "no flowable tables in db. set <property name=\"databaseSchemaUpdate\" to value=\"true\" or value=\"create-drop\" (use create-drop for testing only!) in bean processEngineConfiguration in flowable.cfg.xml for automatic schema creation", e); } else { if (e instanceof RuntimeException) { throw (RuntimeException) e; } else { throw new FlowableException("couldn't get db schema version", e); } } } logger.debug("flowable idm db schema check successful"); } protected String addMissingComponent(String missingComponents, String component) { if (missingComponents == null) { return "Tables missing for component(s) " + component; } return missingComponents + ", " + component; } @Override public String getContext() { return SCHEMA_COMPONENT; } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\db\IdmDbSchemaManager.java
1
请在Spring Boot框架中完成以下Java代码
public class GeneratorController { private final GeneratorService generatorService; private final GenConfigService genConfigService; @Value("${generator.enabled}") private Boolean generatorEnabled; @ApiOperation("查询数据库数据") @GetMapping(value = "/tables/all") public ResponseEntity<Object> queryAllTables(){ return new ResponseEntity<>(generatorService.getTables(), HttpStatus.OK); } @ApiOperation("查询数据库数据") @GetMapping(value = "/tables") public ResponseEntity<PageResult<TableInfo>> queryTables(@RequestParam(defaultValue = "") String name, @RequestParam(defaultValue = "0")Integer page, @RequestParam(defaultValue = "10")Integer size){ int[] startEnd = PageUtil.transToStartEnd(page, size); return new ResponseEntity<>(generatorService.getTables(name,startEnd), HttpStatus.OK); } @ApiOperation("查询字段数据") @GetMapping(value = "/columns") public ResponseEntity<PageResult<ColumnInfo>> queryColumns(@RequestParam String tableName){ List<ColumnInfo> columnInfos = generatorService.getColumns(tableName); return new ResponseEntity<>(PageUtil.toPage(columnInfos,columnInfos.size()), HttpStatus.OK); } @ApiOperation("保存字段数据") @PutMapping public ResponseEntity<HttpStatus> saveColumn(@RequestBody List<ColumnInfo> columnInfos){
generatorService.save(columnInfos); return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("同步字段数据") @PostMapping(value = "sync") public ResponseEntity<HttpStatus> syncColumn(@RequestBody List<String> tables){ for (String table : tables) { generatorService.sync(generatorService.getColumns(table), generatorService.query(table)); } return new ResponseEntity<>(HttpStatus.OK); } @ApiOperation("生成代码") @PostMapping(value = "/{tableName}/{type}") public ResponseEntity<Object> generatorCode(@PathVariable String tableName, @PathVariable Integer type, HttpServletRequest request, HttpServletResponse response){ if(!generatorEnabled && type == 0){ throw new BadRequestException("此环境不允许生成代码,请选择预览或者下载查看!"); } switch (type){ // 生成代码 case 0: generatorService.generator(genConfigService.find(tableName), generatorService.getColumns(tableName)); break; // 预览 case 1: return generatorService.preview(genConfigService.find(tableName), generatorService.getColumns(tableName)); // 打包 case 2: generatorService.download(genConfigService.find(tableName), generatorService.getColumns(tableName), request, response); break; default: throw new BadRequestException("没有这个选项"); } return new ResponseEntity<>(HttpStatus.OK); } }
repos\eladmin-master\eladmin-generator\src\main\java\me\zhengjie\rest\GeneratorController.java
2
请完成以下Java代码
void archive() { if (status != Status.ARCHIVED) { status = Status.ARCHIVED; } throw new IllegalStateException("the article is already archived"); } void comment(Username user, String message) { comments.add(new Comment(user, message)); } void like(Username user) { likedBy.add(user); } void dislike(Username user) { likedBy.remove(user); } public Slug getSlug() { return slug; }
public Username getAuthor() { return author; } public String getTitle() { return title; } public String getContent() { return content; } public Status getStatus() { return status; } public List<Comment> getComments() { return Collections.unmodifiableList(comments); } public List<Username> getLikedBy() { return Collections.unmodifiableList(likedBy); } }
repos\tutorials-master\patterns-modules\ddd\src\main\java\com\baeldung\dddjmolecules\article\Article.java
1
请在Spring Boot框架中完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } InfoFromBuyer infoFromBuyer = (InfoFromBuyer)o; return Objects.equals(this.note, infoFromBuyer.note) && Objects.equals(this.returnShipmentTracking, infoFromBuyer.returnShipmentTracking); } @Override public int hashCode() { return Objects.hash(note, returnShipmentTracking); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InfoFromBuyer {\n"); sb.append(" note: ").append(toIndentedString(note)).append("\n");
sb.append(" returnShipmentTracking: ").append(toIndentedString(returnShipmentTracking)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-ebay\ebay-api-client\src\main\java\de\metas\camel\externalsystems\ebay\api\model\InfoFromBuyer.java
2
请完成以下Java代码
public void propagatePOReferenceChangeToShipmentSchedule(@NonNull final I_C_Order order) { //retrieve and invalidate all related shipment schedules final Set<ShipmentScheduleId> shipmentScheduleIds = shipmentSchedulePA.retrieveScheduleIdsByOrderId(OrderId.ofRepoId(order.getC_Order_ID())); //invalidate all related shipment schedules scheduleInvalidateRepository.invalidateShipmentSchedules(shipmentScheduleIds); } @DocValidate(timings = { ModelValidator.TIMING_BEFORE_REACTIVATE }) public void reactivateIfNoActiveShipment(final I_C_Order order) { if (!isEligibleForShipmentSchedule(order)) { return; }
final ImmutableSet<I_M_InOut> activeShipments = inOutBL.getNotVoidedNotReversedForOrderId(OrderId.ofRepoId(order.getC_Order_ID())); if (!activeShipments.isEmpty()) { throw new AdempiereException( ERR_NoReactivationIfNotVoidedNotReversedShipments, activeShipments.stream().map(I_M_InOut::getDocumentNo).collect(Collectors.joining(", "))); } } public static boolean isEligibleForShipmentSchedule(@NonNull final I_C_Order order) { // Only Sales Orders are handled return order.isSOTrx(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\C_Order_ShipmentSchedule.java
1
请完成以下Java代码
public short getVersion() { return version; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) {
return false; } return id != null && id.equals(((Book) obj).id); } @Override public int hashCode() { return 2021; } @Override public String toString() { return "Book{" + "id=" + id + ", title=" + title + ", isbn=" + isbn + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootSaveAndMerge\src\main\java\com\bookstore\entity\Book.java
1
请在Spring Boot框架中完成以下Java代码
public I_C_BP_Group getByBPartnerId(@NonNull final BPartnerId bpartnerId) { final I_C_BPartner bpartnerRecord = Services.get(IBPartnerDAO.class).getById(bpartnerId); final BPGroupId bpGroupId = BPGroupId.ofRepoId(bpartnerRecord.getC_BP_Group_ID()); return getById(bpGroupId); } @Override public BPGroupId getBPGroupByBPartnerId(@NonNull final BPartnerId bpartnerId) { return BPGroupId.ofRepoId(getByBPartnerId(bpartnerId).getC_BP_Group_ID()); } @Override @Nullable public I_C_BP_Group getDefaultByClientOrgId(@NonNull final ClientAndOrgId clientAndOrgId) { final BPGroupId bpGroupId = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_C_BP_Group.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_C_BP_Group.COLUMNNAME_AD_Client_ID, clientAndOrgId.getClientId()) .addInArrayFilter(I_C_BP_Group.COLUMNNAME_AD_Org_ID, clientAndOrgId.getOrgId(), OrgId.ANY) .addEqualsFilter(I_C_BP_Group.COLUMNNAME_IsDefault, true) .orderByDescending(I_C_BP_Group.COLUMNNAME_AD_Org_ID) .create() .firstId(BPGroupId::ofRepoIdOrNull); if (bpGroupId == null) { logger.warn("No default BP group found for {}", clientAndOrgId); return null; }
return getById(bpGroupId); } @Override public BPartnerNameAndGreetingStrategyId getBPartnerNameAndGreetingStrategyId(@NonNull final BPGroupId bpGroupId) { final I_C_BP_Group bpGroup = getById(bpGroupId); return StringUtils.trimBlankToOptional(bpGroup.getBPNameAndGreetingStrategy()) .map(BPartnerNameAndGreetingStrategyId::ofString) .orElse(DoNothingBPartnerNameAndGreetingStrategy.ID); } @Override public void save(@NonNull final I_C_BP_Group bpGroup) { InterfaceWrapperHelper.saveRecord(bpGroup); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\bpartner\service\impl\BPGroupDAO.java
2
请在Spring Boot框架中完成以下Java代码
public class LotNumberQuarantineRepository { public LotNumberQuarantine getById(final int lotNoQuarantineId) { Check.assumeGreaterThanZero(lotNoQuarantineId, "lotNoQuarantineId"); final I_M_Product_LotNumber_Quarantine record = load(lotNoQuarantineId, I_M_Product_LotNumber_Quarantine.class); return toLotNumberQuarantine(record); } private static LotNumberQuarantine toLotNumberQuarantine(final I_M_Product_LotNumber_Quarantine record) { return LotNumberQuarantine.builder() .id(record.getM_Product_LotNumber_Quarantine_ID()) .productId(record.getM_Product_ID()) .lotNo(record.getLot()) .description(record.getDescription()) .build(); }
public LotNumberQuarantine getByProductIdAndLot(final ProductId productId, final String lotNo) { final I_M_Product_LotNumber_Quarantine record = Services.get(IQueryBL.class) .createQueryBuilder(I_M_Product_LotNumber_Quarantine.class) .addOnlyActiveRecordsFilter() .addOnlyContextClient() .addInArrayFilter(I_M_Product_LotNumber_Quarantine.COLUMN_M_Product_ID, productId, null) .addEqualsFilter(I_M_Product_LotNumber_Quarantine.COLUMNNAME_Lot, lotNo) .orderBy(I_M_Product_LotNumber_Quarantine.COLUMNNAME_M_Product_ID) .create() .first(); return record != null ? toLotNumberQuarantine(record) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\LotNumberQuarantineRepository.java
2
请在Spring Boot框架中完成以下Java代码
public void preInit(SpringProcessEngineConfiguration configuration) { final DatabaseProperty database = camundaBpmProperties.getDatabase(); if (camundaTransactionManager == null) { configuration.setTransactionManager(transactionManager); } else { configuration.setTransactionManager(camundaTransactionManager); } if (camundaDataSource == null) { configuration.setDataSource(dataSource); } else { configuration.setDataSource(camundaDataSource); } configuration.setDatabaseType(database.getType()); configuration.setDatabaseSchemaUpdate(database.getSchemaUpdate()); if (!StringUtils.isEmpty(database.getTablePrefix())) { configuration.setDatabaseTablePrefix(database.getTablePrefix()); } if(!StringUtils.isEmpty(database.getSchemaName())) { configuration.setDatabaseSchema(database.getSchemaName()); } configuration.setJdbcBatchProcessing(database.isJdbcBatchProcessing()); } public PlatformTransactionManager getTransactionManager() { return transactionManager; } public void setTransactionManager(PlatformTransactionManager transactionManager) { this.transactionManager = transactionManager; } public PlatformTransactionManager getCamundaTransactionManager() { return camundaTransactionManager; } public void setCamundaTransactionManager(PlatformTransactionManager camundaTransactionManager) {
this.camundaTransactionManager = camundaTransactionManager; } public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public DataSource getCamundaDataSource() { return camundaDataSource; } public void setCamundaDataSource(DataSource camundaDataSource) { this.camundaDataSource = camundaDataSource; } }
repos\camunda-bpm-platform-master\spring-boot-starter\starter\src\main\java\org\camunda\bpm\spring\boot\starter\configuration\impl\DefaultDatasourceConfiguration.java
2
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setOrg_ID (final int Org_ID) { if (Org_ID < 1) set_Value (COLUMNNAME_Org_ID, null); else set_Value (COLUMNNAME_Org_ID, Org_ID); } @Override public int getOrg_ID() { return get_ValueAsInt(COLUMNNAME_Org_ID); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } @Override public void setUserElementString1 (final @Nullable java.lang.String UserElementString1) { set_Value (COLUMNNAME_UserElementString1, UserElementString1); } @Override public java.lang.String getUserElementString1() { return get_ValueAsString(COLUMNNAME_UserElementString1); } @Override public void setUserElementString2 (final @Nullable java.lang.String UserElementString2) { set_Value (COLUMNNAME_UserElementString2, UserElementString2); } @Override public java.lang.String getUserElementString2() { return get_ValueAsString(COLUMNNAME_UserElementString2); }
@Override public void setUserElementString3 (final @Nullable java.lang.String UserElementString3) { set_Value (COLUMNNAME_UserElementString3, UserElementString3); } @Override public java.lang.String getUserElementString3() { return get_ValueAsString(COLUMNNAME_UserElementString3); } @Override public void setUserElementString4 (final @Nullable java.lang.String UserElementString4) { set_Value (COLUMNNAME_UserElementString4, UserElementString4); } @Override public java.lang.String getUserElementString4() { return get_ValueAsString(COLUMNNAME_UserElementString4); } @Override public void setUserElementString5 (final @Nullable java.lang.String UserElementString5) { set_Value (COLUMNNAME_UserElementString5, UserElementString5); } @Override public java.lang.String getUserElementString5() { return get_ValueAsString(COLUMNNAME_UserElementString5); } @Override public void setUserElementString6 (final @Nullable java.lang.String UserElementString6) { set_Value (COLUMNNAME_UserElementString6, UserElementString6); } @Override public java.lang.String getUserElementString6() { return get_ValueAsString(COLUMNNAME_UserElementString6); } @Override public void setUserElementString7 (final @Nullable java.lang.String UserElementString7) { set_Value (COLUMNNAME_UserElementString7, UserElementString7); } @Override public java.lang.String getUserElementString7() { return get_ValueAsString(COLUMNNAME_UserElementString7); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_AcctSchema_Element.java
1
请在Spring Boot框架中完成以下Java代码
public class ReductionExtensionType { @XmlElement(name = "TypeOfReduction", required = true) protected String typeOfReduction; /** * Gets the value of the typeOfReduction property. * * @return * possible object is * {@link String } * */ public String getTypeOfReduction() { return typeOfReduction;
} /** * Sets the value of the typeOfReduction property. * * @param value * allowed object is * {@link String } * */ public void setTypeOfReduction(String value) { this.typeOfReduction = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\extensions\edifact\ReductionExtensionType.java
2
请完成以下Java代码
public void deleteNotificationRuleById(TenantId tenantId, NotificationRuleId id) { notificationRuleDao.removeById(tenantId, id.getId()); eventPublisher.publishEvent(DeleteEntityEvent.builder().tenantId(tenantId).entityId(id).build()); } @Override public void deleteEntity(TenantId tenantId, EntityId id, boolean force) { deleteNotificationRuleById(tenantId, (NotificationRuleId) id); } @Override public void deleteNotificationRulesByTenantId(TenantId tenantId) { notificationRuleDao.removeByTenantId(tenantId); } @Override public void deleteByTenantId(TenantId tenantId) { deleteNotificationRulesByTenantId(tenantId); }
@Override public Optional<HasId<?>> findEntity(TenantId tenantId, EntityId entityId) { return Optional.ofNullable(findNotificationRuleById(tenantId, new NotificationRuleId(entityId.getId()))); } @Override public FluentFuture<Optional<HasId<?>>> findEntityAsync(TenantId tenantId, EntityId entityId) { return FluentFuture.from(notificationRuleDao.findByIdAsync(tenantId, entityId.getId())) .transform(Optional::ofNullable, directExecutor()); } @Override public EntityType getEntityType() { return EntityType.NOTIFICATION_RULE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\notification\DefaultNotificationRuleService.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public Tag name(String name) { this.name = name; return this; } /** * Get name * @return name **/ @javax.annotation.Nullable @ApiModelProperty(value = "") @JsonProperty(JSON_PROPERTY_NAME) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public String getName() { return name; } public void setName(String name) { this.name = name; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true;
} if (o == null || getClass() != o.getClass()) { return false; } Tag tag = (Tag) o; return Objects.equals(this.id, tag.id) && Objects.equals(this.name, tag.name); } @Override public int hashCode() { return Objects.hash(id, name); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Tag {\n"); sb.append(" id: ").append(toIndentedString(id)).append("\n"); sb.append(" name: ").append(toIndentedString(name)).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-openapi-generator-api-client\src\main\java\com\baeldung\petstore\client\model\Tag.java
1
请完成以下Java代码
public final void run() { final FormFrame formFrame = AEnv.createForm(getAD_Form()); if (formFrame == null) { return; } customizeBeforeOpen(formFrame); AEnv.showCenterWindow(getCallingFrame(), formFrame); } protected void customizeBeforeOpen(final FormFrame formFrame) { // nothing on this level } /** @return the {@link Frame} in which this action was executed or <code>null</code> if not available. */ protected final Frame getCallingFrame() { final GridField gridField = getContext().getEditor().getField(); if (gridField == null) { return null; } final int windowNo = gridField.getWindowNo(); final Frame frame = Env.getWindow(windowNo); return frame; } protected final int getAD_Form_ID() { return _adFormId; } private final synchronized I_AD_Form getAD_Form() { if (!_adFormLoaded) { _adForm = retrieveAD_Form();
_adFormLoaded = true; } return _adForm; } private final I_AD_Form retrieveAD_Form() { final IContextMenuActionContext context = getContext(); Check.assumeNotNull(context, "context not null"); final Properties ctx = context.getCtx(); // Check if user has access to Payment Allocation form final int adFormId = getAD_Form_ID(); final Boolean formAccess = Env.getUserRolePermissions().checkFormAccess(adFormId); if (formAccess == null || !formAccess) { return null; } // Retrieve the form final I_AD_Form form = InterfaceWrapperHelper.create(ctx, adFormId, I_AD_Form.class, ITrx.TRXNAME_None); // Translate it to user's language final I_AD_Form formTrl = InterfaceWrapperHelper.translate(form, I_AD_Form.class); return formTrl; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\OpenFormContextMenuAction.java
1
请完成以下Java代码
public class FieldBaseStructureInstance implements StructureInstance { protected FieldBaseStructureDefinition structureDefinition; protected Map<String, Object> fieldValues; public FieldBaseStructureInstance(FieldBaseStructureDefinition structureDefinition) { this.structureDefinition = structureDefinition; this.fieldValues = new HashMap<String, Object>(); } public Object getFieldValue(String fieldName) { return this.fieldValues.get(fieldName); } public void setFieldValue(String fieldName, Object value) { this.fieldValues.put(fieldName, value); } public int getFieldSize() { return this.structureDefinition.getFieldSize(); } public String getFieldNameAt(int index) { return this.structureDefinition.getFieldNameAt(index); }
public Object[] toArray() { int fieldSize = this.getFieldSize(); Object[] arguments = new Object[fieldSize]; for (int i = 0; i < fieldSize; i++) { String fieldName = this.getFieldNameAt(i); Object argument = this.getFieldValue(fieldName); arguments[i] = argument; } return arguments; } public void loadFrom(Object[] array) { int fieldSize = this.getFieldSize(); for (int i = 0; i < fieldSize; i++) { String fieldName = this.getFieldNameAt(i); Object fieldValue = array[i]; this.setFieldValue(fieldName, fieldValue); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\data\FieldBaseStructureInstance.java
1
请完成以下Java代码
public class PaymentString { @Nullable private final List<String> collectedErrors; @NonNull private final String rawPaymentString; @Nullable private final String postAccountNo; @Nullable private final String innerAccountNo; @Nullable private final BigDecimal amount; @NonNull private final String referenceNoComplete; private final Timestamp paymentDate; private final Timestamp accountDate; private final String orgValue; @Nullable private final String IBAN; private IPaymentStringDataProvider dataProvider;
public void setDataProvider(final IPaymentStringDataProvider dataProvider) { this.dataProvider = dataProvider; } public IPaymentStringDataProvider getDataProvider() { return dataProvider; } @Override public String toString() { return ObjectUtils.toString(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java\de\metas\banking\payment\PaymentString.java
1
请完成以下Java代码
public class ChildPK implements Serializable { @Column(name = "FATHER_ID", nullable = false) private Long fatherId; @Column(name = "MOTHER_ID", nullable = false) private Long motherId; public ChildPK() { } public ChildPK(Father father, Mother mother) { this.fatherId = father.getId(); this.motherId = mother.getId(); } public Long getFatherId() { return fatherId; } public void setFatherId(Long fatherId) { this.fatherId = fatherId; } public Long getMotherId() { return motherId; } public void setMotherId(Long motherId) { this.motherId = motherId;
} @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ChildPK childPK = (ChildPK) o; return Objects.equals(fatherId, childPK.fatherId) && Objects.equals(motherId, childPK.motherId); } @Override public int hashCode() { return Objects.hash(fatherId, motherId); } }
repos\springboot-demo-master\olingo\src\main\java\com\et\olingo\entity\ChildPK.java
1
请完成以下Java代码
public XMLGregorianCalendar getCaseDate() { return caseDate; } /** * Sets the value of the caseDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setCaseDate(XMLGregorianCalendar value) { this.caseDate = value; } /** * Gets the value of the contractNumber property. * * @return * possible object is
* {@link String } * */ public String getContractNumber() { return contractNumber; } /** * Sets the value of the contractNumber property. * * @param value * allowed object is * {@link String } * */ public void setContractNumber(String value) { this.contractNumber = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\KvgLawType.java
1
请完成以下Java代码
private final List<IStorageRecord> createHUStorageRecords(final IContextAware context, final Collection<I_M_HU_Storage> huStorages) { if (huStorages == null || huStorages.isEmpty()) { return Collections.emptyList(); } // // Get the attribute storage factory final IHUContextFactory huContextFactory = Services.get(IHUContextFactory.class); final IHUContext huContext = huContextFactory.createMutableHUContext(context); final IAttributeStorageFactory huAttributeStorageFactory = huContext.getHUAttributeStorageFactory(); // // Iterate them and build up the IStorageRecord list final Map<Integer, HUStorageRecord_HUPart> huId2huPart = new HashMap<>(); final List<IStorageRecord> huStorageRecords = new ArrayList<>(); for (final I_M_HU_Storage huStorage : huStorages) { // Get/Create the HU Part of the Storage Record // NOTE: we are using a map to re-use the HUPart for same HU (optimization) final int huId = huStorage.getM_HU_ID(); HUStorageRecord_HUPart huPart = huId2huPart.get(huId); if (huPart == null) { final I_M_HU hu = huStorage.getM_HU(); final IAttributeStorage huAttributes = huAttributeStorageFactory.getAttributeStorage(hu); huPart = new HUStorageRecord_HUPart(hu, huAttributes); huId2huPart.put(huId, huPart); } // Create the Storage Record and collect it final HUStorageRecord huStorageRecord = new HUStorageRecord(huPart, huStorage); huStorageRecords.add(huStorageRecord);
} return huStorageRecords; } @Override public IAttributeSet getAttributeSet(@NonNull final I_M_AttributeSetInstance asi) { final IHUContextFactory huContextFactory = Services.get(IHUContextFactory.class); final IContextAware contextProvider = InterfaceWrapperHelper.getContextAware(asi); final IHUContext huContext = huContextFactory.createMutableHUContext(contextProvider); return huContext.getHUAttributeStorageFactory().getAttributeStorage(asi); } private final int getQueriesPerChunk() { final int queriesPerChunk = Services.get(ISysConfigBL.class).getIntValue(SYSCONFIG_QueriesPerChunk, DEFAULT_QueriesPerChunk); return queriesPerChunk; } @Override public String toString() { return "HUStorageEngine []"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\storage\spi\hu\impl\HUStorageEngine.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonCreateReceiptInfo { @JsonProperty("externalId") String externalId; @JsonProperty("receiptScheduleId") @NonNull JsonMetasfreshId receiptScheduleId; @JsonProperty("productSearchKey") String productSearchKey; @JsonProperty("movementQuantity") BigDecimal movementQuantity; @JsonProperty("dateReceived") LocalDateTime dateReceived;
@JsonProperty("movementDate") LocalDate movementDate; @JsonProperty("attributes") List<JsonAttributeInstance> attributes; @JsonProperty("externalResourceURL") String externalResourceURL; @JsonPOJOBuilder(withPrefix = "") @JsonIgnoreProperties(ignoreUnknown = true) public static class JsonCreateReceiptInfoBuilder { } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-shipping\src\main\java\de\metas\common\shipping\v1\receipt\JsonCreateReceiptInfo.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable LeakDetection getLeakDetection() { return this.leakDetection; } public void setLeakDetection(@Nullable LeakDetection leakDetection) { this.leakDetection = leakDetection; } public enum LeakDetection { /** * Disable leak detection completely. */ DISABLED, /** * Detect leaks for 1% of buffers.
*/ SIMPLE, /** * Detect leaks for 1% of buffers and track where they were accessed. */ ADVANCED, /** * Detect leaks for 100% of buffers and track where they were accessed. */ PARANOID } }
repos\spring-boot-4.0.1\module\spring-boot-netty\src\main\java\org\springframework\boot\netty\autoconfigure\NettyProperties.java
2
请完成以下Java代码
public boolean isLeftValue() { return node.isLeftValue(); } /** * Answer <code>true</code> if this is a deferred expression (containing * sub-expressions starting with <code>#{</code>) */ public boolean isDeferred() { return deferred; } /** * Expressions are compared using the concept of a <em>structural id</em>: * variable and function names are anonymized such that two expressions with * same tree structure will also have the same structural id and vice versa. * Two value expressions are equal if * <ol> * <li>their structural id's are equal</li> * <li>their bindings are equal</li> * <li>their expected types are equal</li> * </ol> */ @Override public boolean equals(Object obj) { if (obj != null && obj.getClass() == getClass()) { TreeValueExpression other = (TreeValueExpression) obj; if (!builder.equals(other.builder)) { return false; } if (type != other.type) { return false; } return (getStructuralId().equals(other.getStructuralId()) && bindings.equals(other.bindings)); } return false; }
@Override public int hashCode() { return getStructuralId().hashCode(); } @Override public String toString() { return "TreeValueExpression(" + expr + ")"; } /** * Print the parse tree. * @param writer */ public void dump(PrintWriter writer) { NodePrinter.dump(writer, node); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); try { node = builder.build(expr).getRoot(); } catch (ELException e) { throw new IOException(e.getMessage()); } } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\TreeValueExpression.java
1
请完成以下Java代码
public ResponseEntity<ApiError> handleException(Throwable e){ // 打印堆栈信息 log.error(ThrowableUtil.getStackTrace(e)); return buildResponseEntity(ApiError.error(e.getMessage())); } /** * BadCredentialsException */ @ExceptionHandler(BadCredentialsException.class) public ResponseEntity<ApiError> badCredentialsException(BadCredentialsException e){ // 打印堆栈信息 String message = "坏的凭证".equals(e.getMessage()) ? "用户名或密码不正确" : e.getMessage(); log.error(message); return buildResponseEntity(ApiError.error(message)); } /** * 处理自定义异常 */ @ExceptionHandler(value = BadRequestException.class) public ResponseEntity<ApiError> badRequestException(BadRequestException e) { // 打印堆栈信息 log.error(ThrowableUtil.getStackTrace(e)); return buildResponseEntity(ApiError.error(e.getStatus(),e.getMessage())); } /** * 处理 EntityExist */ @ExceptionHandler(value = EntityExistException.class) public ResponseEntity<ApiError> entityExistException(EntityExistException e) { // 打印堆栈信息 log.error(ThrowableUtil.getStackTrace(e)); return buildResponseEntity(ApiError.error(e.getMessage())); } /** * 处理 EntityNotFound */ @ExceptionHandler(value = EntityNotFoundException.class) public ResponseEntity<ApiError> entityNotFoundException(EntityNotFoundException e) { // 打印堆栈信息 log.error(ThrowableUtil.getStackTrace(e)); return buildResponseEntity(ApiError.error(NOT_FOUND.value(),e.getMessage())); }
/** * 处理所有接口数据验证异常 */ @ExceptionHandler(MethodArgumentNotValidException.class) public ResponseEntity<ApiError> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){ // 打印堆栈信息 log.error(ThrowableUtil.getStackTrace(e)); ObjectError objectError = e.getBindingResult().getAllErrors().get(0); String message = objectError.getDefaultMessage(); if (objectError instanceof FieldError) { message = ((FieldError) objectError).getField() + ": " + message; } return buildResponseEntity(ApiError.error(message)); } /** * 统一返回 */ private ResponseEntity<ApiError> buildResponseEntity(ApiError apiError) { return new ResponseEntity<>(apiError, HttpStatus.valueOf(apiError.getStatus())); } }
repos\eladmin-master\eladmin-common\src\main\java\me\zhengjie\exception\handler\GlobalExceptionHandler.java
1
请完成以下Java代码
public boolean isCoProduct() { return this == CoProduct; } public boolean isByProduct() { return this == ByProduct; } public boolean isByOrCoProduct() { return isByProduct() || isCoProduct(); } public boolean isVariant() { return this == Variant; } public boolean isPhantom() { return this == Phantom; } public boolean isTools()
{ return this == Tools; } // public boolean isReceipt() { return isByOrCoProduct(); } public boolean isIssue() { return !isReceipt(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\eevolution\api\BOMComponentType.java
1
请在Spring Boot框架中完成以下Java代码
public DynamicAttrConfig createAbcBean() { return new DynamicAttrConfig(); } // /** * 存在Abc类的实例时 */ @ConditionalOnBean(DynamicAttrConfig.class) @Bean public String bean() { System.err.println("ConditionalOnBean is exist"); return ""; } @ConditionalOnMissingBean(DynamicAttrConfig.class) @Bean public String missBean() { System.err.println("ConditionalOnBean is missing"); return ""; } /** * 表达式为true时 * spel http://itmyhome.com/spring/expressions.html */ @ConditionalOnExpression(value = "2 > 1") @Bean public String expresssion() { System.err.println("expresssion is true"); return ""; } /** * 配置文件属性是否为true */ @ConditionalOnProperty(value = {"spring.activemq.switch"}, matchIfMissing = false)
@Bean public String property() { System.err.println("property is true"); return ""; } /** * 打印容器里的所有bean name (box name 为方法名) * @param appContext * @return */ @Bean public CommandLineRunner run(ApplicationContext appContext) { return args -> { String[] beans = appContext.getBeanDefinitionNames(); Arrays.stream(beans).sorted().forEach(System.out::println); }; } }
repos\spring-boot-quick-master\quick-dynamic-bean\src\main\java\com\dynamic\bean\config\ConditionConfig.java
2
请在Spring Boot框架中完成以下Java代码
public final class CacheAutoConfiguration { @Bean @ConditionalOnMissingBean CacheManagerCustomizers cacheManagerCustomizers(ObjectProvider<CacheManagerCustomizer<?>> customizers) { return new CacheManagerCustomizers(customizers.orderedStream().toList()); } @Bean CacheManagerValidator cacheAutoConfigurationValidator(CacheProperties cacheProperties, ObjectProvider<CacheManager> cacheManager) { return new CacheManagerValidator(cacheProperties, cacheManager); } @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ EntityManagerFactoryDependsOnPostProcessor.class, LocalContainerEntityManagerFactoryBean.class }) @ConditionalOnBean(AbstractEntityManagerFactoryBean.class) @Import(CacheManagerEntityManagerFactoryDependsOnPostProcessor.class) static class CacheManagerEntityManagerFactoryDependsOnConfiguration { } static class CacheManagerEntityManagerFactoryDependsOnPostProcessor extends EntityManagerFactoryDependsOnPostProcessor { CacheManagerEntityManagerFactoryDependsOnPostProcessor() { super("cacheManager"); } } /** * Bean used to validate that a CacheManager exists and provide a more meaningful * exception. */ static class CacheManagerValidator implements InitializingBean { private final CacheProperties cacheProperties; private final ObjectProvider<CacheManager> cacheManager;
CacheManagerValidator(CacheProperties cacheProperties, ObjectProvider<CacheManager> cacheManager) { this.cacheProperties = cacheProperties; this.cacheManager = cacheManager; } @Override public void afterPropertiesSet() { Assert.state(this.cacheManager.getIfAvailable() != null, () -> "No cache manager could be auto-configured, check your configuration (caching type is '" + this.cacheProperties.getType() + "')"); } } /** * {@link ImportSelector} to add {@link CacheType} configuration classes. */ static class CacheConfigurationImportSelector implements ImportSelector { @Override public String[] selectImports(AnnotationMetadata importingClassMetadata) { CacheType[] types = CacheType.values(); String[] imports = new String[types.length]; for (int i = 0; i < types.length; i++) { imports[i] = CacheConfigurations.getConfigurationClass(types[i]); } return imports; } } }
repos\spring-boot-4.0.1\module\spring-boot-cache\src\main\java\org\springframework\boot\cache\autoconfigure\CacheAutoConfiguration.java
2
请完成以下Java代码
private XmlEsr createEsrQrFromEsr9WithExistingBank(final @NonNull XmlEsr9 esr9, @NonNull final String qrIban) { final XmlEsrQR.XmlEsrQRBuilder xEsrQR = XmlEsrQR.builder(); xEsrQR.bank(esr9.getBank()); xEsrQR.creditor(esr9.getCreditor()); xEsrQR.type(jaxbRequestObjectFactory.createEsrQRType().getType()); xEsrQR.iban(qrIban); xEsrQR.referenceNumber(StringUtils.cleanWhitespace(esr9.getReferenceNumber())); xEsrQR.paymentReason(Collections.emptyList()); return xEsrQR.build(); } private XmlEsr createEsrQrFromEsr9UsingDbInfo(final @NonNull XmlEsr9 esr9, @NonNull final BPartnerBankAccount bankAccount, @NonNull final Bank bank, @NonNull final Location location) { final XmlEsrQR.XmlEsrQRBuilder xEsrQR = XmlEsrQR.builder(); xEsrQR.bank(CoalesceUtil.coalesceSuppliers(esr9::getBank, () -> createEsrBank(bank, location))); xEsrQR.creditor(esr9.getCreditor()); xEsrQR.type(jaxbRequestObjectFactory.createEsrQRType().getType()); xEsrQR.iban(bankAccount.getQrIban()); xEsrQR.referenceNumber(StringUtils.cleanWhitespace(esr9.getReferenceNumber())); xEsrQR.paymentReason(Collections.emptyList()); return xEsrQR.build(); } private XmlAddress createEsrBank(final @NonNull Bank bank, @NonNull final Location location) { return XmlAddress.builder() .company(XmlCompany.builder() .companyname(bank.getBankName()) .postal(XmlPostal.builder() .zip(location.getPostal()) .city(location.getCity()) .countryCode(location.getCountryCode())
.build()) .build()) .build(); } private boolean isXmlEsr9(final XmlRequest xAugmentedRequest) { return xAugmentedRequest.getPayload().getBody().getEsr() instanceof XmlEsr9; } @Nullable private BPartnerBankAccount getBPartnerBankAccountOrNull(final BPartnerId bpartnerID) { return bpBankAccountDAO.getBpartnerBankAccount(BankAccountQuery.builder() .bpBankAcctUses(ImmutableSet.of(BPBankAcctUse.DEBIT_OR_DEPOSIT, BPBankAcctUse.DEPOSIT)) .containsQRIBAN(true) .bPartnerId(bpartnerID) .build()) .stream() .findFirst() .orElse(null); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_450_request\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_450\Invoice450FromCrossVersionModelTool.java
1
请完成以下Java代码
public class X_C_TaxPostal extends PO implements I_C_TaxPostal, I_Persistent { /** * */ private static final long serialVersionUID = 20090915L; /** Standard Constructor */ public X_C_TaxPostal (Properties ctx, int C_TaxPostal_ID, String trxName) { super (ctx, C_TaxPostal_ID, trxName); /** if (C_TaxPostal_ID == 0) { setC_Tax_ID (0); setC_TaxPostal_ID (0); setPostal (null); } */ } /** Load Constructor */ public X_C_TaxPostal (Properties ctx, ResultSet rs, String trxName) { super (ctx, rs, trxName); } /** AccessLevel * @return 2 - Client */ protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_C_TaxPostal[") .append(get_ID()).append("]"); return sb.toString(); } public I_C_Tax getC_Tax() throws RuntimeException { return (I_C_Tax)MTable.get(getCtx(), I_C_Tax.Table_Name) .getPO(getC_Tax_ID(), get_TrxName()); } /** Set Tax. @param C_Tax_ID Tax identifier */ public void setC_Tax_ID (int C_Tax_ID) { if (C_Tax_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Tax_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Tax_ID, Integer.valueOf(C_Tax_ID)); } /** Get Tax. @return Tax identifier */ public int getC_Tax_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Tax_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Tax ZIP.
@param C_TaxPostal_ID Tax Postal/ZIP */ public void setC_TaxPostal_ID (int C_TaxPostal_ID) { if (C_TaxPostal_ID < 1) set_ValueNoCheck (COLUMNNAME_C_TaxPostal_ID, null); else set_ValueNoCheck (COLUMNNAME_C_TaxPostal_ID, Integer.valueOf(C_TaxPostal_ID)); } /** Get Tax ZIP. @return Tax Postal/ZIP */ public int getC_TaxPostal_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxPostal_ID); if (ii == null) return 0; return ii.intValue(); } /** Set ZIP. @param Postal Postal code */ public void setPostal (String Postal) { set_Value (COLUMNNAME_Postal, Postal); } /** Get ZIP. @return Postal code */ public String getPostal () { return (String)get_Value(COLUMNNAME_Postal); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getPostal()); } /** Set ZIP To. @param Postal_To Postal code to */ public void setPostal_To (String Postal_To) { set_Value (COLUMNNAME_Postal_To, Postal_To); } /** Get ZIP To. @return Postal code to */ public String getPostal_To () { return (String)get_Value(COLUMNNAME_Postal_To); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_TaxPostal.java
1
请完成以下Java代码
public String getLieferscheinnummer() { return lieferscheinnummer; } /** * Sets the value of the lieferscheinnummer property. * * @param value * allowed object is * {@link String } * */ public void setLieferscheinnummer(String value) { this.lieferscheinnummer = value; } /** * Gets the value of the barcodeReferenz property. * * @return * possible object is * {@link String }
* */ public String getBarcodeReferenz() { return barcodeReferenz; } /** * Sets the value of the barcodeReferenz property. * * @param value * allowed object is * {@link String } * */ public void setBarcodeReferenz(String value) { this.barcodeReferenz = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.schema.v2\src\main\java-xjc\de\metas\vertical\pharma\vendor\gateway\msv3\schema\v2\LieferavisAbfrageHistAbfrage.java
1
请完成以下Java代码
public static CoreDictionary.Attribute guessAttribute(Term term) { CoreDictionary.Attribute attribute = CoreDictionary.get(term.word); if (attribute == null) { attribute = CustomDictionary.get(term.word); } if (attribute == null) { if (term.nature != null) { if (Nature.nx == term.nature) attribute = new CoreDictionary.Attribute(Nature.nx); else if (Nature.m == term.nature) attribute = CoreDictionary.get(CoreDictionary.M_WORD_ID); } else if (term.word.trim().length() == 0) attribute = new CoreDictionary.Attribute(Nature.x); else attribute = new CoreDictionary.Attribute(Nature.nz); } else term.nature = attribute.nature[0]; return attribute; } /** * 以下方法用于纯分词模型 * 分词、词性标注联合模型则直接重载segSentence */ @Override protected List<Term> segSentence(char[] sentence) { if (sentence.length == 0) return Collections.emptyList(); List<Term> termList = roughSegSentence(sentence); if (!(config.ner || config.useCustomDictionary || config.speechTagging)) return termList; List<Vertex> vertexList = toVertexList(termList, true); if (config.speechTagging) { Viterbi.compute(vertexList, CoreDictionaryTransformMatrixDictionary.transformMatrixDictionary); int i = 0; for (Term term : termList) { if (term.nature != null) term.nature = vertexList.get(i + 1).guessNature(); ++i; } } if (config.useCustomDictionary) { combineByCustomDictionary(vertexList); termList = convert(vertexList, config.offset); } return termList; }
/** * 单纯的分词模型实现该方法,仅输出词 * @param sentence * @return */ protected abstract List<Term> roughSegSentence(char[] sentence); /** * 将中间结果转换为词网顶点, * 这样就可以利用基于Vertex开发的功能, 如词性标注、NER等 * @param wordList * @param appendStart * @return */ protected List<Vertex> toVertexList(List<Term> wordList, boolean appendStart) { ArrayList<Vertex> vertexList = new ArrayList<Vertex>(wordList.size() + 2); if (appendStart) vertexList.add(Vertex.newB()); for (Term word : wordList) { CoreDictionary.Attribute attribute = guessAttribute(word); Vertex vertex = new Vertex(word.word, attribute); vertexList.add(vertex); } if (appendStart) vertexList.add(Vertex.newE()); return vertexList; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\seg\CharacterBasedSegment.java
1
请完成以下Java代码
public PublicKey getPublicKey(Resource resource, KeyFormat format) { byte[] keyBytes = getResourceBytes(resource); if (format == KeyFormat.PEM) { keyBytes = decodePem(keyBytes, PUBLIC_KEY_HEADER, PUBLIC_KEY_FOOTER); } X509EncodedKeySpec spec = new X509EncodedKeySpec(keyBytes); KeyFactory kf = KeyFactory.getInstance("RSA"); return kf.generatePublic(spec); } /** * <p>encrypt.</p> * * @param msg an array of {@link byte} objects * @param key a {@link java.security.PublicKey} object * @return an array of {@link byte} objects */ @SneakyThrows public byte[] encrypt(byte[] msg, PublicKey key) { final Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.ENCRYPT_MODE, key); return cipher.doFinal(msg); } /**
* <p>decrypt.</p> * * @param msg an array of {@link byte} objects * @param key a {@link java.security.PrivateKey} object * @return an array of {@link byte} objects */ @SneakyThrows public byte[] decrypt(byte[] msg, PrivateKey key) { final Cipher cipher = Cipher.getInstance("RSA"); cipher.init(Cipher.DECRYPT_MODE, key); return cipher.doFinal(msg); } public enum KeyFormat { DER, PEM; } }
repos\jasypt-spring-boot-master\jasypt-spring-boot\src\main\java\com\ulisesbocchio\jasyptspringboot\util\AsymmetricCryptography.java
1
请完成以下Spring Boot application配置
com: baeldung: sendgrid: api-key: ${SENDGRID_API_KEY} from-email: ${SENDGRID_FROM_EMAIL} from-name: ${SENDGRID_FROM_NAME} hydration-a
lert-notification: template-id: ${HYDRATION_ALERT_TEMPLATE_ID}
repos\tutorials-master\saas-modules\sendgrid\src\main\resources\application.yaml
2
请完成以下Java代码
private void splitNodeToParentAndChild(Node parentNode, String parentNewText, String childNewText) { Node childNode = new Node(childNewText, parentNode.getPosition()); if (parentNode.getChildren() .size() > 0) { while (parentNode.getChildren() .size() > 0) { childNode.getChildren() .add(parentNode.getChildren() .remove(0)); } } parentNode.getChildren() .add(childNode); parentNode.setText(parentNewText); parentNode.setPosition(POSITION_UNDEFINED); } private String getLongestCommonPrefix(String str1, String str2) { int compareLength = Math.min(str1.length(), str2.length()); for (int i = 0; i < compareLength; i++) { if (str1.charAt(i) != str2.charAt(i)) { return str1.substring(0, i); } } return str1.substring(0, compareLength); } private List<Node> getAllNodesInTraversePath(String pattern, Node startNode, boolean isAllowPartialMatch) { List<Node> nodes = new ArrayList<>(); for (int i = 0; i < startNode.getChildren() .size(); i++) { Node currentNode = startNode.getChildren() .get(i); String nodeText = currentNode.getText(); if (pattern.charAt(0) == nodeText.charAt(0)) { if (isAllowPartialMatch && pattern.length() <= nodeText.length()) { nodes.add(currentNode); return nodes; } int compareLength = Math.min(nodeText.length(), pattern.length()); for (int j = 1; j < compareLength; j++) {
if (pattern.charAt(j) != nodeText.charAt(j)) { if (isAllowPartialMatch) { nodes.add(currentNode); } return nodes; } } nodes.add(currentNode); if (pattern.length() > compareLength) { List<Node> nodes2 = getAllNodesInTraversePath(pattern.substring(compareLength), currentNode, isAllowPartialMatch); if (nodes2.size() > 0) { nodes.addAll(nodes2); } else if (!isAllowPartialMatch) { nodes.add(null); } } return nodes; } } return nodes; } public String printTree() { return root.printTree(""); } }
repos\tutorials-master\algorithms-modules\algorithms-searching\src\main\java\com\baeldung\algorithms\suffixtree\SuffixTree.java
1
请在Spring Boot框架中完成以下Java代码
public static File getEmptyPNGFile() { File file = ImageUtils.emptyPNGFile; if (file == null || !file.exists() || !file.canRead()) { file = ImageUtils.emptyPNGFile = createTempPNGFile("empty", BaseEncoding.base64().decode(emptyPNGBase64Encoded)); } return file; } public static File createTempPNGFile(@NonNull final String filenamePrefix, byte[] content) { if (content == null || content.length <= 0) { return getEmptyPNGFile(); } try { final File tempFile = File.createTempFile(filenamePrefix, ".png"); try (final FileOutputStream out = new FileOutputStream(tempFile)) { out.write(content); } return tempFile; } catch (IOException e) { throw new AdempiereException("Failed creating the PNG temporary file with prefix `" + filenamePrefix + "`", e); } } public static Optional<File> createTempImageFile(@NonNull final AdImageId adImageId) { try
{ final I_AD_Image adImage = InterfaceWrapperHelper.load(adImageId, I_AD_Image.class); if (adImage == null) { return Optional.empty(); } final byte[] data = adImage.getBinaryData(); if (data == null || data.length <= 0) { return Optional.empty(); } return Optional.of(createTempPNGFile("AD_Image-" + adImageId.getRepoId() + "_", data)); } catch (Exception ex) { logger.warn("Failed creating temp PNG file for {}. Returning blank file.", adImageId, ex); return Optional.of(getEmptyPNGFile()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\metasfresh-report-service\src\main\java\de\metas\report\jasper\class_loader\images\ImageUtils.java
2
请在Spring Boot框架中完成以下Java代码
public class BookstoreController { private final BookstoreService bookstoreService; public BookstoreController(BookstoreService bookstoreService) { this.bookstoreService = bookstoreService; } @GetMapping("/booksAndauthors/1") public List<BookDto> fetchBooksWithAuthorsQueryBuilderMechanism() { return bookstoreService.fetchBooksWithAuthorsQueryBuilderMechanism(); } @GetMapping("/booksAndauthors/2") public List<BookDto> fetchBooksWithAuthorsViaQuery() { return bookstoreService.fetchBooksWithAuthorsViaQuery(); }
@GetMapping("/booksAndauthors/3") public List<SimpleBookDto> fetchBooksWithAuthorsViaQuerySimpleDto() { return bookstoreService.fetchBooksWithAuthorsViaQuerySimpleDto(); } @GetMapping("/booksAndauthors/4") public List<VirtualBookDto> fetchBooksWithAuthorsViaQueryVirtualDto() { return bookstoreService.fetchBooksWithAuthorsViaQueryVirtualDto(); } @GetMapping("/booksAndauthors/5") public List<Object[]> fetchBooksWithAuthorsViaArrayOfObjects() { return bookstoreService.fetchBooksWithAuthorsViaArrayOfObjects(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNestedVsVirtualProjection\src\main\java\com\bookstore\controller\BookstoreController.java
2
请完成以下Java代码
public static final Object[] getUIDefaults() { return new Object[] { uiClassID, MetasFreshScrollBarUI.class.getName() , KEY_Width, DEFAULT_Width , KEY_Track_Color, DEFAULT_Track_Color , KEY_Thumb_Color, DEFAULT_Thumb_Color , KEY_Thumb_MouseOver_Color, DEFAULT_Thumb_MouseOver_Color , KEY_Thumb_Dragging_Color, DEFAULT_Thumb_Dragging_Color }; } private final JButton noButton = new JButton() { private static final long serialVersionUID = 1L; @Override public Dimension getPreferredSize() { return new Dimension(0, 0); } }; private Color thumbColor; private Color thumbColorMouseOver; private Color thumbColorDragging; private boolean isMouseButtonPressed = false; MetasFreshScrollBarUI() { super(); noButton.setVisible(false); noButton.setEnabled(false); } @Override protected void installDefaults() { super.installDefaults(); trackColor = AdempierePLAF.getColor(KEY_Track_Color); thumbColor = AdempierePLAF.getColor(KEY_Thumb_Color, DEFAULT_Thumb_Color); thumbColorMouseOver = AdempierePLAF.getColor(KEY_Thumb_MouseOver_Color, DEFAULT_Thumb_MouseOver_Color); thumbColorDragging = AdempierePLAF.getColor(KEY_Thumb_Dragging_Color, DEFAULT_Thumb_Dragging_Color); scrollBarWidth = AdempierePLAF.getInt(KEY_Width, DEFAULT_Width); } @Override protected void paintThumb(final Graphics g, final JComponent c, final Rectangle r) { final Color color; if (!scrollbar.isEnabled()) { color = thumbColor; } else if (isDragging || isMouseButtonPressed) { color = thumbColorDragging; } else if (isThumbRollover()) { color = thumbColorMouseOver;
} else { color = thumbColor; } g.setColor(color); g.fillRect(r.x, r.y, r.width, r.height); } @Override protected void paintTrack(final Graphics g, final JComponent c, final Rectangle r) { g.setColor(trackColor); g.fillRect(r.x, r.y, r.width, r.height); } @Override protected JButton createDecreaseButton(final int orientation) { return noButton; } @Override protected JButton createIncreaseButton(final int orientation) { return noButton; } @Override protected TrackListener createTrackListener() { return new MetasTrackListener(); } private class MetasTrackListener extends TrackListener { @Override public void mousePressed(MouseEvent e) { isMouseButtonPressed = true; super.mousePressed(e); scrollbar.repaint(getThumbBounds()); } @Override public void mouseReleased(MouseEvent e) { isMouseButtonPressed = false; super.mouseReleased(e); scrollbar.repaint(getThumbBounds()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\plaf\MetasFreshScrollBarUI.java
1
请完成以下Java代码
public PI setTarget(String target) { setElementType(target); return(this); } /** * Add an additional instruction (which works like an XML * attribute) to the PI * * @param name - Name of instruction (e.g. standalone) * @param value - value of instruction (e.g. "no") */ public PI addInstruction(String name, String value) { addAttribute(name, value); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public PI addElement(String hashcode,Element element) { addElementToRegistry(hashcode,element); return(this); } /** Adds an Element to the element. @param hashcode name of element for hash table @param element Adds an Element to the element. */ public PI addElement(String hashcode,String element) { addElementToRegistry(hashcode,element); return(this); }
/** Adds an Element to the element. @param element Adds an Element to the element. */ public PI addElement(Element element) { addElementToRegistry(element); return(this); } /** Adds an Element to the element. @param element Adds an Element to the element. */ public PI addElement(String element) { addElementToRegistry(element); return(this); } /** Removes an Element from the element. @param hashcode the name of the element to be removed. */ public PI removeElement(String hashcode) { removeElementFromRegistry(hashcode); return(this); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xml\PI.java
1
请完成以下Java代码
public void setC_AcctSchema(final org.compiere.model.I_C_AcctSchema C_AcctSchema) { set_ValueFromPO(COLUMNNAME_C_AcctSchema_ID, org.compiere.model.I_C_AcctSchema.class, C_AcctSchema); } @Override public void setC_AcctSchema_ID (final int C_AcctSchema_ID) { if (C_AcctSchema_ID < 1) set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, null); else set_ValueNoCheck (COLUMNNAME_C_AcctSchema_ID, C_AcctSchema_ID); } @Override public int getC_AcctSchema_ID() { return get_ValueAsInt(COLUMNNAME_C_AcctSchema_ID); } @Override public void setC_Project_ID (final int C_Project_ID) { if (C_Project_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Project_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Project_ID, C_Project_ID); } @Override public int getC_Project_ID() { return get_ValueAsInt(COLUMNNAME_C_Project_ID); } @Override public org.compiere.model.I_C_ValidCombination getPJ_Asset_A() { return get_ValueAsPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setPJ_Asset_A(final org.compiere.model.I_C_ValidCombination PJ_Asset_A) { set_ValueFromPO(COLUMNNAME_PJ_Asset_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_Asset_A); }
@Override public void setPJ_Asset_Acct (final int PJ_Asset_Acct) { set_Value (COLUMNNAME_PJ_Asset_Acct, PJ_Asset_Acct); } @Override public int getPJ_Asset_Acct() { return get_ValueAsInt(COLUMNNAME_PJ_Asset_Acct); } @Override public org.compiere.model.I_C_ValidCombination getPJ_WIP_A() { return get_ValueAsPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class); } @Override public void setPJ_WIP_A(final org.compiere.model.I_C_ValidCombination PJ_WIP_A) { set_ValueFromPO(COLUMNNAME_PJ_WIP_Acct, org.compiere.model.I_C_ValidCombination.class, PJ_WIP_A); } @Override public void setPJ_WIP_Acct (final int PJ_WIP_Acct) { set_Value (COLUMNNAME_PJ_WIP_Acct, PJ_WIP_Acct); } @Override public int getPJ_WIP_Acct() { return get_ValueAsInt(COLUMNNAME_PJ_WIP_Acct); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Project_Acct.java
1
请完成以下Java代码
public MethodInfo getMethodInfo(Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes) { return null; } public boolean isLeftValue() { return false; } public boolean isMethodInvocation() { return true; } public final ValueReference getValueReference(Bindings bindings, ELContext context) { return null; } @Override public void appendStructure(StringBuilder builder, Bindings bindings) { property.appendStructure(builder, bindings); params.appendStructure(builder, bindings); } protected Object eval(Bindings bindings, ELContext context, boolean answerNullIfBaseIsNull) { Object base = property.getPrefix().eval(bindings, context); if (base == null) { if (answerNullIfBaseIsNull) { return null; } throw new PropertyNotFoundException(LocalMessages.get("error.property.base.null", property.getPrefix())); } Object method = property.getProperty(bindings, context); if (method == null) { throw new PropertyNotFoundException(LocalMessages.get("error.property.method.notfound", "null", base)); } String name = bindings.convert(method, String.class); context.setPropertyResolved(false); Object result = context.getELResolver().invoke(context, base, name, null, params.eval(bindings, context)); if (!context.isPropertyResolved()) { throw new MethodNotFoundException( LocalMessages.get("error.property.method.notfound", name, base.getClass()) ); } return result; } @Override public Object eval(Bindings bindings, ELContext context) { return eval(bindings, context, true);
} public Object invoke( Bindings bindings, ELContext context, Class<?> returnType, Class<?>[] paramTypes, Object[] paramValues ) { return eval(bindings, context, false); } public int getCardinality() { return 2; } public Node getChild(int i) { return i == 0 ? property : i == 1 ? params : null; } @Override public String toString() { return "<method>"; } }
repos\Activiti-develop\activiti-core-common\activiti-juel-jakarta\src\main\java\org\activiti\core\el\juel\tree\impl\ast\AstMethod.java
1
请完成以下Java代码
public void setFrequencyType (java.lang.String FrequencyType) { set_Value (COLUMNNAME_FrequencyType, FrequencyType); } /** Get Frequency Type. @return Frequency of event */ @Override public java.lang.String getFrequencyType () { return (java.lang.String)get_Value(COLUMNNAME_FrequencyType); } /** Set Next Payment Date. @param NextPaymentDate Next Payment Date */ @Override public void setNextPaymentDate (java.sql.Timestamp NextPaymentDate) { set_ValueNoCheck (COLUMNNAME_NextPaymentDate, NextPaymentDate); } /** Get Next Payment Date. @return Next Payment Date */ @Override public java.sql.Timestamp getNextPaymentDate () { return (java.sql.Timestamp)get_Value(COLUMNNAME_NextPaymentDate); } /** Set Payment amount. @param PayAmt Amount being paid */ @Override public void setPayAmt (java.math.BigDecimal PayAmt) { set_Value (COLUMNNAME_PayAmt, PayAmt); } /** Get Payment amount. @return Amount being paid */ @Override public java.math.BigDecimal getPayAmt ()
{ BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_PayAmt); if (bd == null) return BigDecimal.ZERO; return bd; } /** Set Aussendienst. @param SalesRep_ID Aussendienst */ @Override public void setSalesRep_ID (int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, Integer.valueOf(SalesRep_ID)); } /** Get Aussendienst. @return Aussendienst */ @Override public int getSalesRep_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_SalesRep_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.base\src\main\java-gen\de\metas\banking\model\X_C_RecurrentPaymentLine.java
1
请完成以下Java代码
public Optional<BankAccountId> retrieveByBPartnerAndCurrencyAndIBAN(@NonNull final BPartnerId bPartnerId, @NonNull final CurrencyId currencyId, @NonNull final String iban) { final BankAccountId bankAccountId = queryBL.createQueryBuilder(I_C_BP_BankAccount.class) .addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_C_BPartner_ID, bPartnerId) .addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_C_Currency_ID, currencyId) .addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_IBAN, iban) .addOnlyActiveRecordsFilter() .create() .firstIdOnly(BankAccountId::ofRepoIdOrNull); return Optional.ofNullable(bankAccountId); } @Override public BankId getBankId(@NonNull final BankAccountId bankAccountId) { return getById(bankAccountId).getBankId(); } @Override @NonNull public Optional<BankAccount> getDefaultBankAccount(@NonNull final BPartnerId bPartnerId) { return retrieveDefaultBankAccountInTrx(bPartnerId) .map(BPBankAccountDAO::toBankAccount); } @Override @NonNull public Optional<BankAccountId> getBankAccountId( @NonNull final BankId bankId,
@NonNull final String accountNo) { return queryBL.createQueryBuilder(I_C_BP_BankAccount.class) .addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_AccountNo, accountNo) .addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_C_Bank_ID, bankId) .addOnlyActiveRecordsFilter() .create() .firstOnlyOptional(I_C_BP_BankAccount.class) .map(bpBankAccount -> BankAccountId.ofRepoId(bpBankAccount.getC_BP_BankAccount_ID())); } @Override @NonNull public Optional<BankAccountId> getBankAccountIdByIBAN( @NonNull final String iban) { return queryBL.createQueryBuilder(I_C_BP_BankAccount.class) .addEqualsFilter(I_C_BP_BankAccount.COLUMNNAME_IBAN, iban, CleanWhitespaceQueryFilterModifier.getInstance()) .addOnlyActiveRecordsFilter() .create() .firstIdOnlyOptional(BankAccountId::ofRepoIdOrNull); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\banking\api\impl\BPBankAccountDAO.java
1
请完成以下Java代码
private static void addAll(final HashMultimap<ContextPath, String> target, @Nullable Map<String, String> source) { if (source == null || source.isEmpty()) {return;} source.forEach((pathStr, contextVariables) -> { final ContextPath path = ContextPath.ofJson(pathStr); COMMA_SPLITTER.splitToList(contextVariables) .forEach(missingContextVariable -> target.put(path, missingContextVariable)); }); } public void recordContextVariableUsed(final ContextPath path, final String contextVariable, boolean wasFound) { reportedMissingButNotUsed.remove(path, contextVariable); final boolean isKnownAsMissing = isKnownAsMissing(path, contextVariable); if (wasFound) { if (isKnownAsMissing) { reportedMissingButExists.put(path, contextVariable); } } else // not found { if (!isKnownAsMissing) { foundMissing.put(path, contextVariable); } } } public boolean isKnownAsMissing(final ContextPath path, String contextVariable)
{ return all.containsEntry(path, contextVariable); } public JsonContextVariablesResponse toJsonContextVariablesResponse() { return JsonContextVariablesResponse.builder() .missing(toKeyAndCommaSeparatedValues(foundMissing, adWindowIdsInScope)) .reportedMissingButNotUsed(toKeyAndCommaSeparatedValues(reportedMissingButNotUsed, adWindowIdsInScope)) .reportedMissingButExists(toKeyAndCommaSeparatedValues(reportedMissingButExists, adWindowIdsInScope)) .build(); } private static Map<String, String> toKeyAndCommaSeparatedValues( @NonNull final SetMultimap<ContextPath, String> multimap, @Nullable final AdWindowIdSelection adWindowIdsInScope) { final ImmutableMap.Builder<String, String> result = ImmutableMap.builder(); multimap.asMap().forEach((path, values) -> { if (adWindowIdsInScope != null && !adWindowIdsInScope.contains(path)) { return; } result.put(path.toJson(), Joiner.on(',').join(values)); }); return result.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\MissingContextVariables.java
1
请完成以下Java代码
public AssignableInvoiceCandidate ofRecord(@Nullable final I_C_Invoice_Candidate assignableRecord) { final InvoiceCandidateId invoiceCandidateId = InvoiceCandidateId.ofRepoId(assignableRecord.getC_Invoice_Candidate_ID()); final Timestamp invoicableFromDate = getValueOverrideOrValue(assignableRecord, I_C_Invoice_Candidate.COLUMNNAME_DateToInvoice); final BigDecimal moneyAmount = assignableRecord .getNetAmtInvoiced() .add(assignableRecord.getNetAmtToInvoice()); final CurrencyId currencyId = CurrencyId.ofRepoId(assignableRecord.getC_Currency_ID()); final CurrencyPrecision precision = currenciesRepo.getStdPrecision(currencyId); final Money money = Money.of(stripTrailingDecimalZeros(moneyAmount), currencyId); final Quantity quantity = extractQuantity(assignableRecord); final Quantity quantityOld = extractQuantity(createOld(assignableRecord, I_C_Invoice_Candidate.class)); final List<AssignmentToRefundCandidate> assignments = assignmentToRefundCandidateRepository.getAssignmentsByAssignableCandidateId(invoiceCandidateId); final BPartnerLocationAndCaptureId billLocationId = InvoiceCandidateLocationAdapterFactory .billLocationAdapter(assignableRecord) .getBPartnerLocationAndCaptureId(); return AssignableInvoiceCandidate.builder() .id(invoiceCandidateId) .bpartnerLocationId(billLocationId.getBpartnerLocationId()) .invoiceableFrom(TimeUtil.asLocalDate(invoicableFromDate)) .money(money) .precision(precision.toInt()) .quantity(quantity) .quantityOld(quantityOld)
.productId(ProductId.ofRepoId(assignableRecord.getM_Product_ID())) .assignmentsToRefundCandidates(assignments) .build(); } private Quantity extractQuantity(@NonNull final I_C_Invoice_Candidate assignableRecord) { final IUOMDAO uomDAO = Services.get(IUOMDAO.class); final IProductDAO productDAO = Services.get(IProductDAO.class); final I_M_Product product = productDAO.getById(assignableRecord.getM_Product_ID()); final I_C_UOM uom = uomDAO.getById(product.getC_UOM_ID()); final Quantity quantity = Quantity.of( assignableRecord.getQtyToInvoice().add(stripTrailingDecimalZeros(assignableRecord.getQtyInvoiced())), uom); return quantity; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\AssignableInvoiceCandidateFactory.java
1
请完成以下Java代码
public static UserAuthQRCode ofGlobalQRCodeJsonString(final String json) { return UserAuthQRCodeJsonConverter.fromGlobalQRCodeJsonString(json); } @NonNull public static UserAuthQRCode ofGlobalQRCode(final GlobalQRCode globalQRCode) { return UserAuthQRCodeJsonConverter.fromGlobalQRCode(globalQRCode); } @NonNull public static UserAuthQRCode ofAuthToken(@NonNull final UserAuthToken authToken) { return builder() .userId(authToken.getUserId()) .token(authToken.getAuthToken()) .build(); } @NonNull public PrintableQRCode toPrintableQRCode() { return PrintableQRCode.builder() .qrCode(toGlobalQRCodeJsonString())
.bottomText(getDisplayableQrCode()) .build(); } public String getDisplayableQrCode() { return String.valueOf(userId.getRepoId()); } @NonNull public String toGlobalQRCodeJsonString() { return UserAuthQRCodeJsonConverter.toGlobalQRCodeJsonString(this); } public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode) { return UserAuthQRCodeJsonConverter.isTypeMatching(globalQRCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\qr\UserAuthQRCode.java
1
请完成以下Java代码
public boolean reverseCorrectIt() { log.info(toString()); // Before reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_BEFORE_REVERSECORRECT); if (m_processMsg != null) return false; // After reverseCorrect m_processMsg = ModelValidationEngine.get().fireDocValidate(this, ModelValidator.TIMING_AFTER_REVERSECORRECT); if (m_processMsg != null) return false; return true; } /** * Unlock Document. *
* @return true if success */ @Override public boolean unlockIt() { log.info(toString()); setProcessing(false); return true; } // unlockIt @Override public boolean voidIt() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\model\MCFlatrateTransition.java
1