instruction
string
input
string
output
string
source_file
string
priority
int64
请在Spring Boot框架中完成以下Java代码
public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } public String getImageUrl() { return imageUrl; } public void setImageUrl(String imageUrl) { this.imageUrl = imageUrl; } public boolean isActivated() { return activated; } public void setActivated(boolean activated) { this.activated = activated; } public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey; } public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Instant getCreatedDate() { return createdDate; } public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() { return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy;
} public Instant getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Instant lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } public Set<String> getAuthorities() { return authorities; } public void setAuthorities(Set<String> authorities) { this.authorities = authorities; } @Override public String toString() { return "UserDTO{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated=" + activated + ", langKey='" + langKey + '\'' + ", createdBy=" + createdBy + ", createdDate=" + createdDate + ", lastModifiedBy='" + lastModifiedBy + '\'' + ", lastModifiedDate=" + lastModifiedDate + ", authorities=" + authorities + "}"; } }
repos\tutorials-master\jhipster-6\bookstore-monolith\src\main\java\com\baeldung\jhipster6\service\dto\UserDTO.java
2
请完成以下Java代码
public IMutableHUContext createMutableHUContext( @NonNull final Properties ctx, @NonNull final ClientAndOrgId clientAndOrgId) { final Properties ctxEffective = Env.copyCtx(ctx); Env.setClientId(ctxEffective, clientAndOrgId.getClientId()); Env.setOrgId(ctxEffective, clientAndOrgId.getOrgId()); return new MutableHUContext(ctxEffective, ITrx.TRXNAME_None); } // TODO: probably will have to add ClientAndOrgId here as well. I don't have time for this now @Override public IMutableHUContext createMutableHUContext(final Properties ctx, @NonNull final String trxName) { final PlainContextAware contextProvider = PlainContextAware.newWithTrxName(ctx, trxName); return new MutableHUContext(contextProvider); } @Override public IMutableHUContext createMutableHUContext(final IContextAware contextProvider) { return new MutableHUContext(contextProvider); } @Override public final IHUContext deriveWithTrxName(final IHUContext huContext, final String trxNameNew) { // FIXME: handle the case of SaveOnCommit Storage and Attributes when changing transaction name // // Check: if transaction name was not changed, do nothing, return the old context final String contextTrxName = huContext.getTrxName();// // TODO tbp: here the context has wrong org. WHYYYYY final ITrxManager trxManager = Services.get(ITrxManager.class); if (trxManager.isSameTrxName(contextTrxName, trxNameNew)) { return huContext;
} final IMutableHUContext huContextNew = huContext.copyAsMutable(); huContextNew.setTrxName(trxNameNew); configureProcessingContext(huContextNew); return huContextNew; } @Override public String toString() { return "HUContextFactory []"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUContextFactory.java
1
请完成以下Java代码
public PartitionedQueueResponseTemplate<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>> createEdqsResponseTemplate(TbQueueHandler<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>> handler) { var responseProducer = TbKafkaProducerTemplate.<TbProtoQueueMsg<FromEdqsMsg>>builder() .settings(kafkaSettings) .clientId("edqs-response-producer-" + serviceInfoProvider.getServiceId()) .defaultTopic(topicService.buildTopicName(edqsConfig.getResponsesTopic())) .admin(edqsRequestsAdmin) .build(); return PartitionedQueueResponseTemplate.<TbProtoQueueMsg<ToEdqsMsg>, TbProtoQueueMsg<FromEdqsMsg>>builder() .key("edqs") .handler(handler) .requestsTopic(topicService.buildTopicName(edqsConfig.getRequestsTopic())) .consumerCreator(tpi -> createEdqsMsgConsumer(edqsConfig.getRequestsTopic(), "edqs-requests-consumer-" + serviceInfoProvider.getServiceId() + "-" + tpi.getPartition().orElse(999), "edqs-requests-consumer-group", false, edqsRequestsAdmin)) .responseProducer(responseProducer)
.pollInterval(edqsConfig.getPollInterval()) .requestTimeout(edqsConfig.getMaxRequestTimeout()) .maxPendingRequests(edqsConfig.getMaxPendingRequests()) .consumerExecutor(edqsExecutors.getConsumersExecutor()) .callbackExecutor(edqsExecutors.getRequestExecutor()) .consumerTaskExecutor(edqsExecutors.getConsumerTaskExecutor()) .stats(statsFactory.createMessagesStats(StatsType.EDQS.getName())) .build(); } @Override public TbKafkaAdmin getEdqsQueueAdmin() { return edqsEventsAdmin; } }
repos\thingsboard-master\common\queue\src\main\java\org\thingsboard\server\queue\edqs\KafkaEdqsQueueFactory.java
1
请完成以下Java代码
default <T extends RepoIdAware> T getSingleSelectedRecordId(final Class<T> type) { return RepoIdAwares.ofRepoId(getSingleSelectedRecordId(), type); } /** * Gets how many rows were selected. * In case the size is not determined, an exception is thrown. * <p> * Instead of calling this method, always consider using {@link #isNoSelection()}, {@link #isSingleSelection()}, {@link #isMoreThanOneSelected()} if applicable. */ SelectionSize getSelectionSize(); default boolean isNoSelection() { return getSelectionSize().isNoSelection(); } default boolean isSingleSelection() { return getSelectionSize().isSingleSelection(); } default boolean isMoreThanOneSelected() { return getSelectionSize().isMoreThanOneSelected(); } default boolean isMoreThanAllowedSelected(final int maxAllowedSelectionSize) { return getSelectionSize().getSize() > maxAllowedSelectionSize; } /** * @return selected included rows of current single selected document */ default Set<TableRecordReference> getSelectedIncludedRecords() { return ImmutableSet.of(); } default boolean isSingleIncludedRecordSelected() { return getSelectedIncludedRecords().size() == 1; }
<T> IQueryFilter<T> getQueryFilter(@NonNull Class<T> recordClass); default ProcessPreconditionsResolution acceptIfSingleSelection() { if (isNoSelection()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } else if (isMoreThanOneSelected()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } else { return ProcessPreconditionsResolution.accept(); } } default OptionalBoolean isExistingDocument() {return OptionalBoolean.UNKNOWN;} default OptionalBoolean isProcessedDocument() { return OptionalBoolean.UNKNOWN; }; }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\IProcessPreconditionsContext.java
1
请完成以下Java代码
public class PaymentResponse { /** * подпись to Sign */ private String sign; /** * код провайдера */ private String serviceCode; /** * токен пользователя */ private String userToken; /** * сумма платежа в копейках (сумма которая идет на счет пользователю) */ private Integer amount; /** * комиссия платежа в копейках (если нет комиссии - передается 0) */ private String comission; /** * идентификатор карты (для рекуррентного платежа), см. пункт Получение списка карт */ private String cardToken; /** * тип клиента */ private String clientType; /** * Токен при оплате через Google Pay. Более подробно в разделе Google Pay */ private String gPayToken; /** * Номер телефона пользователя(для СМС платежа), с которого будет произведена оплата */ private String userPhone; /** * номер телефона с кодом, но без + (например, 79999999999) */ private String login; /** * e-mail для отправки фискального чека */ private String email; /** * Имя пользователя */ private String name; /** * Фамилия пользователя */ private String surName; /** * Отчество пользователя */
private String middleName; /** * Описание Параметра */ private String fiscalType; /** * способ оплаты */ private String payType; /** * Время истечения срока жизни заказа в секундах. Подробнее */ private String orderBestBefore; /** * массив реквизитов */ private List<CKassaRequestProperties> properties; private String regPayNum; /** * идентификатор организации */ private String shopToken; /** * секретный ключ магазина */ private String shopSecKey; }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\payload\payment\PaymentResponse.java
1
请完成以下Java代码
public String getId() { return id; } @Override public void execute(final ICalloutExecutor executor, final ICalloutField field) { final String columnName = field.getColumnName(); final CalloutMethodPointcutKey pointcutKey = CalloutMethodPointcutKey.of(columnName); final List<CalloutMethodPointcut> pointcutsForKey = mapPointcuts.get(pointcutKey); if (pointcutsForKey.isEmpty()) { return; } for (final ICalloutMethodPointcut pointcut : pointcutsForKey) { executePointcut(pointcut, executor, field); } } private void executePointcut(@NonNull final ICalloutMethodPointcut pointcut, @NonNull final ICalloutExecutor executor, @NonNull final ICalloutField field) { // Skip executing this callout if we were asked to skip when record copying mode is active if (pointcut.isSkipIfCopying() && field.isRecordCopyingMode()) { logger.info("Skip invoking callout because we are in copying mode: {}", pointcut.getMethod()); return; } if (pointcut.isSkipIfIndirectlyCalled() && executor.getActiveCalloutInstancesCount() > 1) { logger.info("Skip invoking callout because it is called via another callout: {}", pointcut.getMethod()); return; } try { final Method method = pointcut.getMethod(); final Object model = field.getModel(pointcut.getModelClass());
// make sure the method can be executed if (!method.isAccessible()) { method.setAccessible(true); } if (pointcut.isParamCalloutFieldRequired()) { method.invoke(annotatedObject, model, field); } else { method.invoke(annotatedObject, model); } } catch (final CalloutExecutionException e) { throw e; } catch (final Exception e) { throw CalloutExecutionException.wrapIfNeeded(e) .setCalloutExecutor(executor) .setCalloutInstance(this) .setField(field); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\callout\annotations\api\impl\AnnotatedCalloutInstance.java
1
请完成以下Java代码
public class JsonPointerCrud { private JsonStructure jsonStructure = null; public JsonPointerCrud(String fileName) throws IOException { try (JsonReader reader = Json.createReader(Files.newBufferedReader(Paths.get(fileName)))) { jsonStructure = reader.read(); } catch (FileNotFoundException e) { System.out.println("Error to open json file: " + e.getMessage()); } } public JsonPointerCrud(InputStream stream) { JsonReader reader = Json.createReader(stream); jsonStructure = reader.read(); reader.close(); } public JsonStructure insert(String key, String value) { JsonPointer jsonPointer = Json.createPointer("/" + key); JsonString jsonValue = Json.createValue(value); jsonStructure = jsonPointer.add(jsonStructure, jsonValue); return jsonStructure; } public JsonStructure update(String key, String newValue) { JsonPointer jsonPointer = Json.createPointer("/" + key); JsonString jsonNewValue = Json.createValue(newValue); jsonStructure = jsonPointer.replace(jsonStructure, jsonNewValue); return jsonStructure; } public JsonStructure delete(String key) { JsonPointer jsonPointer = Json.createPointer("/" + key); jsonPointer.getValue(jsonStructure); jsonStructure = jsonPointer.remove(jsonStructure); return jsonStructure;
} public String fetchValueFromKey(String key) { JsonPointer jsonPointer = Json.createPointer("/" + key); JsonString jsonString = (JsonString) jsonPointer.getValue(jsonStructure); return jsonString.getString(); } public String fetchListValues(String key) { JsonPointer jsonPointer = Json.createPointer("/" + key); JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure); return jsonObject.toString(); } public String fetchFullJSON() { JsonPointer jsonPointer = Json.createPointer(""); JsonObject jsonObject = (JsonObject) jsonPointer.getValue(jsonStructure); return jsonObject.toString(); } public boolean check(String key) { JsonPointer jsonPointer = Json.createPointer("/" + key); boolean found = jsonPointer.containsValue(jsonStructure); return found; } }
repos\tutorials-master\json-modules\json\src\main\java\com\baeldung\jsonpointer\JsonPointerCrud.java
1
请完成以下Java代码
public String getMsgId() { return msgId; } /** * Sets the value of the msgId property. * * @param value * allowed object is * {@link String } * */ public void setMsgId(String value) { this.msgId = value; } /** * Gets the value of the pmtInfId property. * * @return * possible object is * {@link String } * */ public String getPmtInfId() { return pmtInfId; } /** * Sets the value of the pmtInfId property. * * @param value * allowed object is * {@link String } * */ public void setPmtInfId(String value) { this.pmtInfId = value; } /** * Gets the value of the nbOfTxs property. * * @return * possible object is * {@link String } * */ public String getNbOfTxs() { return nbOfTxs; } /** * Sets the value of the nbOfTxs property. * * @param value * allowed object is * {@link String } * */ public void setNbOfTxs(String value) { this.nbOfTxs = value; } /** * Gets the value of the ttlAmt property. * * @return * possible object is * {@link ActiveOrHistoricCurrencyAndAmount } *
*/ public ActiveOrHistoricCurrencyAndAmount getTtlAmt() { return ttlAmt; } /** * Sets the value of the ttlAmt property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setTtlAmt(ActiveOrHistoricCurrencyAndAmount value) { this.ttlAmt = value; } /** * Gets the value of the cdtDbtInd property. * * @return * possible object is * {@link CreditDebitCode } * */ public CreditDebitCode getCdtDbtInd() { return cdtDbtInd; } /** * Sets the value of the cdtDbtInd property. * * @param value * allowed object is * {@link CreditDebitCode } * */ public void setCdtDbtInd(CreditDebitCode value) { this.cdtDbtInd = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\BatchInformation2.java
1
请完成以下Java代码
public String getItemRef() { return itemRef; } public void setItemRef(String itemRef) { this.itemRef = itemRef; } public Message clone() { Message clone = new Message(); clone.setValues(this); return clone; } public void setValues(Message otherElement) { super.setValues(otherElement); setName(otherElement.getName()); setItemRef(otherElement.getItemRef()); } /** * Creates builder to build {@link Message}. * @return created builder */ public static Builder builder() { return new Builder(); } /** * Creates a builder to build {@link Message} and initialize it with the given object. * @param message to initialize the builder with * @return created builder */ public static Builder builderFrom(Message message) { return new Builder(message); } /** * Builder to build {@link Message}. */ public static final class Builder { private String id; private int xmlRowNumber; private int xmlColumnNumber; private Map<String, List<ExtensionElement>> extensionElements = emptyMap(); private Map<String, List<ExtensionAttribute>> attributes = emptyMap(); private String name; private String itemRef; private Builder() {} private Builder(Message message) {
this.id = message.id; this.xmlRowNumber = message.xmlRowNumber; this.xmlColumnNumber = message.xmlColumnNumber; this.extensionElements = message.extensionElements; this.attributes = message.attributes; this.name = message.name; this.itemRef = message.itemRef; } public Builder id(String id) { this.id = id; return this; } public Builder xmlRowNumber(int xmlRowNumber) { this.xmlRowNumber = xmlRowNumber; return this; } public Builder xmlColumnNumber(int xmlColumnNumber) { this.xmlColumnNumber = xmlColumnNumber; return this; } public Builder extensionElements(Map<String, List<ExtensionElement>> extensionElements) { this.extensionElements = extensionElements; return this; } public Builder attributes(Map<String, List<ExtensionAttribute>> attributes) { this.attributes = attributes; return this; } public Builder name(String name) { this.name = name; return this; } public Builder itemRef(String itemRef) { this.itemRef = itemRef; return this; } public Message build() { return new Message(this); } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\Message.java
1
请完成以下Java代码
public void setMSV3_Menge (int MSV3_Menge) { set_Value (COLUMNNAME_MSV3_Menge, Integer.valueOf(MSV3_Menge)); } /** Get MSV3_Menge. @return MSV3_Menge */ @Override public int getMSV3_Menge () { Integer ii = (Integer)get_Value(COLUMNNAME_MSV3_Menge); if (ii == null) return 0; return ii.intValue(); } /** Set Tourabweichung. @param MSV3_Tourabweichung Tourabweichung */ @Override public void setMSV3_Tourabweichung (boolean MSV3_Tourabweichung) { set_Value (COLUMNNAME_MSV3_Tourabweichung, Boolean.valueOf(MSV3_Tourabweichung)); } /** Get Tourabweichung. @return Tourabweichung */ @Override public boolean isMSV3_Tourabweichung () { Object oo = get_Value(COLUMNNAME_MSV3_Tourabweichung); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** * MSV3_Typ AD_Reference_ID=540823
* Reference name: MSV3_BestellungRueckmeldungTyp */ public static final int MSV3_TYP_AD_Reference_ID=540823; /** Normal = Normal */ public static final String MSV3_TYP_Normal = "Normal"; /** Verbund = Verbund */ public static final String MSV3_TYP_Verbund = "Verbund"; /** Nachlieferung = Nachlieferung */ public static final String MSV3_TYP_Nachlieferung = "Nachlieferung"; /** Dispo = Dispo */ public static final String MSV3_TYP_Dispo = "Dispo"; /** KeineLieferungAberNormalMoeglich = KeineLieferungAberNormalMoeglich */ public static final String MSV3_TYP_KeineLieferungAberNormalMoeglich = "KeineLieferungAberNormalMoeglich"; /** KeineLieferungAberVerbundMoeglich = KeineLieferungAberVerbundMoeglich */ public static final String MSV3_TYP_KeineLieferungAberVerbundMoeglich = "KeineLieferungAberVerbundMoeglich"; /** KeineLieferungAberNachlieferungMoeglich = KeineLieferungAberNachlieferungMoeglich */ public static final String MSV3_TYP_KeineLieferungAberNachlieferungMoeglich = "KeineLieferungAberNachlieferungMoeglich"; /** KeineLieferungAberDispoMoeglich = KeineLieferungAberDispoMoeglich */ public static final String MSV3_TYP_KeineLieferungAberDispoMoeglich = "KeineLieferungAberDispoMoeglich"; /** NichtLieferbar = NichtLieferbar */ public static final String MSV3_TYP_NichtLieferbar = "NichtLieferbar"; /** Set Typ. @param MSV3_Typ Typ */ @Override public void setMSV3_Typ (java.lang.String MSV3_Typ) { set_Value (COLUMNNAME_MSV3_Typ, MSV3_Typ); } /** Get Typ. @return Typ */ @Override public java.lang.String getMSV3_Typ () { return (java.lang.String)get_Value(COLUMNNAME_MSV3_Typ); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.vendor.gateway.msv3\src\main\java-gen\de\metas\vertical\pharma\vendor\gateway\msv3\model\X_MSV3_BestellungAnteil.java
1
请在Spring Boot框架中完成以下Java代码
public byte[] serialize(Object graph) throws SerializationException { if (graph == null) { return new byte[0]; } ByteArrayOutputStream bos = null; GZIPOutputStream gzip = null; try { // serialize byte[] bytes = jacksonRedisSerializer.serialize(graph); log.info("bytes size{}",bytes.length); bos = new ByteArrayOutputStream(); gzip = new GZIPOutputStream(bos); // compress gzip.write(bytes); gzip.finish(); byte[] result = bos.toByteArray(); log.info("result size{}",result.length); //return result; return new BASE64Encoder().encode(result).getBytes(); } catch (Exception e) { throw new SerializationException("Gzip Serialization Error", e); } finally { IOUtils.closeQuietly(bos); IOUtils.closeQuietly(gzip); } } @Override public Object deserialize(byte[] bytes) throws SerializationException { if (bytes == null || bytes.length == 0) { return null; } ByteArrayOutputStream bos = null; ByteArrayInputStream bis = null; GZIPInputStream gzip = null; try { bos = new ByteArrayOutputStream(); byte[] compressed = new sun.misc.BASE64Decoder().decodeBuffer( new String(bytes));; bis = new ByteArrayInputStream(compressed); gzip = new GZIPInputStream(bis); byte[] buff = new byte[BUFFER_SIZE]; int n; // uncompress
while ((n = gzip.read(buff, 0, BUFFER_SIZE)) > 0) { bos.write(buff, 0, n); } //deserialize Object result = jacksonRedisSerializer.deserialize(bos.toByteArray()); return result; } catch (Exception e) { throw new SerializationException("Gzip deserizelie error", e); } finally { IOUtils.closeQuietly(bos); IOUtils.closeQuietly(bis); IOUtils.closeQuietly(gzip); } } private static JacksonRedisSerializer<User> getValueSerializer() { JacksonRedisSerializer<User> jackson2JsonRedisSerializer = new JacksonRedisSerializer<>(User.class); ObjectMapper mapper=new ObjectMapper(); jackson2JsonRedisSerializer.setObjectMapper(mapper); return jackson2JsonRedisSerializer; } }
repos\springboot-demo-master\gzip\src\main\java\com\et\gzip\config\CompressRedis.java
2
请完成以下Java代码
public static List<Integer> findByBucketSort(Integer[] arr, int n) { List<Integer> result = new ArrayList<>(); Map<Integer, Integer> freqMap = new HashMap<>(); List<Integer>[] bucket = new List[arr.length + 1]; // Loop through the input array and update the frequency count of each element in the HashMap for (int num : arr) { freqMap.put(num, freqMap.getOrDefault(num, 0) + 1); } // Loop through the HashMap and add each element to its corresponding bucket based on its frequency count for (int num : freqMap.keySet()) { int freq = freqMap.get(num); if (bucket[freq] == null) { bucket[freq] = new ArrayList<>(); } bucket[freq].add(num);
} // Loop through the bucket array in reverse order and add the elements to the result list // until we have found the n most frequent elements for (int i = bucket.length - 1; i >= 0 && result.size() < n; i--) { if (bucket[i] != null) { result.addAll(bucket[i]); } } // Return a sublist of the result list containing only the first n elements return result.subList(0, n); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-7\src\main\java\com\baeldung\algorithms\frequentelements\MostFrequentElementsFinder.java
1
请完成以下Java代码
public final void assertScriptEngineExists(final I_AD_Rule rule) { try { final ScriptExecutor executor = createExecutor(rule); Check.assumeNotNull(executor, "executor is not null"); // shall not happen } catch (final Throwable e) { throw new AdempiereException("@WrongScriptValue@", e); } } public static final String extractEngineNameFromRuleValue(final String ruleValue) { if (ruleValue == null) { return null; } final int colonPosition = ruleValue.indexOf(":"); if (colonPosition < 0) { return null; } return ruleValue.substring(0, colonPosition); } public static final Optional<String> extractRuleValueFromClassname(final String classname) { if (classname == null || classname.isEmpty()) { return Optional.empty(); }
if (!classname.toLowerCase().startsWith(SCRIPT_PREFIX)) { return Optional.empty(); } final String ruleValue = classname.substring(SCRIPT_PREFIX.length()).trim(); return Optional.of(ruleValue); } private final ScriptEngine createScriptEngine_JSR223(final String engineName) { Check.assumeNotEmpty(engineName, "engineName is not empty"); final ScriptEngineManager factory = getScriptEngineManager(); final ScriptEngine engine = factory.getEngineByName(engineName); if (engine == null) { throw new AdempiereException("Script engine was not found for engine name: '" + engineName + "'"); } return engine; } private final ScriptEngineManager getScriptEngineManager() { return scriptEngineManager.get(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\script\ScriptEngineFactory.java
1
请完成以下Java代码
public class UserInitializer { private final UserRepository repository; public void init() throws Exception { List<User> users = readUsers(new ClassPathResource("randomuser.me.csv")); repository.deleteAll(); repository.saveAll(users); } private static List<User> readUsers(Resource resource) throws Exception { Scanner scanner = new Scanner(resource.getInputStream()); String line = scanner.nextLine(); scanner.close(); DelimitedLineTokenizer tokenizer = new DelimitedLineTokenizer(); tokenizer.setNames(line.split(",")); tokenizer.setStrict(false); DefaultLineMapper<User> lineMapper = new DefaultLineMapper<User>(); lineMapper.setFieldSetMapper(fields -> { User user = new User(); user.setEmail(fields.readString("email")); user.setFirstname(capitalize(fields.readString("first"))); user.setLastname(capitalize(fields.readString("last"))); user.setNationality(fields.readString("nationality")); String city = Arrays.stream(fields.readString("city").split(" "))// .map(StringUtils::capitalize)// .collect(Collectors.joining(" ")); String street = Arrays.stream(fields.readString("street").split(" "))// .map(StringUtils::capitalize)// .collect(Collectors.joining(" ")); try { user.setAddress(new Address(city, street, fields.readString("zip"))); } catch (IllegalArgumentException e) { user.setAddress(new Address(city, street, fields.readString("postcode"))); }
user.setPicture( new Picture(fields.readString("large"), fields.readString("medium"), fields.readString("thumbnail"))); user.setUsername(fields.readString("username")); user.setPassword(fields.readString("password")); return user; }); lineMapper.setLineTokenizer(tokenizer); FlatFileItemReader<User> reader = new FlatFileItemReader<User>(lineMapper); reader.setResource(resource); reader.setRecordSeparatorPolicy(new DefaultRecordSeparatorPolicy()); reader.setLinesToSkip(1); reader.open(new ExecutionContext()); List<User> users = new ArrayList<>(); User user = null; do { user = reader.read(); if (user != null) { users.add(user); } } while (user != null); return users; } }
repos\spring-data-examples-main\web\querydsl\src\main\java\example\users\UserInitializer.java
1
请完成以下Java代码
public List<String> getSourceColumnNames() { return SOURCE_COLUMN_NAMES; } /** * Obtains the given olCand's pricing result and resets the olCand's ASI with the list of {@link IPricingResult#getPricingAttributes()}. * <p> * About corner cases: * <ul> * <li>if there is no dynamic-attribute pricing result (of if the price was not calculated!), it does nothing. Rationale: this implementation's job is to sync/reset the result of a successful * price calculation with the olCand's ASI. If there is no such pricing result, we assume that this method's service is not wanted. * <li>if the pricing result has no pricing attributes, then the olCand gets an "empty" ASI with no attribute instances * <li>if the olCand has already an ASI, then that ASI is discarded and ignored. * <li>We do <b>not</b> care if the attribute set of the olCand's product matches the attribute values of the pricing result. Rationale: we assume that the pricing result was created for this * olCand and its quantity, PIIP, date etc. and in particular also for its product. * </ul> * * @see DefaultOLCandValidator#getPreviouslyCalculatedPricingResultOrNull(I_C_OLCand) */ @Override public void modelChanged(final Object model) {
final I_C_OLCand olCand = InterfaceWrapperHelper.create(model, I_C_OLCand.class); final IPricingResult pricingResult = DefaultOLCandValidator.getPreviouslyCalculatedPricingResultOrNull(olCand); if (pricingResult == null || !pricingResult.isCalculated()) { return; // nothing to do } final IAttributeSetInstanceAware asiAware = attributeSetInstanceAwareFactoryService.createOrNull(olCand); Check.assumeNotNull(asiAware, "We have an asiAware for C_OLCand {}, because we implemented and registered the factory {}", olCand, OLCandASIAwareFactory.class.getName()); asiAware.setM_AttributeSetInstance(null); // reset, because we want getCreateASI to give us a new ASI final List<IPricingAttribute> pricingAttributes = pricingResult.getPricingAttributes(); if (!pricingAttributes.isEmpty()) { attributeSetInstanceBL.getCreateASI(asiAware); attributePricingBL.addToASI(asiAware, pricingAttributes); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java\de\metas\ordercandidate\spi\impl\OLCandPricingASIListener.java
1
请完成以下Java代码
public class StreamSumCalculator { public static Integer getSumUsingCustomizedAccumulator(List<Integer> integers) { return integers.stream() .reduce(0, ArithmeticUtils::add); } public static Integer getSumUsingJavaAccumulator(List<Integer> integers) { return integers.stream() .reduce(0, Integer::sum); } public static Integer getSumUsingReduce(List<Integer> integers) { return integers.stream() .reduce(0, (a, b) -> a + b); } public static Integer getSumUsingCollect(List<Integer> integers) { return integers.stream() .collect(Collectors.summingInt(Integer::intValue)); } public static Integer getSumUsingSum(List<Integer> integers) {
return integers.stream() .mapToInt(Integer::intValue) .sum(); } public static Integer getSumOfMapValues(Map<Object, Integer> map) { return map.values() .stream() .mapToInt(Integer::valueOf) .sum(); } public static Integer getSumIntegersFromString(String str) { Integer sum = Arrays.stream(str.split(" ")) .filter((s) -> s.matches("\\d+")) .mapToInt(Integer::valueOf) .sum(); return sum; } }
repos\tutorials-master\core-java-modules\core-java-streams\src\main\java\com\baeldung\stream\sum\StreamSumCalculator.java
1
请在Spring Boot框架中完成以下Java代码
public class IndexController { @Resource private XxlJobService xxlJobService; @Resource private LoginService loginService; @RequestMapping("/") public String index(Model model) { Map<String, Object> dashboardMap = xxlJobService.dashboardInfo(); model.addAllAttributes(dashboardMap); return "index"; } @RequestMapping("/chartInfo") @ResponseBody public ReturnT<Map<String, Object>> chartInfo(Date startDate, Date endDate) { ReturnT<Map<String, Object>> chartInfo = xxlJobService.chartInfo(startDate, endDate); return chartInfo; } @RequestMapping("/toLogin") @PermissionLimit(limit=false) public ModelAndView toLogin(HttpServletRequest request, HttpServletResponse response,ModelAndView modelAndView) { if (loginService.ifLogin(request, response) != null) { modelAndView.setView(new RedirectView("/",true,false)); return modelAndView; } return new ModelAndView("login"); } @RequestMapping(value="login", method=RequestMethod.POST) @ResponseBody @PermissionLimit(limit=false) public ReturnT<String> loginDo(HttpServletRequest request, HttpServletResponse response, String userName, String password, String ifRemember){ boolean ifRem = (ifRemember!=null && ifRemember.trim().length()>0 && "on".equals(ifRemember))?true:false; return loginService.login(request, response, userName, password, ifRem);
} @RequestMapping(value="logout", method=RequestMethod.POST) @ResponseBody @PermissionLimit(limit=false) public ReturnT<String> logout(HttpServletRequest request, HttpServletResponse response){ return loginService.logout(request, response); } @RequestMapping("/help") public String help() { /*if (!PermissionInterceptor.ifLogin(request)) { return "redirect:/toLogin"; }*/ return "help"; } @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); dateFormat.setLenient(false); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\controller\IndexController.java
2
请在Spring Boot框架中完成以下Java代码
public void setProcessesXmls(List<ProcessesXml> processesXmls) { this.processesXmls = processesXmls; } public List<ProcessesXml> getProcessesXmls() { return processesXmls; } public void setDeploymentMap(Map<String, DeployedProcessArchive> processArchiveDeploymentMap) { this.deploymentMap = processArchiveDeploymentMap; } public Map<String, DeployedProcessArchive> getProcessArchiveDeploymentMap() { return deploymentMap; } public List<String> getDeploymentIds() { List<String> deploymentIds = new ArrayList<String>(); for (DeployedProcessArchive registration : deploymentMap.values()) {
deploymentIds.addAll(registration.getAllDeploymentIds()); } return deploymentIds; } public List<String> getDeploymentNames() { return new ArrayList<String>(deploymentMap.keySet()); } public ProcessApplicationInfoImpl getProcessApplicationInfo() { return processApplicationInfo; } public ProcessApplicationReference getProcessApplicationReference() { return processApplicationReference; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\container\impl\jmx\services\JmxManagedProcessApplication.java
2
请在Spring Boot框架中完成以下Java代码
public List<AuthorDto> fetchAuthorsWithBooksQueryBuilderMechanism() { return bookstoreService.fetchAuthorsWithBooksQueryBuilderMechanism(); } @GetMapping("/authorsAndbooks/2") public List<AuthorDto> fetchAuthorsWithBooksViaQuery() { return bookstoreService.fetchAuthorsWithBooksViaQuery(); } @GetMapping("/authorsAndbooks/3") public Set<AuthorDto> fetchAuthorsWithBooksViaJoinFetch() { return bookstoreService.fetchAuthorsWithBooksViaJoinFetch(); } @GetMapping("/authorsAndbooks/4") public List<SimpleAuthorDto> fetchAuthorsWithBooksViaQuerySimpleDto() { return bookstoreService.fetchAuthorsWithBooksViaQuerySimpleDto();
} @GetMapping("/authorsAndbooks/5") public List<Object[]> fetchAuthorsWithBooksViaArrayOfObjects() { return bookstoreService.fetchAuthorsWithBooksViaArrayOfObjects(); } @GetMapping("/authorsAndbooks/6") public List<com.bookstore.transform.dto.AuthorDto> fetchAuthorsWithBooksViaArrayOfObjectsAndTransformToDto() { return bookstoreService.fetchAuthorsWithBooksViaArrayOfObjectsAndTransformToDto(); } @GetMapping("/authorsAndbooks/7") public List<com.bookstore.jdbcTemplate.dto.AuthorDto> fetchAuthorsWithBooksViaJdbcTemplateToDto() { return bookstoreService.fetchAuthorsWithBooksViaJdbcTemplateToDto(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootProjectionAndCollections\src\main\java\com\bookstore\controller\BookstoreController.java
2
请完成以下Java代码
public class DeviceDescriptor extends EdgeNodeDescriptor { private final String deviceId; private final String descriptorString; public DeviceDescriptor(String groupId, String edgeNodeId, String deviceId) { super(groupId, edgeNodeId); this.deviceId = deviceId; this.descriptorString = groupId + "/" + edgeNodeId + "/" + deviceId; } public DeviceDescriptor(String descriptorString) { super(descriptorString.substring(0, descriptorString.lastIndexOf("/"))); this.deviceId = descriptorString.substring(descriptorString.lastIndexOf("/") + 1); this.descriptorString = descriptorString; } public DeviceDescriptor(EdgeNodeDescriptor edgeNodeDescriptor, String deviceId) { super(edgeNodeDescriptor.getGroupId(), edgeNodeDescriptor.getEdgeNodeId()); this.deviceId = deviceId; this.descriptorString = edgeNodeDescriptor.getDescriptorString() + "/" + deviceId; } public String getDeviceId() { return deviceId; } /** * Returns a {@link String} representing the Device's Descriptor of the form: * "<groupName>/<edgeNodeName>/<deviceId>".
* * @return a {@link String} representing the Device's Descriptor. */ @Override public String getDescriptorString() { return descriptorString; } public String getEdgeNodeDescriptorString() { return super.getDescriptorString(); } @Override public int hashCode() { return this.getDescriptorString().hashCode(); } @Override public boolean equals(Object object) { if (object instanceof DeviceDescriptor) { return this.getDescriptorString().equals(((DeviceDescriptor) object).getDescriptorString()); } return this.getDescriptorString().equals(object); } @Override public String toString() { return getDescriptorString(); } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\util\sparkplug\DeviceDescriptor.java
1
请在Spring Boot框架中完成以下Java代码
private void computeNextImportDate(@NonNull final Exchange exchange, @NonNull final Order orderCandidate) { final Instant nextImportSinceDateCandidate = AlbertaUtil.asInstant(orderCandidate.getCreationDate()); if (nextImportSinceDateCandidate == null) { return; } final NextImportSinceTimestamp currentNextImportSinceDate = ProcessorHelper.getPropertyOrThrowError(exchange, GetOrdersRouteConstants.ROUTE_PROPERTY_UPDATED_AFTER, NextImportSinceTimestamp.class); if (nextImportSinceDateCandidate.isAfter(currentNextImportSinceDate.getDate())) { currentNextImportSinceDate.setDate(nextImportSinceDateCandidate); } } @NonNull private static Optional<JsonRequestBPartnerLocationAndContact> getBillToBPartner(@NonNull final JsonResponseComposite jsonResponseComposite) { final Optional<JsonResponseLocation> billingAddressLocation = jsonResponseComposite.getLocations()
.stream() .filter(JsonResponseLocation::isBillTo) .findFirst(); if (billingAddressLocation.isEmpty()) { return Optional.empty(); } return Optional.of(JsonRequestBPartnerLocationAndContact.builder() .bPartnerIdentifier(JsonMetasfreshId.toValueStr(jsonResponseComposite.getBpartner().getMetasfreshId())) .bPartnerLocationIdentifier(JsonMetasfreshId.toValueStr(billingAddressLocation.get().getMetasfreshId())) .build()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\de-metas-camel-alberta-camelroutes\src\main\java\de\metas\camel\externalsystems\alberta\ordercandidate\processor\JsonOLCandCreateRequestProcessor.java
2
请在Spring Boot框架中完成以下Java代码
public void setTotalAmt(BigDecimal value) { this.totalAmt = value; } /** * Gets the value of the referenceNo property. * * @return * possible object is * {@link String } * */ public String getReferenceNo() { return referenceNo; } /** * Sets the value of the referenceNo property. * * @param value * allowed object is * {@link String } * */ public void setReferenceNo(String value) { this.referenceNo = value; } /** * Gets the value of the surchargeAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getSurchargeAmt() { return surchargeAmt; } /** * Sets the value of the surchargeAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setSurchargeAmt(BigDecimal value) { this.surchargeAmt = value; } /** * Gets the value of the taxBaseAmtWithSurchargeAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getTaxBaseAmtWithSurchargeAmt() { return taxBaseAmtWithSurchargeAmt;
} /** * Sets the value of the taxBaseAmtWithSurchargeAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setTaxBaseAmtWithSurchargeAmt(BigDecimal value) { this.taxBaseAmtWithSurchargeAmt = value; } /** * Gets the value of the taxAmtWithSurchargeAmt property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getTaxAmtWithSurchargeAmt() { return taxAmtWithSurchargeAmt; } /** * Sets the value of the taxAmtWithSurchargeAmt property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setTaxAmtWithSurchargeAmt(BigDecimal value) { this.taxAmtWithSurchargeAmt = value; } /** * Gets the value of the isMainVAT property. * * @return * possible object is * {@link String } * */ public String getIsMainVAT() { return isMainVAT; } /** * Sets the value of the isMainVAT property. * * @param value * allowed object is * {@link String } * */ public void setIsMainVAT(String value) { this.isMainVAT = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctop901991VType.java
2
请完成以下Java代码
public POSProductsSearchResult execute() { return CoalesceUtil.coalesceSuppliersNotNull( this::searchByGS1, this::searchByEAN13, this::searchByUPCorValue, this::searchByValueName, this::allProducts ); } @Nullable private POSProductsSearchResult searchByGS1() { if (queryString == null) { return null; } final GS1Elements elements = GS1Parser.parseElementsOrNull(queryString); if (elements == null) { return null; } final GTIN gtin = elements.getGTIN().orElse(null); if (gtin == null) { return null; } final ProductId productId = productBL.getProductIdByGTIN(gtin).orElse(null); final POSProduct product = getPOSProduct(productId); if (product == null) { return null; } return POSProductsSearchResult.ofBarcodeMatchedProduct( product.withCatchWeight(elements.getWeightInKg().orElse(null)) ); } @Nullable private POSProductsSearchResult searchByEAN13() { if (queryString == null) { return null; } final EAN13 ean13 = EAN13HUQRCode.fromString(queryString).map(EAN13HUQRCode::unbox).orElse(null); if (ean13 == null) { return null; } final ProductId productId = productBL.getProductIdByEAN13(ean13).orElse(null); final POSProduct product = getPOSProduct(productId); if (product == null) { return null; } return POSProductsSearchResult.ofBarcodeMatchedProduct( product.withCatchWeight(ean13.getWeightInKg().orElse(null)) ); } @Nullable private POSProductsSearchResult searchByUPCorValue() { if (queryString == null) { return null; } final ProductId productId = productBL.getProductIdByBarcode(queryString, ClientId.METASFRESH).orElse(null); final POSProduct product = getPOSProduct(productId); if (product == null) { return null; }
return POSProductsSearchResult.ofBarcodeMatchedProduct(product); } @Nullable private POSProduct getPOSProduct(@Nullable final ProductId productId) { if (productId == null) { return null; } final List<POSProduct> products = loader.load(evalDate, InSetPredicate.only(productId)); if (products.size() != 1) { return null; } return products.get(0); } @Nullable private POSProductsSearchResult searchByValueName() { if (queryString == null) { return null; } final Set<ProductId> productIds = productBL.getProductIdsMatchingQueryString(queryString, ClientId.METASFRESH, QueryLimit.ONE_HUNDRED); return POSProductsSearchResult.ofList(loader.load(evalDate, InSetPredicate.only(productIds))); } @NonNull private POSProductsSearchResult allProducts() { return POSProductsSearchResult.ofList(loader.load(evalDate, InSetPredicate.any())); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.pos.base\src\main\java\de\metas\pos\POSProductsSearchCommand.java
1
请完成以下Java代码
public java.lang.String getRollbackStatement () { return (java.lang.String)get_Value(COLUMNNAME_RollbackStatement); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set SQLStatement. @param SQLStatement SQLStatement */ @Override public void setSQLStatement (java.lang.String SQLStatement) { set_Value (COLUMNNAME_SQLStatement, SQLStatement); } /** Get SQLStatement. @return SQLStatement */ @Override public java.lang.String getSQLStatement () { return (java.lang.String)get_Value(COLUMNNAME_SQLStatement); } /** * StatusCode AD_Reference_ID=53311 * Reference name: AD_Migration Status */ public static final int STATUSCODE_AD_Reference_ID=53311; /** Applied = A */ public static final String STATUSCODE_Applied = "A"; /** Unapplied = U */ public static final String STATUSCODE_Unapplied = "U"; /** Failed = F */ public static final String STATUSCODE_Failed = "F"; /** Partially applied = P */ public static final String STATUSCODE_PartiallyApplied = "P"; /** Set Status Code. @param StatusCode Status Code */ @Override public void setStatusCode (java.lang.String StatusCode) { set_ValueNoCheck (COLUMNNAME_StatusCode, StatusCode); } /** Get Status Code. @return Status Code */ @Override public java.lang.String getStatusCode () { return (java.lang.String)get_Value(COLUMNNAME_StatusCode); } /** * StepType AD_Reference_ID=53313 * Reference name: Migration step type */
public static final int STEPTYPE_AD_Reference_ID=53313; /** Application Dictionary = AD */ public static final String STEPTYPE_ApplicationDictionary = "AD"; /** SQL Statement = SQL */ public static final String STEPTYPE_SQLStatement = "SQL"; /** Set Step type. @param StepType Migration step type */ @Override public void setStepType (java.lang.String StepType) { set_ValueNoCheck (COLUMNNAME_StepType, StepType); } /** Get Step type. @return Migration step type */ @Override public java.lang.String getStepType () { return (java.lang.String)get_Value(COLUMNNAME_StepType); } /** Set Name der DB-Tabelle. @param TableName Name der DB-Tabelle */ @Override public void setTableName (java.lang.String TableName) { set_Value (COLUMNNAME_TableName, TableName); } /** Get Name der DB-Tabelle. @return Name der DB-Tabelle */ @Override public java.lang.String getTableName () { return (java.lang.String)get_Value(COLUMNNAME_TableName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_MigrationStep.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Category getCategory() { return category; } public void setCategory(Category category) { this.category = category; }
public double getPrice() { return price; } public void setPrice(double price) { this.price = price; } @Override public Product clone() throws CloneNotSupportedException { Product clone = (Product) super.clone(); clone.setId(null); return clone; } }
repos\tutorials-master\persistence-modules\java-jpa-4\src\main\java\com\baeldung\jpa\cloneentity\Product.java
1
请完成以下Java代码
public Date convertFrom(final Object valueObj, final ExpressionContext options) { if (valueObj == null) { return null; } else if (valueObj instanceof Date) { return (Date)valueObj; } else if (TimeUtil.isDateOrTimeObject(valueObj)) { return TimeUtil.asDate(valueObj); } else { return convertFromString(valueObj.toString(), options); } } private Date convertFromString(String valueStr, @NonNull final ExpressionContext options) { if (valueStr == null) { return null; } valueStr = valueStr.trim(); // // Use the given date format try { final DateFormat dateFormat = (DateFormat)options.get(DateStringExpression.PARAM_DateFormat); if (dateFormat != null) { return dateFormat.parse(valueStr); } } catch (final ParseException ex1) { // second try // FIXME: this is not optimum. We shall unify how we store Dates (as String) logger.warn("Using Env.parseTimestamp to convert '{}' to Date", valueStr, ex1); } // // Fallback try { final Timestamp ts = Env.parseTimestamp(valueStr); if (ts == null) { return null; } return new java.util.Date(ts.getTime()); } catch (final Exception ex2) { final IllegalArgumentException exFinal = new IllegalArgumentException("Failed converting '" + valueStr + "' to date", ex2); throw exFinal;
} } } private static final class NullExpression extends NullExpressionTemplate<Date, DateStringExpression> implements DateStringExpression { public NullExpression(final Compiler<Date, DateStringExpression> compiler) { super(compiler); } } private static final class ConstantExpression extends ConstantExpressionTemplate<Date, DateStringExpression> implements DateStringExpression { public ConstantExpression(final ExpressionContext context, final Compiler<Date, DateStringExpression> compiler, final String expressionStr, final Date constantValue) { super(context, compiler, expressionStr, constantValue); } } private static final class SingleParameterExpression extends SingleParameterExpressionTemplate<Date, DateStringExpression> implements DateStringExpression { public SingleParameterExpression(final ExpressionContext context, final Compiler<Date, DateStringExpression> compiler, final String expressionStr, final CtxName parameter) { super(context, compiler, expressionStr, parameter); } @Override protected Object extractParameterValue(final Evaluatee ctx) { return parameter.getValueAsDate(ctx); } } private static final class GeneralExpression extends GeneralExpressionTemplate<Date, DateStringExpression> implements DateStringExpression { public GeneralExpression(final ExpressionContext context, final Compiler<Date, DateStringExpression> compiler, final String expressionStr, final List<Object> expressionChunks) { super(context, compiler, expressionStr, expressionChunks); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\expression\api\impl\DateStringExpressionSupport.java
1
请完成以下Java代码
public int getR_Request_ID() { return get_ValueAsInt(COLUMNNAME_R_Request_ID); } @Override public void setSourceClassName (final @Nullable java.lang.String SourceClassName) { set_Value (COLUMNNAME_SourceClassName, SourceClassName); } @Override public java.lang.String getSourceClassName() { return get_ValueAsString(COLUMNNAME_SourceClassName); } @Override public void setSourceMethodName (final @Nullable java.lang.String SourceMethodName) { set_Value (COLUMNNAME_SourceMethodName, SourceMethodName); } @Override public java.lang.String getSourceMethodName() { return get_ValueAsString(COLUMNNAME_SourceMethodName); } @Override public void setStackTrace (final @Nullable java.lang.String StackTrace) { set_Value (COLUMNNAME_StackTrace, StackTrace); } @Override public java.lang.String getStackTrace() { return get_ValueAsString(COLUMNNAME_StackTrace); } @Override public void setStatisticsInfo (final @Nullable java.lang.String StatisticsInfo) { set_ValueNoCheck (COLUMNNAME_StatisticsInfo, StatisticsInfo); } @Override public java.lang.String getStatisticsInfo() { return get_ValueAsString(COLUMNNAME_StatisticsInfo); } @Override public void setSupportEMail (final @Nullable java.lang.String SupportEMail) { set_Value (COLUMNNAME_SupportEMail, SupportEMail); } @Override public java.lang.String getSupportEMail() { return get_ValueAsString(COLUMNNAME_SupportEMail); } /** * SystemStatus AD_Reference_ID=374 * Reference name: AD_System Status */ public static final int SYSTEMSTATUS_AD_Reference_ID=374; /** Evaluation = E */ public static final String SYSTEMSTATUS_Evaluation = "E"; /** Implementation = I */ public static final String SYSTEMSTATUS_Implementation = "I"; /** Production = P */ public static final String SYSTEMSTATUS_Production = "P"; @Override public void setSystemStatus (final java.lang.String SystemStatus) { set_Value (COLUMNNAME_SystemStatus, SystemStatus); } @Override public java.lang.String getSystemStatus() { return get_ValueAsString(COLUMNNAME_SystemStatus);
} @Override public void setUserAgent (final @Nullable java.lang.String UserAgent) { set_Value (COLUMNNAME_UserAgent, UserAgent); } @Override public java.lang.String getUserAgent() { return get_ValueAsString(COLUMNNAME_UserAgent); } @Override public void setUserName (final java.lang.String UserName) { set_ValueNoCheck (COLUMNNAME_UserName, UserName); } @Override public java.lang.String getUserName() { return get_ValueAsString(COLUMNNAME_UserName); } @Override public void setVersion (final java.lang.String Version) { set_ValueNoCheck (COLUMNNAME_Version, Version); } @Override public java.lang.String getVersion() { return get_ValueAsString(COLUMNNAME_Version); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Issue.java
1
请完成以下Java代码
public DmnDataTypeTransformerRegistry getDataTypeTransformerRegistry() { return dataTypeTransformerRegistry; } public void setDataTypeTransformerRegistry(DmnDataTypeTransformerRegistry dataTypeTransformerRegistry) { this.dataTypeTransformerRegistry = dataTypeTransformerRegistry; } public DmnTransformer dataTypeTransformerRegistry(DmnDataTypeTransformerRegistry dataTypeTransformerRegistry) { setDataTypeTransformerRegistry(dataTypeTransformerRegistry); return this; } public DmnHitPolicyHandlerRegistry getHitPolicyHandlerRegistry() { return hitPolicyHandlerRegistry; }
public void setHitPolicyHandlerRegistry(DmnHitPolicyHandlerRegistry hitPolicyHandlerRegistry) { this.hitPolicyHandlerRegistry = hitPolicyHandlerRegistry; } public DmnTransformer hitPolicyHandlerRegistry(DmnHitPolicyHandlerRegistry hitPolicyHandlerRegistry) { setHitPolicyHandlerRegistry(hitPolicyHandlerRegistry); return this; } public DmnTransform createTransform() { return transformFactory.createTransform(this); } }
repos\camunda-bpm-platform-master\engine-dmn\engine\src\main\java\org\camunda\bpm\dmn\engine\impl\transform\DefaultDmnTransformer.java
1
请在Spring Boot框架中完成以下Java代码
public class Product { @Id private long id; private String name; private String description; private String category; private BigDecimal unitPrice; public long getId() { return id; } public void setId(long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDescription() { return description; } public void setDescription(String description) {
this.description = description; } public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } public BigDecimal getUnitPrice() { return unitPrice; } public void setUnitPrice(BigDecimal unitPrice) { this.unitPrice = unitPrice; } }
repos\tutorials-master\persistence-modules\java-jpa-2\src\main\java\com\baeldung\jpa\projections\Product.java
2
请在Spring Boot框架中完成以下Java代码
public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public List<RestVariable> getVariables() { return variables; } public void setVariables(List<RestVariable> variables) { this.variables = variables; } public void addVariable(RestVariable variable) { variables.add(variable); } public String getScopeDefinitionId() { return scopeDefinitionId; } public void setScopeDefinitionId(String scopeDefinitionId) { this.scopeDefinitionId = scopeDefinitionId; } public String getScopeId() { return scopeId; } public void setScopeId(String scopeId) { this.scopeId = scopeId; } public String getSubScopeId() { return subScopeId; } public void setSubScopeId(String subScopeId) { this.subScopeId = subScopeId;
} public String getScopeType() { return scopeType; } public void setScopeType(String scopeType) { this.scopeType = scopeType; } public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getTenantId() { return tenantId; } public void setCategory(String category) { this.category = category; } public String getCategory() { return category; } }
repos\flowable-engine-main\modules\flowable-rest\src\main\java\org\flowable\rest\service\api\history\HistoricTaskInstanceResponse.java
2
请完成以下Java代码
public static void givenStack_whenUsingIterator_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20); stack.push(30); Iterator<Integer> iterator = stack.iterator(); while (iterator.hasNext()) { System.out.print(iterator.next() + " "); } } public static void givenStack_whenUsingListIteratorReverseOrder_thenPrintStack() { Stack<Integer> stack = new Stack<>(); stack.push(10); stack.push(20);
stack.push(30); ListIterator<Integer> iterator = stack.listIterator(stack.size()); while (iterator.hasPrevious()) { System.out.print(iterator.previous() + " "); } } public static void givenStack_whenUsingDeque_thenPrintStack() { Deque<Integer> stack = new ArrayDeque<>(); stack.push(10); stack.push(20); stack.push(30); stack.forEach(e -> System.out.print(e + " ")); } }
repos\tutorials-master\core-java-modules\core-java-collections-7\src\main\java\com\baeldung\PrintStack.java
1
请完成以下Java代码
public void markAsCarrierAdviceRequested(final I_M_ShipmentSchedule shipmentSchedule) { if(InterfaceWrapperHelper.isValueChanged(shipmentSchedule, I_M_ShipmentSchedule.COLUMNNAME_M_Shipper_ID)) { shipmentSchedule.setCarrier_Product_ID(CarrierProductId.toRepoId(null)); shipmentSchedule.setCarrier_Goods_Type_ID(CarrierGoodsTypeId.toRepoId(null)); shipmentSchedule.setCarrier_Advising_Status(CarrierAdviseStatus.NotRequested.getCode()); final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoIdOrNull(shipmentSchedule.getM_ShipmentSchedule_ID()); if(shipmentScheduleId != null) { shipmentScheduleService.removeAssignedServiceIdsByShipmentScheduleIds(ImmutableSet.of(shipmentScheduleId)); } } if (!shipmentScheduleService.isEligibleForAutoCarrierAdvise(shipmentSchedule)) { return; } shipmentSchedule.setCarrier_Advising_Status(CarrierAdviseStatus.Requested.getCode()); shipmentSchedule.setCarrier_Product_ID(CarrierProductId.toRepoId(null)); } @ModelChange(timings = {
ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_M_ShipmentSchedule.COLUMNNAME_Carrier_Advising_Status }) public void requestCarrierAdvice(final I_M_ShipmentSchedule shipmentSchedule) { if (!isMarkedAsCarrierAdviceRequested(shipmentSchedule)) { return; } final ShipmentScheduleId shipmentScheduleId = ShipmentScheduleId.ofRepoId(shipmentSchedule.getM_ShipmentSchedule_ID()); final AsyncBatchId asyncBatchId = AsyncBatchId.ofRepoIdOrNull(shipmentSchedule.getC_Async_Batch_ID()); AdviseDeliveryOrderWorkpackageProcessor.enqueueOnTrxCommit(shipmentScheduleId, asyncBatchId); } private boolean isMarkedAsCarrierAdviceRequested(final I_M_ShipmentSchedule shipmentSchedule) { final CarrierAdviseStatus carrierAdviseStatus = CarrierAdviseStatus.ofNullableCode(shipmentSchedule.getCarrier_Advising_Status()); return carrierAdviseStatus != null && carrierAdviseStatus.isRequested(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.commons\src\main\java\de\metas\shipper\gateway\commons\model\interceptor\M_ShipmentSchedule.java
1
请完成以下Java代码
private DocumentId getParentRowId() { return parentRowId; } public boolean isRootRow() { return getParentRowId() == null; } private IViewRowType getType() { return type; } public Builder setType(final IViewRowType type) { this.type = type; return this; } public Builder setProcessed(final boolean processed) { this.processed = processed; return this; } private boolean isProcessed() { if (processed == null) { // NOTE: don't take the "Processed" field if any, because in frontend we will end up with a lot of grayed out completed sales orders, for example. // return DisplayType.toBoolean(values.getOrDefault("Processed", false)); return false; } else { return processed.booleanValue(); } } public Builder putFieldValue(final String fieldName, @Nullable final Object jsonValue) { if (jsonValue == null || JSONNullValue.isNull(jsonValue)) { values.remove(fieldName); } else { values.put(fieldName, jsonValue); } return this; } private Map<String, Object> getValues() { return values; }
public LookupValue getFieldValueAsLookupValue(final String fieldName) { return LookupValue.cast(values.get(fieldName)); } public Builder addIncludedRow(final IViewRow includedRow) { if (includedRows == null) { includedRows = new ArrayList<>(); } includedRows.add(includedRow); return this; } private List<IViewRow> buildIncludedRows() { if (includedRows == null || includedRows.isEmpty()) { return ImmutableList.of(); } return ImmutableList.copyOf(includedRows); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRow.java
1
请完成以下Java代码
public boolean isHigherInclusive() { return this.higherInclusive; } public String toRangeString() { StringBuilder sb = new StringBuilder(); if (this.lowerVersion == null && this.higherVersion == null) { return ""; } if (this.higherVersion != null) { sb.append(this.lowerInclusive ? "[" : "(") .append(this.lowerVersion) .append(",") .append(this.higherVersion) .append(this.higherInclusive ? "]" : ")"); } else { sb.append(this.lowerVersion); } return sb.toString(); } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } VersionRange other = (VersionRange) obj; if (this.higherInclusive != other.higherInclusive) { return false; } if (this.higherVersion == null) { if (other.higherVersion != null) { return false; } } else if (!this.higherVersion.equals(other.higherVersion)) { return false; } if (this.lowerInclusive != other.lowerInclusive) { return false; } if (this.lowerVersion == null) { if (other.lowerVersion != null) { return false;
} } else if (!this.lowerVersion.equals(other.lowerVersion)) { return false; } return true; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + (this.higherInclusive ? 1231 : 1237); result = prime * result + ((this.higherVersion == null) ? 0 : this.higherVersion.hashCode()); result = prime * result + (this.lowerInclusive ? 1231 : 1237); result = prime * result + ((this.lowerVersion == null) ? 0 : this.lowerVersion.hashCode()); return result; } @Override public String toString() { StringBuilder sb = new StringBuilder(); if (this.lowerVersion != null) { sb.append(this.lowerInclusive ? ">=" : ">").append(this.lowerVersion); } if (this.higherVersion != null) { sb.append(" and ").append(this.higherInclusive ? "<=" : "<").append(this.higherVersion); } return sb.toString(); } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\version\VersionRange.java
1
请完成以下Java代码
static MultiValueMap<String, String> toMultiMap(Map<String, String[]> map) { MultiValueMap<String, String> params = new LinkedMultiValueMap<>(map.size()); map.forEach((key, values) -> { if (values.length > 0) { for (String value : values) { params.add(key, value); } } }); return params; } static boolean isAuthorizationResponse(MultiValueMap<String, String> request) { return isAuthorizationResponseSuccess(request) || isAuthorizationResponseError(request); } static boolean isAuthorizationResponseSuccess(MultiValueMap<String, String> request) { return StringUtils.hasText(request.getFirst(OAuth2ParameterNames.CODE)) && StringUtils.hasText(request.getFirst(OAuth2ParameterNames.STATE)); } static boolean isAuthorizationResponseError(MultiValueMap<String, String> request) { return StringUtils.hasText(request.getFirst(OAuth2ParameterNames.ERROR)) && StringUtils.hasText(request.getFirst(OAuth2ParameterNames.STATE)); }
static OAuth2AuthorizationResponse convert(MultiValueMap<String, String> request, String redirectUri) { String code = request.getFirst(OAuth2ParameterNames.CODE); String errorCode = request.getFirst(OAuth2ParameterNames.ERROR); String state = request.getFirst(OAuth2ParameterNames.STATE); if (StringUtils.hasText(code)) { return OAuth2AuthorizationResponse.success(code).redirectUri(redirectUri).state(state).build(); } String errorDescription = request.getFirst(OAuth2ParameterNames.ERROR_DESCRIPTION); String errorUri = request.getFirst(OAuth2ParameterNames.ERROR_URI); // @formatter:off return OAuth2AuthorizationResponse.error(errorCode) .redirectUri(redirectUri) .errorDescription(errorDescription) .errorUri(errorUri) .state(state) .build(); // @formatter:on } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\web\OAuth2AuthorizationResponseUtils.java
1
请完成以下Java代码
public class HtmlList implements HtmlElement { private final Type type; private final List<String> items; public HtmlList(Type type, String... items) { this.type = type; this.items = Arrays.asList(items); } @Override public String html() { String listItems = items.stream().map(el -> format("<li>%s</li>", el)).collect(joining()); return String.format("<%s>%s</%s>", type.tag(), listItems, type.tag()); }
public enum Type { ORDERED("ol"), UNORDERED("ul"); private final String tag; Type(String tag) { this.tag = tag; } public String tag() { return tag; } } }
repos\tutorials-master\patterns-modules\design-patterns-behavioral-2\src\main\java\com\baeldung\fluentinterface\components\HtmlList.java
1
请完成以下Java代码
public void end() { this.ended.set(true); this.recorder.accept(this); } boolean isEnded() { return this.ended.get(); } static class DefaultTag implements Tag { private final String key; private final String value; DefaultTag(String key, String value) { this.key = key; this.value = value;
} @Override public String getKey() { return this.key; } @Override public String getValue() { return this.value; } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\context\metrics\buffering\BufferedStartupStep.java
1
请完成以下Java代码
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String clientId = config.getValue("client.clientId", String.class); String clientSecret = config.getValue("client.clientSecret", String.class); JsonObject actualTokenResponse = (JsonObject) request.getSession().getAttribute("tokenResponse"); Client client = ClientBuilder.newClient(); WebTarget target = client.target(config.getValue("provider.tokenUri", String.class)); Form form = new Form(); form.param("grant_type", "refresh_token"); form.param("refresh_token", actualTokenResponse.getString("refresh_token")); String scope = request.getParameter("scope"); if (scope != null && !scope.isEmpty()) {
form.param("scope", scope); } Response jaxrsResponse = target.request(MediaType.APPLICATION_JSON_TYPE) .header(HttpHeaders.AUTHORIZATION, getAuthorizationHeaderValue(clientId, clientSecret)) .post(Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE), Response.class); JsonObject tokenResponse = jaxrsResponse.readEntity(JsonObject.class); if (jaxrsResponse.getStatus() == 200) { request.getSession().setAttribute("tokenResponse", tokenResponse); } else { request.setAttribute("error", tokenResponse.getString("error_description", "error!")); } dispatch("/", request, response); } }
repos\tutorials-master\security-modules\oauth2-framework-impl\oauth2-client\src\main\java\com\baeldung\oauth2\client\RefreshTokenServlet.java
1
请完成以下Java代码
private static boolean matchesAccessToken(OAuth2Authorization authorization, String token) { OAuth2Authorization.Token<OAuth2AccessToken> accessToken = authorization.getToken(OAuth2AccessToken.class); return accessToken != null && accessToken.getToken().getTokenValue().equals(token); } private static boolean matchesRefreshToken(OAuth2Authorization authorization, String token) { OAuth2Authorization.Token<OAuth2RefreshToken> refreshToken = authorization.getToken(OAuth2RefreshToken.class); return refreshToken != null && refreshToken.getToken().getTokenValue().equals(token); } private static boolean matchesIdToken(OAuth2Authorization authorization, String token) { OAuth2Authorization.Token<OidcIdToken> idToken = authorization.getToken(OidcIdToken.class); return idToken != null && idToken.getToken().getTokenValue().equals(token); } private static boolean matchesDeviceCode(OAuth2Authorization authorization, String token) { OAuth2Authorization.Token<OAuth2DeviceCode> deviceCode = authorization.getToken(OAuth2DeviceCode.class); return deviceCode != null && deviceCode.getToken().getTokenValue().equals(token); }
private static boolean matchesUserCode(OAuth2Authorization authorization, String token) { OAuth2Authorization.Token<OAuth2UserCode> userCode = authorization.getToken(OAuth2UserCode.class); return userCode != null && userCode.getToken().getTokenValue().equals(token); } private static final class MaxSizeHashMap<K, V> extends LinkedHashMap<K, V> { private final int maxSize; private MaxSizeHashMap(int maxSize) { this.maxSize = maxSize; } @Override protected boolean removeEldestEntry(Map.Entry<K, V> eldest) { return size() > this.maxSize; } } }
repos\spring-security-main\oauth2\oauth2-authorization-server\src\main\java\org\springframework\security\oauth2\server\authorization\InMemoryOAuth2AuthorizationService.java
1
请完成以下Java代码
public static int findByBruteForce(int n) { for (int i = n - 1; i >= 2; i--) { if (isPrime(i)) { return i; } } return -1; // Return -1 if no prime number is found } public static boolean isPrime(int number) { for (int i = 2; i <= Math.sqrt(number); i++) { if (number % i == 0) { return false; } } return true; } public static int findBySieveOfEratosthenes(int n) { boolean[] isPrime = new boolean[n]; Arrays.fill(isPrime, true);
for (int p = 2; p*p < n; p++) { if (isPrime[p]) { for (int i = p * p; i < n; i += p) { isPrime[i] = false; } } } for (int i = n - 1; i >= 2; i--) { if (isPrime[i]) { return i; } } return -1; } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-7\src\main\java\com\baeldung\algorithms\primeundernumber\LargestPrimeFinder.java
1
请完成以下Java代码
public class User { private UUID id; private String name; private String email; @DynamoDbPartitionKey public UUID getId() { return id; } public void setId(UUID id) { this.id = id; } public String getName() {
return name; } public void setName(String name) { this.name = name; } public String getEmail() { return email; } public void setEmail(String email) { this.email = email; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-aws-v3\src\main\java\com\baeldung\spring\cloud\aws\dynamodb\User.java
1
请在Spring Boot框架中完成以下Java代码
public void configure(RedisConnection connection) { String notifyOptions = getNotifyOptions(connection); String customizedNotifyOptions = notifyOptions; if (!customizedNotifyOptions.contains("E")) { customizedNotifyOptions += "E"; } boolean A = customizedNotifyOptions.contains("A"); if (!(A || customizedNotifyOptions.contains("g"))) { customizedNotifyOptions += "g"; } if (!(A || customizedNotifyOptions.contains("x"))) { customizedNotifyOptions += "x"; } if (!notifyOptions.equals(customizedNotifyOptions)) { connection.serverCommands().setConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS, customizedNotifyOptions); } } private String getNotifyOptions(RedisConnection connection) {
try { Properties config = connection.serverCommands().getConfig(CONFIG_NOTIFY_KEYSPACE_EVENTS); if (config.isEmpty()) { return ""; } return config.getProperty(config.stringPropertyNames().iterator().next()); } catch (InvalidDataAccessApiUsageException ex) { throw new IllegalStateException( "Unable to configure Redis to keyspace notifications. See https://docs.spring.io/spring-session/docs/current/reference/html5/#api-redisindexedsessionrepository-sessiondestroyedevent", ex); } } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\ConfigureNotifyKeyspaceEventsAction.java
2
请完成以下Java代码
public DefaultSyncHttpGraphQlClientBuilder messageConverters(Consumer<List<HttpMessageConverter<?>>> configurer) { this.restClientBuilder.messageConverters(configurer); return this; } @Override public DefaultSyncHttpGraphQlClientBuilder configureMessageConverters(Consumer<HttpMessageConverters.ClientBuilder> configurer) { this.restClientBuilder.configureMessageConverters(configurer); return this; } @Override public DefaultSyncHttpGraphQlClientBuilder restClient(Consumer<RestClient.Builder> configurer) { configurer.accept(this.restClientBuilder); return this; } @Override @SuppressWarnings("unchecked") public HttpSyncGraphQlClient build() { this.restClientBuilder.configureMessageConverters((builder) -> { builder.registerDefaults().configureMessageConverters((converter) -> { if (HttpMessageConverterDelegate.isJsonConverter(converter)) { setJsonConverter((HttpMessageConverter<Object>) converter); } }); }); RestClient restClient = this.restClientBuilder.build(); HttpSyncGraphQlTransport transport = new HttpSyncGraphQlTransport(restClient); GraphQlClient graphQlClient = super.buildGraphQlClient(transport); return new DefaultHttpSyncGraphQlClient(graphQlClient, restClient, getBuilderInitializer()); } /** * Default {@link HttpSyncGraphQlClient} implementation. */ private static class DefaultHttpSyncGraphQlClient extends AbstractDelegatingGraphQlClient implements HttpSyncGraphQlClient { private final RestClient restClient; private final Consumer<AbstractGraphQlClientSyncBuilder<?>> builderInitializer;
DefaultHttpSyncGraphQlClient( GraphQlClient delegate, RestClient restClient, Consumer<AbstractGraphQlClientSyncBuilder<?>> builderInitializer) { super(delegate); Assert.notNull(restClient, "RestClient is required"); Assert.notNull(builderInitializer, "`builderInitializer` is required"); this.restClient = restClient; this.builderInitializer = builderInitializer; } @Override public DefaultSyncHttpGraphQlClientBuilder mutate() { DefaultSyncHttpGraphQlClientBuilder builder = new DefaultSyncHttpGraphQlClientBuilder(this.restClient); this.builderInitializer.accept(builder); return builder; } } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\client\DefaultSyncHttpGraphQlClientBuilder.java
1
请完成以下Java代码
public class Item { private String location; private String description; private String timeStamp; @Column(name = "location") public String getLocation() { return location; } public void setLocation(String location) { this.location = location; } @Column(name = "description") public String getDescription() { return description;
} public void setDescription(String description) { this.description = description; } @Column(name = "timestamp") public String getTimeStamp() { return timeStamp; } public void setTimeStamp(String timeStamp) { this.timeStamp = timeStamp; } }
repos\tutorials-master\aws-modules\aws-lambda-modules\shipping-tracker-lambda\ShippingFunction\src\main\java\com\baeldung\lambda\shipping\Item.java
1
请完成以下Java代码
protected String getDeploymentMode() { return DEPLOYMENT_MODE; } @Override protected void deployResourcesInternal(String deploymentNameHint, Resource[] resources, CmmnEngine engine) { CmmnRepositoryService repositoryService = engine.getCmmnRepositoryService(); // Create a single deployment for all resources using the name hint as the literal name final CmmnDeploymentBuilder deploymentBuilder = repositoryService.createDeployment().enableDuplicateFiltering().name(deploymentNameHint); for (final Resource resource : resources) { addResource(resource, deploymentBuilder); } try {
deploymentBuilder.deploy(); } catch (RuntimeException e) { if (isThrowExceptionOnDeploymentFailure()) { throw e; } else { LOGGER.warn("Exception while autodeploying CMMN definitions. " + "This exception can be ignored if the root cause indicates a unique constraint violation, " + "which is typically caused by two (or more) servers booting up at the exact same time and deploying the same definitions. ", e); } } } }
repos\flowable-engine-main\modules\flowable-cmmn-spring\src\main\java\org\flowable\cmmn\spring\autodeployment\DefaultAutoDeploymentStrategy.java
1
请完成以下Java代码
private UserNotificationRequest createUserNotification(@NonNull final ProductId productId) { final IADWindowDAO adWindowDAO = Services.get(IADWindowDAO.class); final AdWindowId productWindowId = adWindowDAO.getAdWindowId(I_M_Product.Table_Name, SOTrx.SALES, DEFAULT_WINDOW_Product); final TableRecordReference productRef = toTableRecordRef(productId); return newUserNotificationRequest() .recipientUserId(Env.getLoggedUserId()) .contentADMessage(MSG_ProductWithNoCustomsTariff) .contentADMessageParam(productRef) .targetAction(TargetRecordAction.ofRecordAndWindow(productRef, productWindowId)) .build(); } private static TableRecordReference toTableRecordRef(final ProductId productId)
{ return TableRecordReference.of(I_M_Product.Table_Name, productId); } private UserNotificationRequest.UserNotificationRequestBuilder newUserNotificationRequest() { return UserNotificationRequest.builder() .topic(EVENTBUS_TOPIC); } private void postNotifications(final List<UserNotificationRequest> notifications) { Services.get(INotificationBL.class).sendAfterCommit(notifications); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\product\event\ProductWithNoCustomsTariffUserNotificationsProducer.java
1
请完成以下Java代码
public void setServiceDate (Timestamp ServiceDate) { set_Value (COLUMNNAME_ServiceDate, ServiceDate); } /** Get Service date. @return Date service was provided */ public Timestamp getServiceDate () { return (Timestamp)get_Value(COLUMNNAME_ServiceDate); } /** Set Text Message. @param TextMsg Text Message */ public void setTextMsg (String TextMsg) { set_Value (COLUMNNAME_TextMsg, TextMsg); } /** Get Text Message. @return Text Message */ public String getTextMsg () { return (String)get_Value(COLUMNNAME_TextMsg); } public I_C_ElementValue getUser1() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name) .getPO(getUser1_ID(), get_TrxName()); } /** Set User List 1. @param User1_ID User defined list element #1 */ public void setUser1_ID (int User1_ID) { if (User1_ID < 1) set_Value (COLUMNNAME_User1_ID, null); else set_Value (COLUMNNAME_User1_ID, Integer.valueOf(User1_ID)); } /** Get User List 1. @return User defined list element #1 */ public int getUser1_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User1_ID); if (ii == null) return 0; return ii.intValue(); } public I_C_ElementValue getUser2() throws RuntimeException { return (I_C_ElementValue)MTable.get(getCtx(), I_C_ElementValue.Table_Name)
.getPO(getUser2_ID(), get_TrxName()); } /** Set User List 2. @param User2_ID User defined list element #2 */ public void setUser2_ID (int User2_ID) { if (User2_ID < 1) set_Value (COLUMNNAME_User2_ID, null); else set_Value (COLUMNNAME_User2_ID, Integer.valueOf(User2_ID)); } /** Get User List 2. @return User defined list element #2 */ public int getUser2_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_User2_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Valid from. @param ValidFrom Valid from including this date (first day) */ public void setValidFrom (Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Valid from. @return Valid from including this date (first day) */ public Timestamp getValidFrom () { return (Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\eevolution\model\X_HR_Movement.java
1
请完成以下Java代码
public TaskQueryImpl createTaskQuery() { return new TaskQueryImpl(); } public JobQueryImpl createJobQuery() { return new JobQueryImpl(); } public HistoricProcessInstanceQueryImpl createHistoricProcessInstanceQuery() { return new HistoricProcessInstanceQueryImpl(); } public HistoricActivityInstanceQueryImpl createHistoricActivityInstanceQuery() { return new HistoricActivityInstanceQueryImpl(); } public HistoricTaskInstanceQueryImpl createHistoricTaskInstanceQuery() { return new HistoricTaskInstanceQueryImpl(); } public HistoricDetailQueryImpl createHistoricDetailQuery() { return new HistoricDetailQueryImpl(); }
public HistoricVariableInstanceQueryImpl createHistoricVariableInstanceQuery() { return new HistoricVariableInstanceQueryImpl(); } // getters and setters // ////////////////////////////////////////////////////// public SqlSession getSqlSession() { return sqlSession; } public DbSqlSessionFactory getDbSqlSessionFactory() { return dbSqlSessionFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\db\DbSqlSession.java
1
请完成以下Java代码
public class Client implements BundleActivator, ServiceListener { private BundleContext ctx; private ServiceReference serviceReference; public void start(BundleContext ctx) { this.ctx = ctx; try { ctx.addServiceListener(this, "(objectclass=" + Greeter.class.getName() + ")"); } catch (InvalidSyntaxException ise) { ise.printStackTrace(); } } public void stop(BundleContext bundleContext) { if (serviceReference != null) { ctx.ungetService(serviceReference); } this.ctx = null; } public void serviceChanged(ServiceEvent serviceEvent) { int type = serviceEvent.getType(); switch (type) {
case (ServiceEvent.REGISTERED): System.out.println("Notification of service registered."); serviceReference = serviceEvent.getServiceReference(); Greeter service = (Greeter) (ctx.getService(serviceReference)); System.out.println(service.sayHiTo("John")); break; case (ServiceEvent.UNREGISTERING): System.out.println("Notification of service unregistered."); ctx.ungetService(serviceEvent.getServiceReference()); break; default: break; } } }
repos\tutorials-master\osgi\osgi-intro-sample-client\src\main\java\com\baeldung\osgi\sample\client\Client.java
1
请完成以下Java代码
public void setC_Order_ID (final int C_Order_ID) { if (C_Order_ID < 1) set_Value (COLUMNNAME_C_Order_ID, null); else set_Value (COLUMNNAME_C_Order_ID, C_Order_ID); } @Override public int getC_Order_ID() { return get_ValueAsInt(COLUMNNAME_C_Order_ID); } @Override public void setDateOrdered (final @Nullable java.sql.Timestamp DateOrdered) { set_Value (COLUMNNAME_DateOrdered, DateOrdered); } @Override public java.sql.Timestamp getDateOrdered() { return get_ValueAsTimestamp(COLUMNNAME_DateOrdered); } @Override public void setEDI_cctop_111_v_ID (final int EDI_cctop_111_v_ID) { if (EDI_cctop_111_v_ID < 1) set_ValueNoCheck (COLUMNNAME_EDI_cctop_111_v_ID, null); else set_ValueNoCheck (COLUMNNAME_EDI_cctop_111_v_ID, EDI_cctop_111_v_ID); } @Override public int getEDI_cctop_111_v_ID() { return get_ValueAsInt(COLUMNNAME_EDI_cctop_111_v_ID); } @Override public org.compiere.model.I_M_InOut getM_InOut() { return get_ValueAsPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class); } @Override public void setM_InOut(final org.compiere.model.I_M_InOut M_InOut) { set_ValueFromPO(COLUMNNAME_M_InOut_ID, org.compiere.model.I_M_InOut.class, M_InOut); } @Override public void setM_InOut_ID (final int M_InOut_ID) { if (M_InOut_ID < 1) set_Value (COLUMNNAME_M_InOut_ID, null); else set_Value (COLUMNNAME_M_InOut_ID, M_InOut_ID); }
@Override public int getM_InOut_ID() { return get_ValueAsInt(COLUMNNAME_M_InOut_ID); } @Override public void setMovementDate (final @Nullable java.sql.Timestamp MovementDate) { set_Value (COLUMNNAME_MovementDate, MovementDate); } @Override public java.sql.Timestamp getMovementDate() { return get_ValueAsTimestamp(COLUMNNAME_MovementDate); } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setShipment_DocumentNo (final @Nullable java.lang.String Shipment_DocumentNo) { set_Value (COLUMNNAME_Shipment_DocumentNo, Shipment_DocumentNo); } @Override public java.lang.String getShipment_DocumentNo() { return get_ValueAsString(COLUMNNAME_Shipment_DocumentNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.edi\src\main\java-gen\de\metas\esb\edi\model\X_EDI_cctop_111_v.java
1
请完成以下Java代码
public ILoggable addLog(final String msg, final Object... msgParameters) { if (msg == null) { logger.warn("Called with msg=null; msgParameters={}; -> ignoring;", msgParameters); return this; } final LoggableWithThrowableUtil.FormattedMsgWithAdIssueId msgAndAdIssueId = LoggableWithThrowableUtil.extractMsgAndAdIssue(msg, msgParameters); final ProcessInfoLog processInfoLog = ProcessInfoLog.ofMessage(msgAndAdIssueId.getFormattedMessage()); addToBuffer(processInfoLog); return this; } @Override public void flush() { List<ProcessInfoLog> logEntries = null; try { //note: synchronized with addToBuffer mainLock.lock(); logEntries = buffer; this.buffer = null; if (logEntries == null || logEntries.isEmpty()) { return; } pInstanceDAO.saveProcessInfoLogs(pInstanceId, logEntries); } catch (final Exception ex) { // make sure flush never fails logger.warn("Failed saving {} log entries but IGNORED: {}", logEntries != null ? logEntries.size() : 0, logEntries, ex); } finally { mainLock.unlock(); } } private void addToBuffer(final ProcessInfoLog logEntry)
{ try { //making sure there is no flush going on in a diff thread while adding to buffer mainLock.lock(); List<ProcessInfoLog> buffer = this.buffer; if (buffer == null) { buffer = this.buffer = new ArrayList<>(bufferSize); } buffer.add(logEntry); if (buffer.size() >= bufferSize) { flush(); } } finally { mainLock.unlock(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\process\impl\ADProcessLoggable.java
1
请在Spring Boot框架中完成以下Java代码
class Tree extends ReflectionWrapper { private final Class<?> treeVisitorType = findClass("com.sun.source.tree.TreeVisitor"); private final Method acceptMethod = findMethod("accept", this.treeVisitorType, Object.class); private final Method getClassTreeMembers = findMethod(findClass("com.sun.source.tree.ClassTree"), "getMembers"); Tree(Object instance) { super("com.sun.source.tree.Tree", instance); } void accept(TreeVisitor visitor) throws Exception { this.acceptMethod.invoke(getInstance(), Proxy.newProxyInstance(getInstance().getClass().getClassLoader(), new Class<?>[] { this.treeVisitorType }, new TreeVisitorInvocationHandler(visitor)), 0); } /** * {@link InvocationHandler} to call the {@link TreeVisitor}. */ private class TreeVisitorInvocationHandler implements InvocationHandler { private TreeVisitor treeVisitor; TreeVisitorInvocationHandler(TreeVisitor treeVisitor) { this.treeVisitor = treeVisitor; }
@Override @SuppressWarnings("rawtypes") public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (method.getName().equals("visitClass") && (Integer) args[1] == 0) { Iterable members = (Iterable) Tree.this.getClassTreeMembers.invoke(args[0]); for (Object member : members) { if (member != null) { Tree.this.acceptMethod.invoke(member, proxy, ((Integer) args[1]) + 1); } } } if (method.getName().equals("visitVariable")) { this.treeVisitor.visitVariable(new VariableTree(args[0])); } return null; } } }
repos\spring-boot-4.0.1\configuration-metadata\spring-boot-configuration-processor\src\main\java\org\springframework\boot\configurationprocessor\fieldvalues\javac\Tree.java
2
请完成以下Java代码
public void handleRecord(@NonNull final Object recordModel) { columns.forEach((column) -> handleColumn(recordModel, column)); } private void handleColumn( @NonNull final Object recordModel, @NonNull final MinimalColumnInfo column) { if (!InterfaceWrapperHelper.isNullOrEmpty(recordModel, column.getColumnName())) { return; } final int resultId = retrieveFirstValRuleResultId(recordModel, column, adReferenceService); final int firstValidId = InterfaceWrapperHelper.getFirstValidIdByColumnName(column.getColumnName()); if (resultId >= firstValidId) { InterfaceWrapperHelper.setValue(recordModel, column.getColumnName(), resultId); } } private static int retrieveFirstValRuleResultId( @NonNull final Object recordModel, @NonNull final MinimalColumnInfo column, @NonNull final ADReferenceService adReferenceService) { final ADRefTable tableRefInfo = extractTableRefInfo(column, adReferenceService); final IQueryBuilder<Object> queryBuilder = Services.get(IQueryBL.class) .createQueryBuilder(tableRefInfo.getTableName()); final AdValRuleId adValRuleId = column.getAdValRuleId(); if (adValRuleId != null) { final ValidationRuleQueryFilter<Object> validationRuleQueryFilter = new ValidationRuleQueryFilter<>(recordModel, adValRuleId); queryBuilder.filter(validationRuleQueryFilter); } final IQuery<Object> query = queryBuilder .create()
.setRequiredAccess(Access.READ); final String orderByClause = tableRefInfo.getOrderByClause(); if (query instanceof TypedSqlQuery && !Check.isEmpty(orderByClause, true)) { @SuppressWarnings("rawtypes") final TypedSqlQuery sqlQuery = (TypedSqlQuery)query; sqlQuery.setOrderBy(orderByClause); } return query.firstId(); } private static ADRefTable extractTableRefInfo(@NonNull final MinimalColumnInfo column, @NonNull final ADReferenceService adReferenceService) { final ReferenceId adReferenceValueId = column.getAdReferenceValueId(); return adReferenceValueId != null ? adReferenceService.retrieveTableRefInfo(adReferenceValueId) : adReferenceService.getTableDirectRefInfo(column.getColumnName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\column\autoapplyvalrule\ValRuleAutoApplier.java
1
请完成以下Java代码
public class XmlDocumentToString { public static final String FRUIT_XML = "<fruit><name>Apple</name><color>Red</color><weight unit=\"grams\">150</weight><sweetness>7</sweetness></fruit>"; public static Document getDocument() throws SAXException, IOException, ParserConfigurationException { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); Document document = factory.newDocumentBuilder() .parse(new InputSource(new StringReader(FRUIT_XML))); return document; } public static String toString(Document document) throws TransformerException { StringWriter stringWriter = new StringWriter(); getTransformer().transform(new DOMSource(document), new StreamResult(stringWriter)); return stringWriter.toString(); } public static String toStringWithOptions(Document document) throws TransformerException { Transformer transformer = getTransformer();
transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4"); StringWriter stringWriter = new StringWriter(); transformer.transform(new DOMSource(document), new StreamResult(stringWriter)); return stringWriter.toString(); } private static Transformer getTransformer() throws TransformerConfigurationException { TransformerFactory transformerFactory = TransformerFactory.newInstance(); return transformerFactory.newTransformer(); } }
repos\tutorials-master\xml-modules\xml\src\main\java\com\baeldung\xml\xml2string\XmlDocumentToString.java
1
请完成以下Java代码
public boolean requestFocusInWindow() { return this.editor.requestFocusInWindow(); } public void setText(String html) { this.editor.setText(html); } public void setCaretPosition(int position) { this.editor.setCaretPosition(position); } public ActionMap getEditorActionMap() { return this.editor.getActionMap(); }
public InputMap getEditorInputMap(int condition) { return this.editor.getInputMap(condition); } public Keymap getEditorKeymap() { return this.editor.getKeymap(); } public JTextComponent getTextComponent() { return this.editor; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\net\sf\memoranda\ui\htmleditor\HTMLEditor.java
1
请完成以下Java代码
public void setId(String id) { this.id = id; } public String getId() { return id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getWidth() { return width; } public void setWidth(int width) { this.width = width; }
public int getHeight() { return height; } public void setHeight(int height) { this.height = height; } public List<String> getFlowNodeIds() { if(flowNodeIds == null) { flowNodeIds = new ArrayList<String>(); } return flowNodeIds; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\process\Lane.java
1
请在Spring Boot框架中完成以下Java代码
public void setTaskExecutor(@Nullable Executor taskExecutor) { this.taskExecutor = taskExecutor; } protected final RabbitProperties getRabbitProperties() { return this.rabbitProperties; } /** * Configure the specified rabbit listener container factory. The factory can be * further tuned and default settings can be overridden. * @param factory the {@link AbstractRabbitListenerContainerFactory} instance to * configure * @param connectionFactory the {@link ConnectionFactory} to use */ public abstract void configure(T factory, ConnectionFactory connectionFactory); protected void configure(T factory, ConnectionFactory connectionFactory, RabbitProperties.AmqpContainer configuration) { Assert.notNull(factory, "'factory' must not be null"); Assert.notNull(connectionFactory, "'connectionFactory' must not be null"); Assert.notNull(configuration, "'configuration' must not be null"); factory.setConnectionFactory(connectionFactory); if (this.messageConverter != null) { factory.setMessageConverter(this.messageConverter); } factory.setAutoStartup(configuration.isAutoStartup()); if (configuration.getAcknowledgeMode() != null) { factory.setAcknowledgeMode(configuration.getAcknowledgeMode()); } if (configuration.getPrefetch() != null) { factory.setPrefetchCount(configuration.getPrefetch()); } if (configuration.getDefaultRequeueRejected() != null) { factory.setDefaultRequeueRejected(configuration.getDefaultRequeueRejected()); } if (configuration.getIdleEventInterval() != null) { factory.setIdleEventInterval(configuration.getIdleEventInterval().toMillis()); }
factory.setMissingQueuesFatal(configuration.isMissingQueuesFatal()); factory.setDeBatchingEnabled(configuration.isDeBatchingEnabled()); factory.setForceStop(configuration.isForceStop()); if (this.taskExecutor != null) { factory.setTaskExecutor(this.taskExecutor); } factory.setObservationEnabled(configuration.isObservationEnabled()); ListenerRetry retryConfig = configuration.getRetry(); if (retryConfig.isEnabled()) { RetryInterceptorBuilder<?, ?> builder = (retryConfig.isStateless()) ? RetryInterceptorBuilder.stateless() : RetryInterceptorBuilder.stateful(); builder.retryPolicy(createRetryPolicy(retryConfig)); MessageRecoverer recoverer = (this.messageRecoverer != null) ? this.messageRecoverer : new RejectAndDontRequeueRecoverer(); builder.recoverer(recoverer); factory.setAdviceChain(builder.build()); } } private RetryPolicy createRetryPolicy(Retry retryProperties) { RetryPolicySettings retrySettings = retryProperties.initializeRetryPolicySettings(); if (this.retrySettingsCustomizers != null) { for (RabbitListenerRetrySettingsCustomizer customizer : this.retrySettingsCustomizers) { customizer.customize(retrySettings); } } return retrySettings.createRetryPolicy(); } }
repos\spring-boot-4.0.1\module\spring-boot-amqp\src\main\java\org\springframework\boot\amqp\autoconfigure\AbstractRabbitListenerContainerFactoryConfigurer.java
2
请完成以下Java代码
default Channel createChannel(final String name) { return createChannel(name, Collections.emptyList()); } /** * Creates a new channel for the given service name. The returned channel will use all globally registered * {@link ClientInterceptor}s. * * <p> * <b>Note:</b> The underlying implementation might reuse existing {@link ManagedChannel}s allow connection reuse. * </p> * * <p> * <b>Note:</b> The given interceptors will be appended to the global interceptors and applied using * {@link ClientInterceptors#interceptForward(Channel, ClientInterceptor...)}. * </p> * * @param name The name of the service. * @param interceptors A list of additional client interceptors that should be added to the channel. * @return The newly created channel for the given service. */ default Channel createChannel(final String name, final List<ClientInterceptor> interceptors) { return createChannel(name, interceptors, false); } /** * Creates a new channel for the given service name. The returned channel will use all globally registered * {@link ClientInterceptor}s. * * <p> * <b>Note:</b> The underlying implementation might reuse existing {@link ManagedChannel}s allow connection reuse. * </p> * * <p> * <b>Note:</b> The given interceptors will be appended to the global interceptors and applied using
* {@link ClientInterceptors#interceptForward(Channel, ClientInterceptor...)}. * </p> * * @param name The name of the service. * @param interceptors A list of additional client interceptors that should be added to the channel. * @param sortInterceptors Whether the interceptors (both global and custom) should be sorted before being applied. * @return The newly created channel for the given service. */ Channel createChannel(String name, List<ClientInterceptor> interceptors, boolean sortInterceptors); /** * Gets an unmodifiable map that contains the names of the created channel with their current * {@link ConnectivityState}. This method will return an empty map, if the feature is not supported. * * @return A map with the channel names and their connectivity state. */ default Map<String, ConnectivityState> getConnectivityState() { return Collections.emptyMap(); } @Override void close(); }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\channelfactory\GrpcChannelFactory.java
1
请完成以下Java代码
public class PropertyEntityImpl extends AbstractEntity implements PropertyEntity, Serializable { private static final long serialVersionUID = 1L; protected String name; protected String value; public PropertyEntityImpl() {} public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; }
public String getId() { return name; } public Object getPersistentState() { return value; } public void setId(String id) { throw new ActivitiException("only provided id generation allowed for properties"); } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "PropertyEntity[name=" + name + ", value=" + value + "]"; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\PropertyEntityImpl.java
1
请完成以下Java代码
public String getTargetMethod() { return targetMethod; } public void setTargetMethod(String targetMethod) { this.targetMethod = targetMethod; } public List<Object> getArguments() { return arguments; } public void setArguments(List<Object> arguments) { this.arguments = arguments; } public List<String> getParameterTypes() { return parameterTypes; } public void setParameterTypes(List<String> parameterTypes) { this.parameterTypes = parameterTypes; } /** * 必须重写equals和hashCode方法,否则放到set集合里没法去重 * * @param o * @return */ @Override public boolean equals(Object o) { if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; } CachedMethodInvocation that = (CachedMethodInvocation) o; return key.equals(that.key); } @Override public int hashCode() { return key.hashCode(); } }
repos\spring-boot-student-master\spring-boot-student-cache-redis\src\main\java\com\xiaolyuh\redis\cache\CachedMethodInvocation.java
1
请完成以下Java代码
public static String sign(String username, String secret) { Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME); Algorithm algorithm = Algorithm.HMAC256(secret); // 附带username信息 return JWT.create() .withClaim("username", username) .withExpiresAt(date) .sign(algorithm); } /** * 校验token是否正确 * * @param token 密钥 * @param secret 用户的密码 * @return 是否正确 */ public static boolean verify(String token, String username, String secret) {
Algorithm algorithm = Algorithm.HMAC256(secret); JWTVerifier verifier = JWT.require(algorithm) .withClaim("username", username) .build(); DecodedJWT jwt = verifier.verify(token); return true; } /** * 获得token中的信息无需secret解密也能获得 * * @return token中包含的用户名 */ public static String getUsername(String token) { DecodedJWT jwt = JWT.decode(token); return jwt.getClaim("username").asString(); } }
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\common\util\JWTUtil.java
1
请完成以下Java代码
public URI storeAttachment(@NonNull final AttachmentEntry attachmentEntry) { final boolean attachmentIsStoredForThefirstTime = !attachmentEntry .getTags() .toMap() .keySet() .stream() .anyMatch(key -> key.startsWith(AttachmentTags.TAGNAME_STORED_PREFIX)); byte[] attachmentDataToStore; if (attachmentIsStoredForThefirstTime) { attachmentDataToStore = attachmentEntryService.retrieveData(attachmentEntry.getId()); } else { attachmentDataToStore = computeDataWithCopyFlagSetToTrue(attachmentEntry); } final String directory = retrieveDirectoryOrNull(attachmentEntry); final File file = new File(directory, attachmentEntry.getFilename()); try (final FileOutputStream fileOutputStream = new FileOutputStream(file)) { fileOutputStream.write(attachmentDataToStore); return file.toURI(); } catch (final IOException e) { throw new AdempiereException("Unable to write attachment data to file", e).appendParametersToMessage() .setParameter("file", file) .setParameter("attachmentEntry", attachmentEntry); } } private byte[] computeDataWithCopyFlagSetToTrue(@NonNull final AttachmentEntry attachmentEntry) { byte[] attachmentData = attachmentEntryService.retrieveData(attachmentEntry.getId()); // get the converter to use final String xsdName = XmlIntrospectionUtil.extractXsdValueOrNull(new ByteArrayInputStream(attachmentData)); final CrossVersionRequestConverter converter = crossVersionServiceRegistry.getRequestConverterForXsdName(xsdName); Check.assumeNotNull(converter, "Missing CrossVersionRequestConverter for XSD={}; attachmentEntry={}", xsdName, attachmentEntry); // convert to crossVersion data final XmlRequest crossVersionRequest = converter.toCrossVersionRequest(new ByteArrayInputStream(attachmentData));
// patch final XmlRequest updatedCrossVersionRequest = updateCrossVersionRequest(crossVersionRequest); // convert back to byte[] final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); converter.fromCrossVersionRequest(updatedCrossVersionRequest, outputStream); return outputStream.toByteArray(); } private XmlRequest updateCrossVersionRequest(@NonNull final XmlRequest crossVersionRequest) { final RequestMod mod = RequestMod .builder() .payloadMod(PayloadMod .builder() .copy(true) .build()) .build(); return crossVersionRequest.withMod(mod); } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_base\src\main\java\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\base\store\StoreForumDatenaustauschAttachmentService.java
1
请完成以下Java代码
public String getSql() { buildSql(); return sqlWhereClause; } @Override public List<Object> getSqlParams(final Properties ctx) { buildSql(); return sqlParams; } private boolean sqlBuilt = false; private String sqlWhereClause = null; private List<Object> sqlParams = null;
private final void buildSql() { if (sqlBuilt) { return; } sqlWhereClause = "Record_ID = ? AND AD_Table_ID = ?"; sqlParams = new ArrayList<Object>(); sqlParams.add(InterfaceWrapperHelper.getId(referencedModel)); sqlParams.add(MTable.getTable_ID(InterfaceWrapperHelper.getModelTableName(referencedModel))); sqlBuilt = true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\ReferencingPOFilter.java
1
请完成以下Java代码
public class MybatisJoinHelper { protected static final EnginePersistenceLogger LOG = ProcessEngineLogger.PERSISTENCE_LOGGER; protected static final String DEFAULT_ORDER = "RES.ID_ asc"; public static Map<String, MyBatisTableMapping> mappings = new HashMap<String, MyBatisTableMapping>(); static { mappings.put(QueryOrderingProperty.RELATION_VARIABLE, new VariableTableMapping()); mappings.put(QueryOrderingProperty.RELATION_PROCESS_DEFINITION, new ProcessDefinitionTableMapping()); mappings.put(QueryOrderingProperty.RELATION_CASE_DEFINITION, new CaseDefinitionTableMapping()); mappings.put(QueryOrderingProperty.RELATION_DEPLOYMENT, new DeploymentTableMapping()); } public static String tableAlias(String relation, int index) { if (relation == null) { return "RES"; } else { MyBatisTableMapping mapping = getTableMapping(relation); if (mapping.isOneToOneRelation()) { return mapping.getTableAlias(); } else { return mapping.getTableAlias() + index; } } } public static String tableMapping(String relation) { MyBatisTableMapping mapping = getTableMapping(relation); return mapping.getTableName(); } public static String orderBySelection(QueryOrderingProperty orderingProperty, int index) { QueryProperty queryProperty = orderingProperty.getQueryProperty(); StringBuilder sb = new StringBuilder(); if (queryProperty.getFunction() != null) { sb.append(queryProperty.getFunction()); sb.append("("); } sb.append(tableAlias(orderingProperty.getRelation(), index)); sb.append("."); sb.append(queryProperty.getName()); if (queryProperty.getFunction() != null) { sb.append(")");
} return sb.toString(); } public static String orderBy(QueryOrderingProperty orderingProperty, int index) { QueryProperty queryProperty = orderingProperty.getQueryProperty(); StringBuilder sb = new StringBuilder(); sb.append(tableAlias(orderingProperty.getRelation(), index)); if (orderingProperty.isContainedProperty()) { sb.append("."); } else { sb.append("_"); } sb.append(queryProperty.getName()); sb.append(" "); sb.append(orderingProperty.getDirection().getName()); return sb.toString(); } protected static MyBatisTableMapping getTableMapping(String relation) { MyBatisTableMapping mapping = mappings.get(relation); if (mapping == null) { throw LOG.missingRelationMappingException(relation); } return mapping; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\sql\MybatisJoinHelper.java
1
请完成以下Java代码
public SimpleDateFormat getTimeFormat() { if(Adempiere.isUnitTestMode() && useJUnitFixedFormats) { log.warn("Using fixed time format: {}", JUNIT_FIXED_TIME_FORMAT); return new SimpleDateFormat(JUNIT_FIXED_TIME_FORMAT); } return (SimpleDateFormat)DateFormat.getTimeInstance( getTimeStyle(), // dateStyle m_locale // timeStyle ); } // getTimeFormat /** * Get default MediaSize * * @return media size */ public MediaSize getMediaSize() { return _mediaSize; } // getMediaSize /** * String Representation * * @return string representation */ @Override public String toString() { return MoreObjects.toStringHelper(this) .omitNullValues() .add("name", m_name) .add("AD_Language", m_AD_Language) .add("locale", m_locale) .add("decimalPoint", isDecimalPoint()) .toString(); } @Override public int hashCode() { return m_AD_Language.hashCode(); } // hashcode @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj instanceof Language) { final Language other = (Language)obj; return Objects.equals(this.m_AD_Language, other.m_AD_Language); } return false; } // equals
private static int timeStyleDefault = DateFormat.MEDIUM; /** * Sets default time style to be used when getting DateTime format or Time format. * * @param timeStyle one of {@link DateFormat#SHORT}, {@link DateFormat#MEDIUM}, {@link DateFormat#LONG}. */ public static void setDefaultTimeStyle(final int timeStyle) { timeStyleDefault = timeStyle; } public static int getDefaultTimeStyle() { return timeStyleDefault; } public int getTimeStyle() { return getDefaultTimeStyle(); } private boolean matchesLangInfo(final String langInfo) { if (langInfo == null || langInfo.isEmpty()) { return false; } return langInfo.equals(getName()) || langInfo.equals(getAD_Language()) || langInfo.equals(getLanguageCode()); } } // Language
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\i18n\Language.java
1
请完成以下Java代码
public Date getStartedBefore() { return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; } public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; }
public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public List<String> getInvolvedGroups() { return involvedGroups; } public ProcessInstanceQuery 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\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setSerialNo (final @Nullable java.lang.String SerialNo) { throw new IllegalArgumentException ("SerialNo is virtual column"); } @Override public java.lang.String getSerialNo() { return get_ValueAsString(COLUMNNAME_SerialNo); } @Override public void setServiceContract (final @Nullable java.lang.String ServiceContract) { throw new IllegalArgumentException ("ServiceContract is virtual column"); } @Override public java.lang.String getServiceContract()
{ return get_ValueAsString(COLUMNNAME_ServiceContract); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() { return get_ValueAsString(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU.java
1
请完成以下Java代码
public class LwM2MJsonAdaptor implements LwM2MTransportAdaptor { @Override public TransportProtos.PostTelemetryMsg convertToPostTelemetry(JsonElement jsonElement) throws AdaptorException { try { return JsonConverter.convertToTelemetryProto(jsonElement); } catch (IllegalStateException | JsonSyntaxException ex) { throw new AdaptorException(ex); } } @Override public TransportProtos.PostAttributeMsg convertToPostAttributes(JsonElement jsonElement) throws AdaptorException { try { return JsonConverter.convertToAttributesProto(jsonElement); } catch (IllegalStateException | JsonSyntaxException ex) { throw new AdaptorException(ex); } }
@Override public TransportProtos.GetAttributeRequestMsg convertToGetAttributes(Collection<String> clientKeys, Collection<String> sharedKeys) throws AdaptorException { try { TransportProtos.GetAttributeRequestMsg.Builder result = TransportProtos.GetAttributeRequestMsg.newBuilder(); Random random = new Random(); result.setRequestId(random.nextInt()); if (clientKeys != null) { result.addAllClientAttributeNames(clientKeys); } if (sharedKeys != null) { result.addAllSharedAttributeNames(sharedKeys); } return result.build(); } catch (RuntimeException e) { throw new AdaptorException(e); } } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\adaptors\LwM2MJsonAdaptor.java
1
请完成以下Java代码
public void setC_Recurring_ID (int C_Recurring_ID) { if (C_Recurring_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Recurring_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Recurring_ID, Integer.valueOf(C_Recurring_ID)); } /** Get Recurring. @return Recurring Document */ public int getC_Recurring_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Recurring_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Recurring Run. @param C_Recurring_Run_ID Recurring Document Run */ public void setC_Recurring_Run_ID (int C_Recurring_Run_ID) { if (C_Recurring_Run_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Recurring_Run_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Recurring_Run_ID, Integer.valueOf(C_Recurring_Run_ID)); } /** Get Recurring Run. @return Recurring Document Run */ public int getC_Recurring_Run_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Recurring_Run_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Document Date.
@param DateDoc Date of the Document */ public void setDateDoc (Timestamp DateDoc) { set_Value (COLUMNNAME_DateDoc, DateDoc); } /** Get Document Date. @return Date of the Document */ public Timestamp getDateDoc () { return (Timestamp)get_Value(COLUMNNAME_DateDoc); } public I_GL_JournalBatch getGL_JournalBatch() throws RuntimeException { return (I_GL_JournalBatch)MTable.get(getCtx(), I_GL_JournalBatch.Table_Name) .getPO(getGL_JournalBatch_ID(), get_TrxName()); } /** Set Journal Batch. @param GL_JournalBatch_ID General Ledger Journal Batch */ public void setGL_JournalBatch_ID (int GL_JournalBatch_ID) { if (GL_JournalBatch_ID < 1) set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, null); else set_ValueNoCheck (COLUMNNAME_GL_JournalBatch_ID, Integer.valueOf(GL_JournalBatch_ID)); } /** Get Journal Batch. @return General Ledger Journal Batch */ public int getGL_JournalBatch_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_GL_JournalBatch_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Recurring_Run.java
1
请在Spring Boot框架中完成以下Java代码
public abstract class NaturalRepositoryImpl<T, NID extends Serializable> implements NaturalRepository<T, NID> { @PersistenceContext private EntityManager entityManager; private final Class<T> entityClass; public NaturalRepositoryImpl(Class<T> entityClass) { this.entityClass = entityClass; } @Override public Optional<T> findBySimpleNaturalId(NID naturalId) { Optional<T> entity = entityManager.unwrap(Session.class) .bySimpleNaturalId(entityClass)
.loadOptional(naturalId); return entity; } @Override public Optional<T> findByNaturalId(Map<String, Object> naturalIds) { NaturalIdLoadAccess<T> loadAccess = entityManager.unwrap(Session.class).byNaturalId(entityClass); naturalIds.forEach(loadAccess::using); return loadAccess.loadOptional(); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootNaturalId\src\main\java\com\bookstore\naturalid\NaturalRepositoryImpl.java
2
请完成以下Java代码
public class SysUser implements UserDetails { // implements UserDetails 用于登录时 @AuthenticationPrincipal 标签取值 private Integer id; private String username; @JsonIgnore private String password; private String rawPassword; @JsonIgnore private List<SysRole> roles; private List<? extends GrantedAuthority> authorities; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public List<SysRole> getRoles() { return roles; } public void setRoles(List<SysRole> roles) { this.roles = roles; } public String getRawPassword() { return rawPassword; } public void setRawPassword(String rawPassword) { this.rawPassword = rawPassword; } @JsonIgnore @Override public boolean isAccountNonExpired() { return true; } @JsonIgnore @Override
public boolean isAccountNonLocked() { return true; } @JsonIgnore @Override public boolean isCredentialsNonExpired() { return true; } @JsonIgnore @Override public boolean isEnabled() { return true; } @JsonIgnore @Override public Collection<? extends GrantedAuthority> getAuthorities() { return authorities; } public void setGrantedAuthorities(List<? extends GrantedAuthority> authorities) { this.authorities = authorities; } }
repos\springBoot-master\springboot-springSecurity2\src\main\java\com\us\example\domain\SysUser.java
1
请完成以下Java代码
public String getIssr() { return issr; } /** * Sets the value of the issr property. * * @param value * allowed object is * {@link String } * */ public void setIssr(String value) { this.issr = value; } /** * Gets the value of the schmeNm property. * * @return * possible object is * {@link String }
* */ public String getSchmeNm() { return schmeNm; } /** * Sets the value of the schmeNm property. * * @param value * allowed object is * {@link String } * */ public void setSchmeNm(String value) { this.schmeNm = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\GenericIdentification20.java
1
请完成以下Java代码
static MPrintFont create (Font font) { MPrintFont pf = new MPrintFont(Env.getCtx(), 0, ITrx.TRXNAME_None); StringBuilder name = new StringBuilder (font.getName()); if (font.isBold()) name.append(" bold"); if (font.isItalic()) name.append(" italic"); name.append(" ").append(font.getSize()); pf.setName(name.toString()); pf.setFont(font); pf.save(); return pf; } // create /** * String Representation * @return info */ @Override public String toString() { StringBuilder sb = new StringBuilder("MPrintFont["); sb.append("ID=").append(get_ID()) .append(",Name=").append(getName()) .append("PSName=").append(getFont().getPSName()) .append(getFont()) .append("]"); return sb.toString(); } // toString /** * Get PostScript Level 2 definition. * e.g. /dialog 12 selectfont * @return PostScript command */ public String toPS() { final StringBuilder sb = new StringBuilder("/"); sb.append(getFont().getPSName()); if (getFont().isBold()) sb.append(" Bold"); if (getFont().isItalic()) sb.append(" Italic"); sb.append(" ").append(getFont().getSize()) .append(" selectfont"); return sb.toString(); } // toPS
/** Cached Fonts */ private static final CCache<Integer,MPrintFont> s_fonts = new CCache<Integer,MPrintFont>(Table_Name, 20); /** * Get Font * @param AD_PrintFont_ID id * @return Font */ static public MPrintFont get (final int AD_PrintFont_ID) { final MPrintFont printFont = s_fonts.get(AD_PrintFont_ID, new Callable<MPrintFont>() { @Override public MPrintFont call() throws Exception { return new MPrintFont (Env.getCtx(), AD_PrintFont_ID, ITrx.TRXNAME_None); } }); return printFont; } // get } // MPrintFont
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\MPrintFont.java
1
请完成以下Java代码
public void setM_Shipper_ID (final int M_Shipper_ID) { if (M_Shipper_ID < 1) set_Value (COLUMNNAME_M_Shipper_ID, null); else set_Value (COLUMNNAME_M_Shipper_ID, M_Shipper_ID); } @Override public int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_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); } /** * PaymentRule AD_Reference_ID=195 * Reference name: _Payment Rule */ public static final int PAYMENTRULE_AD_Reference_ID=195; /** Cash = B */ public static final String PAYMENTRULE_Cash = "B"; /** CreditCard = K */ public static final String PAYMENTRULE_CreditCard = "K"; /** DirectDeposit = T */ public static final String PAYMENTRULE_DirectDeposit = "T";
/** Check = S */ public static final String PAYMENTRULE_Check = "S"; /** OnCredit = P */ public static final String PAYMENTRULE_OnCredit = "P"; /** DirectDebit = D */ public static final String PAYMENTRULE_DirectDebit = "D"; /** Mixed = M */ public static final String PAYMENTRULE_Mixed = "M"; /** PayPal = L */ public static final String PAYMENTRULE_PayPal = "L"; /** Rückerstattung = E */ public static final String PAYMENTRULE_Reimbursement = "E"; /** Verrechnung = F */ public static final String PAYMENTRULE_Settlement = "F"; @Override public void setPaymentRule (final java.lang.String PaymentRule) { set_Value (COLUMNNAME_PaymentRule, PaymentRule); } @Override public java.lang.String getPaymentRule() { return get_ValueAsString(COLUMNNAME_PaymentRule); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.salescandidate.base\src\main\java-gen\de\metas\ordercandidate\model\X_C_OLCandProcessor.java
1
请完成以下Spring Boot application配置
server.port = 8080 spring.thymeleaf.cache=false spring.datasource.name=springboot-site-datasource spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/db_news_system?useUnicode=true&serverTimezone=Asia/Shanghai&characterEncoding=utf8&autoReconnect=true&useSSL=false&allowMultiQueries=true spring.datasource.username=root spring.datasource.password= spring.datasource.hikari.minimum-idle=5 spring.datasource.hikari.maximum-pool-size=15 spring.datasource.hikari.auto-commit=true spring.datasource.hikari.idle-timeout=30000 spring
.datasource.hikari.pool-name=DatebookHikariCP spring.datasource.hikari.max-lifetime=1800000 spring.datasource.hikari.connection-timeout=30000 spring.datasource.hikari.connection-test-query=SELECT 1 mybatis.mapper-locations=classpath:mapper/*Mapper.xml
repos\spring-boot-projects-main\SpringBoot咨询发布系统实战项目源码\springboot-project-news-publish-system\src\main\resources\application.properties
2
请完成以下Java代码
public void setBase (String Base) { set_Value (COLUMNNAME_Base, Base); } /** Get Base. @return Calculation Base */ public String getBase () { return (String)get_Value(COLUMNNAME_Base); } /** Set Tax Base. @param C_TaxBase_ID Tax Base */ public void setC_TaxBase_ID (int C_TaxBase_ID) { if (C_TaxBase_ID < 1) set_ValueNoCheck (COLUMNNAME_C_TaxBase_ID, null); else set_ValueNoCheck (COLUMNNAME_C_TaxBase_ID, Integer.valueOf(C_TaxBase_ID)); } /** Get Tax Base. @return Tax Base */ public int getC_TaxBase_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_TaxBase_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ 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()); } /** Set Percentage. @param Percentage Percent of the entire amount */ public void setPercentage (int Percentage) { set_Value (COLUMNNAME_Percentage, Integer.valueOf(Percentage)); } /** Get Percentage. @return Percent of the entire amount */ public int getPercentage () { Integer ii = (Integer)get_Value(COLUMNNAME_Percentage); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ 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 */ 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_C_TaxBase.java
1
请完成以下Java代码
public class GetTaskVariablesCmd implements Command<Map<String, Object>>, Serializable { private static final long serialVersionUID = 1L; protected String taskId; protected Collection<String> variableNames; protected boolean isLocal; public GetTaskVariablesCmd(String taskId, Collection<String> variableNames, boolean isLocal) { this.taskId = taskId; this.variableNames = variableNames; this.isLocal = isLocal; } public Map<String, Object> execute(CommandContext commandContext) { if (taskId == null) { throw new ActivitiIllegalArgumentException("taskId is null"); } TaskEntity task = commandContext.getTaskEntityManager().findById(taskId); if (task == null) { throw new ActivitiObjectNotFoundException("task " + taskId + " doesn't exist", Task.class);
} if (variableNames == null) { if (isLocal) { return task.getVariablesLocal(); } else { return task.getVariables(); } } else { if (isLocal) { return task.getVariablesLocal(variableNames, false); } else { return task.getVariables(variableNames, false); } } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\cmd\GetTaskVariablesCmd.java
1
请完成以下Java代码
public Model newModel() { return commandExecutor.execute(new CreateModelCmd()); } public void saveModel(Model model) { commandExecutor.execute(new SaveModelCmd((ModelEntity) model)); } public void deleteModel(String modelId) { commandExecutor.execute(new DeleteModelCmd(modelId)); } public void addModelEditorSource(String modelId, byte[] bytes) { commandExecutor.execute(new AddEditorSourceForModelCmd(modelId, bytes)); } public void addModelEditorSourceExtra(String modelId, byte[] bytes) { commandExecutor.execute(new AddEditorSourceExtraForModelCmd(modelId, bytes)); } public ModelQuery createModelQuery() { return new ModelQueryImpl(commandExecutor); } @Override public NativeModelQuery createNativeModelQuery() { return new NativeModelQueryImpl(commandExecutor); } public Model getModel(String modelId) { return commandExecutor.execute(new GetModelCmd(modelId)); } public byte[] getModelEditorSource(String modelId) { return commandExecutor.execute(new GetModelEditorSourceCmd(modelId)); } public byte[] getModelEditorSourceExtra(String modelId) { return commandExecutor.execute(new GetModelEditorSourceExtraCmd(modelId));
} public void addCandidateStarterUser(String processDefinitionId, String userId) { commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null)); } public void addCandidateStarterGroup(String processDefinitionId, String groupId) { commandExecutor.execute(new AddIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId)); } public void deleteCandidateStarterGroup(String processDefinitionId, String groupId) { commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, null, groupId)); } public void deleteCandidateStarterUser(String processDefinitionId, String userId) { commandExecutor.execute(new DeleteIdentityLinkForProcessDefinitionCmd(processDefinitionId, userId, null)); } public List<IdentityLink> getIdentityLinksForProcessDefinition(String processDefinitionId) { return commandExecutor.execute(new GetIdentityLinksForProcessDefinitionCmd(processDefinitionId)); } public List<ValidationError> validateProcess(BpmnModel bpmnModel) { return commandExecutor.execute(new ValidateBpmnModelCmd(bpmnModel)); } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\RepositoryServiceImpl.java
1
请完成以下Java代码
public HistoricJobLogQuery orderByHostname() { return orderBy(HistoricJobLogQueryProperty.HOSTNAME); } // results ////////////////////////////////////////////////////////////// public long executeCount(CommandContext commandContext) { checkQueryOk(); return commandContext .getHistoricJobLogManager() .findHistoricJobLogsCountByQueryCriteria(this); } public List<HistoricJobLog> executeList(CommandContext commandContext, Page page) { checkQueryOk(); return commandContext .getHistoricJobLogManager() .findHistoricJobLogsByQueryCriteria(this, page); } // getter ////////////////////////////////// public boolean isTenantIdSet() { return isTenantIdSet; } public String getJobId() { return jobId; } public String getJobExceptionMessage() { return jobExceptionMessage; } public String getJobDefinitionId() { return jobDefinitionId; } public String getJobDefinitionType() { return jobDefinitionType; } public String getJobDefinitionConfiguration() { return jobDefinitionConfiguration; } public String[] getActivityIds() { return activityIds; } public String[] getFailedActivityIds() { return failedActivityIds; } public String[] getExecutionIds() { return executionIds; }
public String getProcessInstanceId() { return processInstanceId; } public String getProcessDefinitionId() { return processDefinitionId; } public String getProcessDefinitionKey() { return processDefinitionKey; } public String getDeploymentId() { return deploymentId; } public JobState getState() { return state; } public String[] getTenantIds() { return tenantIds; } public String getHostname() { return hostname; } // setter ////////////////////////////////// protected void setState(JobState state) { this.state = state; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\HistoricJobLogQueryImpl.java
1
请完成以下Java代码
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 registerInterceptors(@NonNull IModelValidationEngine engine) { engine.addModelValidator(new C_Order_ReceiptSchedule()); engine.addModelValidator(new M_ReceiptSchedule()); engine.addModelValidator(new M_ReceiptSchedule_Alloc()); engine.addModelValidator(new C_OrderLine_ReceiptSchedule()); } @Override protected void onAfterInit() { registerFactories(); // task 08452 Services.get(IReceiptScheduleBL.class).addReceiptScheduleListener(OrderLineReceiptScheduleListener.INSTANCE); } /** * Public for testing purposes only! */ public static void registerRSAggregationKeyDependencies() { final IAggregationKeyRegistry keyRegistry = Services.get(IAggregationKeyRegistry.class); final String registrationKey = ReceiptScheduleHeaderAggregationKeyBuilder.REGISTRATION_KEY; // // Register Handlers keyRegistry.registerAggregationKeyValueHandler(registrationKey, new ReceiptScheduleKeyValueHandler()); // // Register ReceiptScheduleHeaderAggregationKeyBuilder keyRegistry.registerDependsOnColumnnames(registrationKey, I_M_ReceiptSchedule.COLUMNNAME_C_DocType_ID, I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_ID, I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_C_BPartner_Location_ID,
I_M_ReceiptSchedule.COLUMNNAME_C_BP_Location_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_ID, I_M_ReceiptSchedule.COLUMNNAME_M_Warehouse_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_AD_User_ID, I_M_ReceiptSchedule.COLUMNNAME_AD_User_Override_ID, I_M_ReceiptSchedule.COLUMNNAME_AD_Org_ID, I_M_ReceiptSchedule.COLUMNNAME_DateOrdered, I_M_ReceiptSchedule.COLUMNNAME_C_Order_ID, I_M_ReceiptSchedule.COLUMNNAME_POReference); } public void registerFactories() { Services.get(IAttributeSetInstanceAwareFactoryService.class) .registerFactoryForTableName(I_M_ReceiptSchedule.Table_Name, new ReceiptScheduleASIAwareFactory()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\inoutcandidate\modelvalidator\ReceiptScheduleValidator.java
1
请完成以下Java代码
public class BpmnError extends ProcessEngineException { private static final long serialVersionUID = 1L; private String errorCode; private String errorMessage; public BpmnError(String errorCode) { super(exceptionMessage(errorCode, null)); setErrorCode(errorCode); } public BpmnError(String errorCode, String message) { super(exceptionMessage(errorCode, message)); setErrorCode(errorCode); setMessage(message); } public BpmnError(String errorCode, String message, Throwable cause) { super(exceptionMessage(errorCode, message), cause); setErrorCode(errorCode); setMessage(message); } public BpmnError(String errorCode, Throwable cause) { super(exceptionMessage(errorCode, null), cause); setErrorCode(errorCode); } private static String exceptionMessage(String errorCode, String message) { if (message == null) { return ""; } else { return message + " (errorCode='" + errorCode + "')"; } } protected void setErrorCode(String errorCode) { ensureNotEmpty("Error Code", errorCode); this.errorCode = errorCode; }
public String getErrorCode() { return errorCode; } @Override public String toString() { return super.toString() + " (errorCode='" + errorCode + "')"; } protected void setMessage(String errorMessage) { ensureNotEmpty("Error Message", errorMessage); this.errorMessage = errorMessage; } @Override public String getMessage() { return errorMessage; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\delegate\BpmnError.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_C_JobCategory[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Position Category. @param C_JobCategory_ID Job Position Category */ public void setC_JobCategory_ID (int C_JobCategory_ID) { if (C_JobCategory_ID < 1) set_ValueNoCheck (COLUMNNAME_C_JobCategory_ID, null); else set_ValueNoCheck (COLUMNNAME_C_JobCategory_ID, Integer.valueOf(C_JobCategory_ID)); } /** Get Position Category. @return Job Position Category */ public int getC_JobCategory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_JobCategory_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help.
@return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ 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()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_JobCategory.java
1
请完成以下Java代码
public ItemDefinition newInstance(ModelTypeInstanceContext instanceContext) { return new ItemDefinitionImpl(instanceContext); } }); structureRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_STRUCTURE_REF) .build(); isCollectionAttribute = typeBuilder.booleanAttribute(BPMN_ATTRIBUTE_IS_COLLECTION) .defaultValue(false) .build(); itemKindAttribute = typeBuilder.enumAttribute(BPMN_ATTRIBUTE_ITEM_KIND, ItemKind.class) .defaultValue(ItemKind.Information) .build(); typeBuilder.build(); } public ItemDefinitionImpl(ModelTypeInstanceContext context) { super(context); } public String getStructureRef() { return structureRefAttribute.getValue(this); } public void setStructureRef(String structureRef) { structureRefAttribute.setValue(this, structureRef); }
public boolean isCollection() { return isCollectionAttribute.getValue(this); } public void setCollection(boolean isCollection) { isCollectionAttribute.setValue(this, isCollection); } public ItemKind getItemKind() { return itemKindAttribute.getValue(this); } public void setItemKind(ItemKind itemKind) { itemKindAttribute.setValue(this, itemKind); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ItemDefinitionImpl.java
1
请完成以下Java代码
public abstract class AbstractDataAssociation implements Serializable { private static final long serialVersionUID = 1L; protected String source; protected Expression sourceExpression; protected String target; protected AbstractDataAssociation(String source, String target) { this.source = source; this.target = target; } protected AbstractDataAssociation(Expression sourceExpression, String target) { this.sourceExpression = sourceExpression;
this.target = target; } public abstract void evaluate(DelegateExecution execution); public String getSource() { return source; } public String getTarget() { return target; } public Expression getSourceExpression() { return sourceExpression; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\bpmn\data\AbstractDataAssociation.java
1
请完成以下Java代码
public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Release No. @param ReleaseNo Internal Release Number */ @Override public void setReleaseNo (java.lang.String ReleaseNo) { set_Value (COLUMNNAME_ReleaseNo, ReleaseNo); } /** Get Release No. @return Internal Release Number */ @Override public java.lang.String getReleaseNo () { return (java.lang.String)get_Value(COLUMNNAME_ReleaseNo); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** * StatusCode AD_Reference_ID=53311 * Reference name: AD_Migration Status */
public static final int STATUSCODE_AD_Reference_ID=53311; /** Applied = A */ public static final String STATUSCODE_Applied = "A"; /** Unapplied = U */ public static final String STATUSCODE_Unapplied = "U"; /** Failed = F */ public static final String STATUSCODE_Failed = "F"; /** Partially applied = P */ public static final String STATUSCODE_PartiallyApplied = "P"; /** Set Status Code. @param StatusCode Status Code */ @Override public void setStatusCode (java.lang.String StatusCode) { set_Value (COLUMNNAME_StatusCode, StatusCode); } /** Get Status Code. @return Status Code */ @Override public java.lang.String getStatusCode () { return (java.lang.String)get_Value(COLUMNNAME_StatusCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\adempiere\ad\migration\model\X_AD_Migration.java
1
请完成以下Java代码
public class PmsAlbum implements Serializable { private Long id; private String name; private String coverPic; private Integer picCount; private Integer sort; private String description; private static final long serialVersionUID = 1L; public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getCoverPic() { return coverPic; } public void setCoverPic(String coverPic) { this.coverPic = coverPic; } public Integer getPicCount() { return picCount; } public void setPicCount(Integer picCount) { this.picCount = picCount; } public Integer getSort() { return sort; }
public void setSort(Integer sort) { this.sort = sort; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", coverPic=").append(coverPic); sb.append(", picCount=").append(picCount); sb.append(", sort=").append(sort); sb.append(", description=").append(description); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsAlbum.java
1
请完成以下Java代码
public class TimerExecutedListenerDelegate implements ActivitiEventListener { private List<BPMNElementEventListener<BPMNTimerExecutedEvent>> processRuntimeEventListeners; private ToTimerExecutedConverter converter; public TimerExecutedListenerDelegate( List<BPMNElementEventListener<BPMNTimerExecutedEvent>> processRuntimeEventListeners, ToTimerExecutedConverter converter ) { this.processRuntimeEventListeners = processRuntimeEventListeners; this.converter = converter; } @Override
public void onEvent(ActivitiEvent event) { converter .from(event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNTimerExecutedEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\TimerExecutedListenerDelegate.java
1
请完成以下Java代码
public void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); HttpSession session = request.getSession(false); if (session != null) { String remoteAddr = getRemoteAddress(request); String geoLocation = getGeoLocation(remoteAddr); SessionDetails details = new SessionDetails(); details.setAccessType(request.getHeader("User-Agent")); details.setLocation(remoteAddr + " " + geoLocation); session.setAttribute("SESSION_DETAILS", details); } } // end::dofilterinternal[] String getGeoLocation(String remoteAddr) { try { CityResponse city = this.reader.city(InetAddress.getByName(remoteAddr)); String cityName = city.getCity().getName(); String countryName = city.getCountry().getName(); if (cityName == null && countryName == null) { return null; } else if (cityName == null) { return countryName; } else if (countryName == null) { return cityName; } return cityName + ", " + countryName;
} catch (Exception ex) { return UNKNOWN; } } private String getRemoteAddress(HttpServletRequest request) { String remoteAddr = request.getHeader("X-FORWARDED-FOR"); if (remoteAddr == null) { remoteAddr = request.getRemoteAddr(); } else if (remoteAddr.contains(",")) { remoteAddr = remoteAddr.split(",")[0]; } return remoteAddr; } } // end::class[]
repos\spring-session-main\spring-session-samples\spring-session-sample-boot-findbyusername\src\main\java\sample\session\SessionDetailsFilter.java
1
请在Spring Boot框架中完成以下Java代码
public ProjectId getProjectId() { return getId().getProjectId(); } public UomId getUomId() { return Quantity.getCommonUomIdOfAll(qtyRequired, qtyReserved, qtyConsumed); } public Quantity getQtyToReserve() { return getQtyRequired().subtract(getQtyReservedOrConsumed()).toZeroIfNegative(); } public Quantity getQtyReservedOrConsumed() { return getQtyReserved().add(getQtyConsumed()); } public ServiceRepairProjectTask reduce(@NonNull final AddQtyToProjectTaskRequest request) { if (!ProductId.equals(getProductId(), request.getProductId())) { return this; } return toBuilder() .qtyReserved(getQtyReserved().add(request.getQtyReserved())) .qtyConsumed(getQtyConsumed().add(request.getQtyConsumed())) .build() .withUpdatedStatus(); } public ServiceRepairProjectTask withUpdatedStatus() { final ServiceRepairProjectTaskStatus newStatus = computeStatus(); return !newStatus.equals(getStatus()) ? toBuilder().status(newStatus).build() : this; } private ServiceRepairProjectTaskStatus computeStatus() { final @NonNull ServiceRepairProjectTaskType type = getType(); switch (type) { case REPAIR_ORDER: return computeStatusForRepairOrderType(); case SPARE_PARTS: return computeStatusForSparePartsType(); default: throw new AdempiereException("Unknown type for " + this); } } private ServiceRepairProjectTaskStatus computeStatusForRepairOrderType() { if (getRepairOrderId() == null) { return ServiceRepairProjectTaskStatus.NOT_STARTED; } else { return isRepairOrderDone() ? ServiceRepairProjectTaskStatus.COMPLETED : ServiceRepairProjectTaskStatus.IN_PROGRESS; } } private ServiceRepairProjectTaskStatus computeStatusForSparePartsType()
{ if (getQtyToReserve().signum() <= 0) { return ServiceRepairProjectTaskStatus.COMPLETED; } else if (getQtyReservedOrConsumed().signum() == 0) { return ServiceRepairProjectTaskStatus.NOT_STARTED; } else { return ServiceRepairProjectTaskStatus.IN_PROGRESS; } } public ServiceRepairProjectTask withRepairOrderId(@NonNull final PPOrderId repairOrderId) { return toBuilder() .repairOrderId(repairOrderId) .build() .withUpdatedStatus(); } public ServiceRepairProjectTask withRepairOrderDone( @Nullable final String repairOrderSummary, @Nullable final ProductId repairServicePerformedId) { return toBuilder() .isRepairOrderDone(true) .repairOrderSummary(repairOrderSummary) .repairServicePerformedId(repairServicePerformedId) .build() .withUpdatedStatus(); } public ServiceRepairProjectTask withRepairOrderNotDone() { return toBuilder() .isRepairOrderDone(false) .repairOrderSummary(null) .repairServicePerformedId(null) .build() .withUpdatedStatus(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.servicerepair.base\src\main\java\de\metas\servicerepair\project\model\ServiceRepairProjectTask.java
2
请在Spring Boot框架中完成以下Java代码
protected ProxyProvider.Builder configureProxyProvider(HttpClientProperties.Proxy proxy, ProxyProvider.TypeSpec proxySpec) { ProxyProvider.Builder builder = proxySpec.type(proxy.getType()).host(proxy.getHost()); PropertyMapper map = PropertyMapper.get(); map.from(proxy::getPort).when(Objects::nonNull).to(builder::port); map.from(proxy::getUsername).whenHasText().to(builder::username); map.from(proxy::getPassword).whenHasText().to(password -> builder.password(s -> password)); map.from(proxy::getNonProxyHostsPattern).whenHasText().to(builder::nonProxyHosts); return builder; } protected HttpResponseDecoderSpec httpResponseDecoder(HttpResponseDecoderSpec spec) { if (properties.getMaxHeaderSize() != null) { // cast to int is ok, since @Max is Integer.MAX_VALUE spec.maxHeaderSize((int) properties.getMaxHeaderSize().toBytes()); } if (properties.getMaxInitialLineLength() != null) { // cast to int is ok, since @Max is Integer.MAX_VALUE spec.maxInitialLineLength((int) properties.getMaxInitialLineLength().toBytes()); } return spec; } protected ConnectionProvider buildConnectionProvider(HttpClientProperties properties) { HttpClientProperties.Pool pool = properties.getPool(); ConnectionProvider connectionProvider; if (pool.getType() == DISABLED) { connectionProvider = ConnectionProvider.newConnection(); } else { // create either Fixed or Elastic pool ConnectionProvider.Builder builder = ConnectionProvider.builder(pool.getName()); if (pool.getType() == FIXED) { builder.maxConnections(pool.getMaxConnections()) .pendingAcquireMaxCount(-1) .pendingAcquireTimeout(Duration.ofMillis(pool.getAcquireTimeout())); } else { // Elastic builder.maxConnections(Integer.MAX_VALUE) .pendingAcquireTimeout(Duration.ofMillis(0)) .pendingAcquireMaxCount(-1); } if (pool.getMaxIdleTime() != null) {
builder.maxIdleTime(pool.getMaxIdleTime()); } if (pool.getMaxLifeTime() != null) { builder.maxLifeTime(pool.getMaxLifeTime()); } builder.evictInBackground(pool.getEvictionInterval()); builder.metrics(pool.isMetrics()); // Define the pool leasing strategy if (pool.getLeasingStrategy() == FIFO) { builder.fifo(); } else { // LIFO builder.lifo(); } connectionProvider = builder.build(); } return connectionProvider; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\config\HttpClientFactory.java
2
请在Spring Boot框架中完成以下Java代码
private SmsCouponHistoryDetail getUseCoupon(List<CartPromotionItem> cartPromotionItemList, Long couponId) { List<SmsCouponHistoryDetail> couponHistoryDetailList = memberCouponService.listCart(cartPromotionItemList, 1); for (SmsCouponHistoryDetail couponHistoryDetail : couponHistoryDetailList) { if (couponHistoryDetail.getCoupon().getId().equals(couponId)) { return couponHistoryDetail; } } return null; } /** * 计算总金额 */ private BigDecimal calcTotalAmount(List<OmsOrderItem> orderItemList) { BigDecimal totalAmount = new BigDecimal("0"); for (OmsOrderItem item : orderItemList) { totalAmount = totalAmount.add(item.getProductPrice().multiply(new BigDecimal(item.getProductQuantity()))); } return totalAmount; } /** * 锁定下单商品的所有库存 */ private void lockStock(List<CartPromotionItem> cartPromotionItemList) { for (CartPromotionItem cartPromotionItem : cartPromotionItemList) { PmsSkuStock skuStock = skuStockMapper.selectByPrimaryKey(cartPromotionItem.getProductSkuId()); skuStock.setLockStock(skuStock.getLockStock() + cartPromotionItem.getQuantity()); int count = portalOrderDao.lockStockBySkuId(cartPromotionItem.getProductSkuId(),cartPromotionItem.getQuantity()); if(count==0){ Asserts.fail("库存不足,无法下单"); } } } /** * 判断下单商品是否都有库存 */ private boolean hasStock(List<CartPromotionItem> cartPromotionItemList) { for (CartPromotionItem cartPromotionItem : cartPromotionItemList) { if (cartPromotionItem.getRealStock()==null //判断真实库存是否为空 ||cartPromotionItem.getRealStock() <= 0 //判断真实库存是否小于0 || cartPromotionItem.getRealStock() < cartPromotionItem.getQuantity()) //判断真实库存是否小于下单的数量 { return false; } } return true;
} /** * 计算购物车中商品的价格 */ private ConfirmOrderResult.CalcAmount calcCartAmount(List<CartPromotionItem> cartPromotionItemList) { ConfirmOrderResult.CalcAmount calcAmount = new ConfirmOrderResult.CalcAmount(); calcAmount.setFreightAmount(new BigDecimal(0)); BigDecimal totalAmount = new BigDecimal("0"); BigDecimal promotionAmount = new BigDecimal("0"); for (CartPromotionItem cartPromotionItem : cartPromotionItemList) { totalAmount = totalAmount.add(cartPromotionItem.getPrice().multiply(new BigDecimal(cartPromotionItem.getQuantity()))); promotionAmount = promotionAmount.add(cartPromotionItem.getReduceAmount().multiply(new BigDecimal(cartPromotionItem.getQuantity()))); } calcAmount.setTotalAmount(totalAmount); calcAmount.setPromotionAmount(promotionAmount); calcAmount.setPayAmount(totalAmount.subtract(promotionAmount)); return calcAmount; } }
repos\mall-master\mall-portal\src\main\java\com\macro\mall\portal\service\impl\OmsPortalOrderServiceImpl.java
2
请完成以下Java代码
public <T> T getAttribute(String attributeName) { return (T) this.sessionAttrs.get(attributeName); } @Override public Set<String> getAttributeNames() { return new HashSet<>(this.sessionAttrs.keySet()); } @Override public void setAttribute(String attributeName, Object attributeValue) { if (attributeValue == null) { removeAttribute(attributeName); } else { this.sessionAttrs.put(attributeName, attributeValue); } } @Override public void removeAttribute(String attributeName) { this.sessionAttrs.remove(attributeName); } /** * Sets the time that this {@link Session} was created. The default is when the * {@link Session} was instantiated. * @param creationTime the time that this {@link Session} was created. */ public void setCreationTime(Instant creationTime) { this.creationTime = creationTime; } /** * Sets the identifier for this {@link Session}. The id should be a secure random * generated value to prevent malicious users from guessing this value. The default is * a secure random generated identifier. * @param id the identifier for this session. */ public void setId(String id) { this.id = id; } @Override public boolean equals(Object obj) { return obj instanceof Session && this.id.equals(((Session) obj).getId()); }
@Override public int hashCode() { return this.id.hashCode(); } private static String generateId() { return UUID.randomUUID().toString(); } /** * Sets the {@link SessionIdGenerator} to use when generating a new session id. * @param sessionIdGenerator the {@link SessionIdGenerator} to use. * @since 3.2 */ public void setSessionIdGenerator(SessionIdGenerator sessionIdGenerator) { this.sessionIdGenerator = sessionIdGenerator; } private static final long serialVersionUID = 7160779239673823561L; }
repos\spring-session-main\spring-session-core\src\main\java\org\springframework\session\MapSession.java
1
请在Spring Boot框架中完成以下Java代码
public void deleteHistoricTaskLogEntriesByTaskId(String taskId) { getDbSqlSession().delete("deleteHistoricTaskLogEntriesByTaskId", taskId, HistoricTaskLogEntryEntityImpl.class); } @Override public void bulkDeleteHistoricTaskLogEntriesForTaskIds(Collection<String> taskIds) { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForTaskIds", createSafeInValuesList(taskIds), HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesForNonExistingProcessInstances() { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForNonExistingProcessInstances", null, HistoricTaskLogEntryEntityImpl.class); } @Override public void deleteHistoricTaskLogEntriesForNonExistingCaseInstances() { getDbSqlSession().delete("bulkDeleteHistoricTaskLogEntriesForNonExistingCaseInstances", null, HistoricTaskLogEntryEntityImpl.class); }
@Override public long findHistoricTaskLogEntriesCountByNativeQueryCriteria(Map<String, Object> nativeHistoricTaskLogEntryQuery) { return (Long) getDbSqlSession().selectOne("selectHistoricTaskLogEntriesCountByNativeQueryCriteria", nativeHistoricTaskLogEntryQuery); } @Override public List<HistoricTaskLogEntry> findHistoricTaskLogEntriesByNativeQueryCriteria(Map<String, Object> nativeHistoricTaskLogEntryQuery) { return getDbSqlSession().selectListWithRawParameter("selectHistoricTaskLogEntriesByNativeQueryCriteria", nativeHistoricTaskLogEntryQuery); } @Override protected IdGenerator getIdGenerator() { return taskServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-task-service\src\main\java\org\flowable\task\service\impl\persistence\entity\data\impl\MyBatisHistoricTaskLogEntryDataManager.java
2
请在Spring Boot框架中完成以下Java代码
public void delete() { // 使用语句删除 Session session = sessionFactory.openSession(); Transaction transaction = session.beginTransaction(); session.query("match (n)-[r]-() delete n,r", Maps.newHashMap()); session.query("match (n)-[r]-() delete r", Maps.newHashMap()); session.query("match (n) delete n", Maps.newHashMap()); transaction.commit(); // 使用 repository 删除 studentRepo.deleteAll(); classRepo.deleteAll(); lessonRepo.deleteAll(); teacherRepo.deleteAll(); } /** * 根据学生姓名查询所选课程 * * @param studentName 学生姓名 * @param depth 深度 * @return 课程列表 */ public List<Lesson> findLessonsFromStudent(String studentName, int depth) { List<Lesson> lessons = Lists.newArrayList(); studentRepo.findByName(studentName, depth).ifPresent(student -> lessons.addAll(student.getLessons())); return lessons; } /** * 查询全校学生数 * * @return 学生总数 */ public Long studentCount(String className) { if (StrUtil.isBlank(className)) { return studentRepo.count(); } else { return studentRepo.countByClassName(className); } } /** * 查询同学关系,根据课程 * * @return 返回同学关系 */ public Map<String, List<Student>> findClassmatesGroupByLesson() { List<ClassmateInfoGroupByLesson> groupByLesson = studentRepo.findByClassmateGroupByLesson(); Map<String, List<Student>> result = Maps.newHashMap();
groupByLesson.forEach(classmateInfoGroupByLesson -> result.put(classmateInfoGroupByLesson.getLessonName(), classmateInfoGroupByLesson.getStudents())); return result; } /** * 查询所有师生关系,包括班主任/学生,任课老师/学生 * * @return 师生关系 */ public Map<String, Set<Student>> findTeacherStudent() { List<TeacherStudent> teacherStudentByClass = studentRepo.findTeacherStudentByClass(); List<TeacherStudent> teacherStudentByLesson = studentRepo.findTeacherStudentByLesson(); Map<String, Set<Student>> result = Maps.newHashMap(); teacherStudentByClass.forEach(teacherStudent -> result.put(teacherStudent.getTeacherName(), Sets.newHashSet(teacherStudent.getStudents()))); teacherStudentByLesson.forEach(teacherStudent -> result.put(teacherStudent.getTeacherName(), Sets.newHashSet(teacherStudent.getStudents()))); return result; } }
repos\spring-boot-demo-master\demo-neo4j\src\main\java\com\xkcoding\neo4j\service\NeoService.java
2
请完成以下Java代码
public PaymentInstructionInformationSDD createPaymentInstructionInformationSDD() { return new PaymentInstructionInformationSDD(); } /** * Create an instance of {@link PaymentTypeInformationSDD } * */ public PaymentTypeInformationSDD createPaymentTypeInformationSDD() { return new PaymentTypeInformationSDD(); } /** * Create an instance of {@link PersonIdentificationSEPA1Choice } * */ public PersonIdentificationSEPA1Choice createPersonIdentificationSEPA1Choice() { return new PersonIdentificationSEPA1Choice(); } /** * Create an instance of {@link PersonIdentificationSEPA2 } * */ public PersonIdentificationSEPA2 createPersonIdentificationSEPA2() { return new PersonIdentificationSEPA2(); } /** * Create an instance of {@link PersonIdentificationSchemeName1Choice } * */ public PersonIdentificationSchemeName1Choice createPersonIdentificationSchemeName1Choice() { return new PersonIdentificationSchemeName1Choice(); } /** * Create an instance of {@link RestrictedPersonIdentificationSchemeNameSEPA } * */ public RestrictedPersonIdentificationSchemeNameSEPA createRestrictedPersonIdentificationSchemeNameSEPA() { return new RestrictedPersonIdentificationSchemeNameSEPA(); } /** * Create an instance of {@link PostalAddressSEPA } * */ public PostalAddressSEPA createPostalAddressSEPA() { return new PostalAddressSEPA(); } /** * Create an instance of {@link PurposeSEPA } * */ public PurposeSEPA createPurposeSEPA() { return new PurposeSEPA();
} /** * Create an instance of {@link RemittanceInformationSEPA1Choice } * */ public RemittanceInformationSEPA1Choice createRemittanceInformationSEPA1Choice() { return new RemittanceInformationSEPA1Choice(); } /** * Create an instance of {@link ServiceLevelSEPA } * */ public ServiceLevelSEPA createServiceLevelSEPA() { return new ServiceLevelSEPA(); } /** * Create an instance of {@link StructuredRemittanceInformationSEPA1 } * */ public StructuredRemittanceInformationSEPA1 createStructuredRemittanceInformationSEPA1() { return new StructuredRemittanceInformationSEPA1(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link Document }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link Document }{@code >} */ @XmlElementDecl(namespace = "urn:iso:std:iso:20022:tech:xsd:pain.008.003.02", name = "Document") public JAXBElement<Document> createDocument(Document value) { return new JAXBElement<Document>(_Document_QNAME, Document.class, null, value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\ObjectFactory.java
1
请完成以下Java代码
public BigDecimal getContinmeFee() { return continmeFee; } public void setContinmeFee(BigDecimal continmeFee) { this.continmeFee = continmeFee; } public String getDest() { return dest; } public void setDest(String dest) { this.dest = dest; } @Override public String toString() { StringBuilder sb = new StringBuilder();
sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", name=").append(name); sb.append(", chargeType=").append(chargeType); sb.append(", firstWeight=").append(firstWeight); sb.append(", firstFee=").append(firstFee); sb.append(", continueWeight=").append(continueWeight); sb.append(", continmeFee=").append(continmeFee); sb.append(", dest=").append(dest); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\PmsFeightTemplate.java
1
请完成以下Java代码
final class BPartnerImportContext { @Getter private final BPartnersCache bpartnersCache; @Getter private final boolean insertOnly; @Getter @Setter private I_I_BPartner currentImportRecord; @Builder private BPartnerImportContext( @NonNull final BPartnersCache bpartnersCache, final boolean insertOnly) { this.bpartnersCache = bpartnersCache; this.insertOnly = insertOnly; } public boolean isSameBPartner(final I_I_BPartner importRecord) { final I_I_BPartner currentImportRecord = getCurrentImportRecord(); return currentImportRecord != null && Objects.equals(importRecord.getBPValue(), currentImportRecord.getBPValue()) && Objects.equals(importRecord.getGlobalId(), currentImportRecord.getGlobalId()); } public boolean isCurrentBPartnerIdSet() { return getCurrentBPartnerIdOrNull() != null; } public BPartner getCurrentBPartner() { final BPartnerId bpartnerId = getCurrentBPartnerIdOrNull(); return getBpartnersCache().getBPartnerById(bpartnerId); } public BPartnerId getCurrentBPartnerIdOrNull() { final I_I_BPartner currentImportRecord = getCurrentImportRecord(); return currentImportRecord != null ? BPartnerId.ofRepoIdOrNull(currentImportRecord.getC_BPartner_ID()) : null; } public void setCurrentBPartnerId(@NonNull final BPartnerId bpartnerId) { final I_I_BPartner currentImportRecord = getCurrentImportRecord(); Check.assumeNotNull(currentImportRecord, "Parameter currentImportRecord is not null"); currentImportRecord.setC_BPartner_ID(bpartnerId.getRepoId()); } public BPartnerLocationId getCurrentBPartnerLocationIdOrNull() { final I_I_BPartner currentImportRecord = getCurrentImportRecord(); return currentImportRecord != null ? BPartnerLocationId.ofRepoIdOrNull(currentImportRecord.getC_BPartner_ID(), currentImportRecord.getC_BPartner_Location_ID()) : null;
} public void setCurrentBPartnerLocationId(@NonNull final BPartnerLocationId bpLocationId) { final I_I_BPartner currentImportRecord = getCurrentImportRecord(); Check.assumeNotNull(currentImportRecord, "Parameter currentImportRecord is not null"); currentImportRecord.setC_BPartner_Location_ID(bpLocationId.getRepoId()); } public BPartnerContactId getCurrentBPartnerContactIdOrNull() { final I_I_BPartner currentImportRecord = getCurrentImportRecord(); return currentImportRecord != null ? BPartnerContactId.ofRepoIdOrNull(currentImportRecord.getC_BPartner_ID(), currentImportRecord.getAD_User_ID()) : null; } public void setCurrentBPartnerContactId(@NonNull final BPartnerContactId bpContactId) { final I_I_BPartner currentImportRecord = getCurrentImportRecord(); Check.assumeNotNull(currentImportRecord, "Parameter currentImportRecord is not null"); currentImportRecord.setAD_User_ID(bpContactId.getRepoId()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\bpartner\impexp\BPartnerImportContext.java
1
请完成以下Java代码
public void setStartDate (Timestamp StartDate) { set_Value (COLUMNNAME_StartDate, StartDate); } /** Get Start Date. @return First effective day (inclusive) */ public Timestamp getStartDate () { return (Timestamp)get_Value(COLUMNNAME_StartDate); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getStartDate())); } /** Set Training Class. @param S_Training_Class_ID The actual training class instance */ public void setS_Training_Class_ID (int S_Training_Class_ID) { if (S_Training_Class_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Training_Class_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Training_Class_ID, Integer.valueOf(S_Training_Class_ID)); } /** Get Training Class. @return The actual training class instance */ public int getS_Training_Class_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_Class_ID); if (ii == null) return 0; return ii.intValue(); } public I_S_Training getS_Training() throws RuntimeException { return (I_S_Training)MTable.get(getCtx(), I_S_Training.Table_Name) .getPO(getS_Training_ID(), get_TrxName()); }
/** Set Training. @param S_Training_ID Repeated Training */ public void setS_Training_ID (int S_Training_ID) { if (S_Training_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Training_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Training_ID, Integer.valueOf(S_Training_ID)); } /** Get Training. @return Repeated Training */ public int getS_Training_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Training_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_Training_Class.java
1
请完成以下Java代码
public void updateFromDocType(final I_M_Inventory inventoryRecord, final ICalloutField field) { final IDocumentNoInfo documentNoInfo = Services.get(IDocumentNoBuilderFactory.class) .createPreliminaryDocumentNoBuilder() .setNewDocType(getDocTypeOrNull(inventoryRecord)) .setOldDocumentNo(inventoryRecord.getDocumentNo()) .setDocumentModel(inventoryRecord) .buildOrNull(); if (documentNoInfo == null) { return; } if (InventoryDocSubType.VirtualInventory.getCode().equals(documentNoInfo.getDocSubType())) { throw new AdempiereException(MSG_WEBUI_ADD_VIRTUAL_INV_NOT_ALLOWED);
} // DocumentNo if (documentNoInfo.isDocNoControlled()) { inventoryRecord.setDocumentNo(documentNoInfo.getDocumentNo()); } } private I_C_DocType getDocTypeOrNull(final I_M_Inventory inventoryRecord) { final DocTypeId docTypeId = DocTypeId.ofRepoIdOrNull(inventoryRecord.getC_DocType_ID()); return docTypeId != null ? Services.get(IDocTypeDAO.class).getById(docTypeId) : null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\callout\M_Inventory.java
1