instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void recycle() { // clean out the object state operationType = null; entityType = null; } // getters / setters ////////////////////////////////////////// public Class<? extends DbEntity> getEntityType() { return entityType; } public void setEntityType(Class<? extends DbEntity> entityType) { this.entityType = entityType; } public DbOperationType getOperationType() { return operationType; } public void setOperationType(DbOperationType operationType) { this.operationType = operationType; } public int getRowsAffected() { return rowsAffected; } public void setRowsAffected(int rowsAffected) { this.rowsAffected = rowsAffected; } public boolean isFailed() { return state == State.FAILED_CONCURRENT_MODIFICATION || state == State.FAILED_CONCURRENT_MODIFICATION_EXCEPTION || state == State.FAILED_ERROR; } public State getState() { return state; } public void setState(State state) { this.state = state; } public Exception getFailure() { return failure; } public void setFailure(Exception failure) {
this.failure = failure; } public enum State { NOT_APPLIED, APPLIED, /** * Indicates that the operation was not performed for any reason except * concurrent modifications. */ FAILED_ERROR, /** * Indicates that the operation was not performed and that the reason * was a concurrent modification to the data to be updated. * Applies to databases with isolation level READ_COMMITTED. */ FAILED_CONCURRENT_MODIFICATION, /** * Indicates that the operation was not performed and was a concurrency * conflict with a SQL exception. Applies to PostgreSQL. */ FAILED_CONCURRENT_MODIFICATION_EXCEPTION } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\db\entitymanager\operation\DbOperation.java
1
请完成以下Java代码
public int getM_CostQueue_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CostQueue_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_CostType getM_CostType() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class); } @Override public void setM_CostType(org.compiere.model.I_M_CostType M_CostType) { set_ValueFromPO(COLUMNNAME_M_CostType_ID, org.compiere.model.I_M_CostType.class, M_CostType); } /** Set Kostenkategorie. @param M_CostType_ID Type of Cost (e.g. Current, Plan, Future) */ @Override public void setM_CostType_ID (int M_CostType_ID) { if (M_CostType_ID < 1) set_ValueNoCheck (COLUMNNAME_M_CostType_ID, null); else set_ValueNoCheck (COLUMNNAME_M_CostType_ID, Integer.valueOf(M_CostType_ID)); } /** Get Kostenkategorie. @return Type of Cost (e.g. Current, Plan, Future) */ @Override public int getM_CostType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_CostType_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product);
} /** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_CostQueue.java
1
请完成以下Java代码
public class LastModifiedFileApp { public static File findUsingIOApi(String sdir) { File dir = new File(sdir); if (dir.isDirectory()) { Optional<File> opFile = Arrays.stream(dir.listFiles(File::isFile)) .max((f1, f2) -> Long.compare(f1.lastModified(), f2.lastModified())); if (opFile.isPresent()) { return opFile.get(); } } return null; } public static Path findUsingNIOApi(String sdir) throws IOException { Path dir = Paths.get(sdir); if (Files.isDirectory(dir)) { Optional<Path> opPath = Files.list(dir) .filter(p -> !Files.isDirectory(p)) .sorted((p1, p2) -> Long.valueOf(p2.toFile().lastModified()) .compareTo(p1.toFile().lastModified())) .findFirst(); if (opPath.isPresent()) { return opPath.get(); } } return null;
} public static File findUsingCommonsIO(String sdir) { File dir = new File(sdir); if (dir.isDirectory()) { File[] dirFiles = dir.listFiles((FileFilter) FileFilterUtils.fileFileFilter()); if (dirFiles != null && dirFiles.length > 0) { Arrays.sort(dirFiles, LastModifiedFileComparator.LASTMODIFIED_REVERSE); return dirFiles[0]; } } return null; } }
repos\tutorials-master\core-java-modules\core-java-io-3\src\main\java\com\baeldung\lastmodifiedfile\LastModifiedFileApp.java
1
请完成以下Java代码
private Set<InventoryId> getSelectedInventoryIds() { return retrieveSelectedRecordsQueryBuilder(I_M_Inventory.class) .create() .listIds() .stream() .map(InventoryId::ofRepoId) .collect(ImmutableSet.toImmutableSet()); } private void recomputeCosts( @NonNull final CostElement costElement, @NonNull final PInstanceId productsSelectionId, @NonNull final Instant startDate) { DB.executeFunctionCallEx(getTrxName() , "select \"de_metas_acct\".product_costs_recreate_from_date( p_C_AcctSchema_ID :=" + getAccountingSchemaId().getRepoId() + ", p_M_CostElement_ID:=" + costElement.getId().getRepoId() + ", p_m_product_selection_id:=" + productsSelectionId.getRepoId() + " , p_ReorderDocs_DateAcct_Trunc:='MM'" + ", p_StartDateAcct:=" + DB.TO_SQL(startDate) + "::date)" // , null // ); }
private Instant getStartDate() { return inventoryDAO.getMinInventoryDate(getSelectedInventoryIds()) .orElseThrow(() -> new AdempiereException("Cannot determine Start Date")); } private List<CostElement> getCostElements() { if (p_costingMethod != null) { return costElementRepository.getMaterialCostingElementsForCostingMethod(p_costingMethod); } return costElementRepository.getActiveMaterialCostingElements(getClientID()); } private AcctSchemaId getAccountingSchemaId() {return p_C_AcctSchema_ID;} }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\inventory\process\M_Inventory_RecomputeCosts.java
1
请完成以下Java代码
public static List<ClusterGroupEntity> wrapToClusterGroup(List<ClusterUniversalStatePairVO> list) { if (list == null || list.isEmpty()) { return new ArrayList<>(); } Map<String, ClusterGroupEntity> map = new HashMap<>(); for (ClusterUniversalStatePairVO stateVO : list) { int mode = stateVO.getState().getStateInfo().getMode(); String ip = stateVO.getIp(); if (mode == ClusterStateManager.CLUSTER_SERVER) { String serverAddress = getIp(ip); int port = stateVO.getState().getServer().getPort(); map.computeIfAbsent(serverAddress, v -> new ClusterGroupEntity() .setBelongToApp(true).setMachineId(ip + '@' + stateVO.getCommandPort()) .setIp(ip).setPort(port) ); } } for (ClusterUniversalStatePairVO stateVO : list) { int mode = stateVO.getState().getStateInfo().getMode(); String ip = stateVO.getIp(); if (mode == ClusterStateManager.CLUSTER_CLIENT) { String targetServer = stateVO.getState().getClient().getClientConfig().getServerHost(); Integer targetPort = stateVO.getState().getClient().getClientConfig().getServerPort(); if (StringUtil.isBlank(targetServer) || targetPort == null || targetPort <= 0) { continue; }
ClusterGroupEntity group = map.computeIfAbsent(targetServer, v -> new ClusterGroupEntity() .setBelongToApp(true).setMachineId(targetServer) .setIp(targetServer).setPort(targetPort) ); group.getClientSet().add(ip + '@' + stateVO.getCommandPort()); } } return new ArrayList<>(map.values()); } private static String getIp(String str) { if (str.contains(":")) { return str.split(":")[0]; } return str; } private ClusterEntityUtils() {} }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\util\ClusterEntityUtils.java
1
请完成以下Java代码
public static List<String> translateBatch(List<String> texts, String targetLanguage) { List<String> translationList = null; try { List<Translation> translations = translate.translate(texts, Translate.TranslateOption.targetLanguage(targetLanguage)); translationList = translations.stream() .map(Translation::getTranslatedText) .collect(Collectors.toList()); } catch (Exception e) { // handle exception } return translationList; } public static String translateWithGlossary(String projectId, String location, String text, String targetLanguage, String glossaryId) { String translatedText = ""; try (TranslationServiceClient client = TranslationServiceClient.create()) { LocationName parent = LocationName.of(projectId, location); GlossaryName glossaryName = GlossaryName.of(projectId, location, glossaryId); TranslateTextRequest request = TranslateTextRequest.newBuilder()
.setParent(parent.toString()) .setTargetLanguageCode(targetLanguage) .addContents(text) .setGlossaryConfig(TranslateTextGlossaryConfig.newBuilder() .setGlossary(glossaryName.toString()).build()) // Attach glossary .build(); TranslateTextResponse response = client.translateText(request); translatedText = response.getTranslations(0).getTranslatedText(); } catch (IOException e) { // handle exception } return translatedText; } }
repos\tutorials-master\google-cloud\src\main\java\com\baeldung\google\cloud\translator\Translator.java
1
请在Spring Boot框架中完成以下Java代码
public String getProductDesc() { return productDesc; } public void setProductDesc(String productDesc) { this.productDesc = productDesc; } public String getRate() { return rate; } public void setRate(String rate) { this.rate = rate; } public String getContactPhone() { return contactPhone; } public void setContactPhone(String contactPhone) { this.contactPhone = contactPhone; } @Override public String toString() { return "RpMicroSubmitRecord{" + "businessCode='" + businessCode + '\'' +
", subMchId='" + subMchId + '\'' + ", idCardCopy='" + idCardCopy + '\'' + ", idCardNational='" + idCardNational + '\'' + ", idCardName='" + idCardName + '\'' + ", idCardNumber='" + idCardNumber + '\'' + ", idCardValidTime='" + idCardValidTime + '\'' + ", accountBank='" + accountBank + '\'' + ", bankAddressCode='" + bankAddressCode + '\'' + ", accountNumber='" + accountNumber + '\'' + ", storeName='" + storeName + '\'' + ", storeAddressCode='" + storeAddressCode + '\'' + ", storeStreet='" + storeStreet + '\'' + ", storeEntrancePic='" + storeEntrancePic + '\'' + ", indoorPic='" + indoorPic + '\'' + ", merchantShortname='" + merchantShortname + '\'' + ", servicePhone='" + servicePhone + '\'' + ", productDesc='" + productDesc + '\'' + ", rate='" + rate + '\'' + ", contactPhone='" + contactPhone + '\'' + ", idCardValidTimeBegin='" + idCardValidTimeBegin + '\'' + ", idCardValidTimeEnd='" + idCardValidTimeEnd + '\'' + '}'; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\entity\RpMicroSubmitRecord.java
2
请完成以下Java代码
public long getTimeSinceLastPoll() { return this.timeSinceLastPoll; } /** * The TopicPartitions the container is listening to. * @return the TopicPartition list. */ public @Nullable Collection<TopicPartition> getTopicPartitions() { return this.topicPartitions == null ? null : Collections.unmodifiableList(this.topicPartitions); } /** * The id of the listener (if {@code @KafkaListener}) or the container bean name. * @return the id. */ public String getListenerId() { return this.listenerId; }
/** * Retrieve the consumer. Only populated if the listener is consumer-aware. * Allows the listener to resume a paused consumer. * @return the consumer. */ public Consumer<?, ?> getConsumer() { return this.consumer; } @Override public String toString() { return "NonResponsiveConsumerEvent [timeSinceLastPoll=" + ((float) this.timeSinceLastPoll / 1000) + "s, listenerId=" + this.listenerId // NOSONAR magic # + ", container=" + getSource() + ", topicPartitions=" + this.topicPartitions + "]"; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\event\NonResponsiveConsumerEvent.java
1
请完成以下Java代码
public void onParameterChanged(final String parameterName) { if (PARAM_CostTypeId.equals(parameterName)) { final OrderCostType costType = p_costTypeId != null ? orderCostService.getCostTypeById(p_costTypeId) : null; p_CostCalculationMethod = costType != null ? costType.getCalculationMethod() : null; p_IsAllowInvoicing = isSOTrx() && costType != null && costType.isAllowInvoicing(); p_InvoiceableProductId = costType != null ? costType.getInvoiceableProductId() : null; } } @Override protected String doIt() { orderCostService.createOrderCost(orderCostCreateRequest()); return MSG_OK; } private OrderCostCreateRequest orderCostCreateRequest() { final OrderCostCreateRequest.OrderLine orderLine; if (p_IsInvoiced) { if (p_InvoiceableProductId == null) { throw new FillMandatoryException("M_Product_ID"); } orderLine = OrderCostCreateRequest.OrderLine.builder() .productId(p_InvoiceableProductId) .build(); } else { orderLine = null; } return OrderCostCreateRequest.builder() .bpartnerId(p_bpartnerId) .costTypeId(p_costTypeId) .orderAndLineIds(getSelectedOrderAndLineIds()) .costCalculationMethodParams(getCostCalculationMethodParams()) .addOrderLine(orderLine) .build(); } private CostCalculationMethodParams getCostCalculationMethodParams() { if (CostCalculationMethod.FixedAmount.equals(p_CostCalculationMethod)) { if (p_amountBD == null || p_amountBD.signum() <= 0) { throw new FillMandatoryException(PARAM_Amount); } return FixedAmountCostCalculationMethodParams.builder() .fixedAmount(Money.of(p_amountBD, getOrderCurrencyId())) .build(); } else if (CostCalculationMethod.PercentageOfAmount.equals(p_CostCalculationMethod)) { if (p_percentageBD == null || p_percentageBD.signum() <= 0) { throw new FillMandatoryException(PARAM_Percentage); } return PercentageCostCalculationMethodParams.builder() .percentage(Percent.of(p_percentageBD)) .build(); } else { throw new AdempiereException("Method not handled: " + p_CostCalculationMethod); }
} private ImmutableSet<OrderAndLineId> getSelectedOrderAndLineIds() { final OrderId orderId = getOrderId(); return getSelectedIncludedRecordIds(I_C_OrderLine.class) .stream() .map(orderLineRepoId -> OrderAndLineId.ofRepoIds(orderId, orderLineRepoId)) .collect(ImmutableSet.toImmutableSet()); } @NonNull private OrderId getOrderId() { return OrderId.ofRepoId(getRecord_ID()); } private I_C_Order getOrder(final OrderId orderId) { return orderCache.computeIfAbsent(orderId, orderBL::getById); } private CurrencyId getOrderCurrencyId() { return CurrencyId.ofRepoId(getOrder(getOrderId()).getC_Currency_ID()); } public boolean isSOTrx() { return getOrder(getOrderId()).isSOTrx(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\costs\C_Order_CreateCost.java
1
请在Spring Boot框架中完成以下Java代码
public int create(SmsHomeAdvertise advertise) { advertise.setClickCount(0); advertise.setOrderCount(0); return advertiseMapper.insert(advertise); } @Override public int delete(List<Long> ids) { SmsHomeAdvertiseExample example = new SmsHomeAdvertiseExample(); example.createCriteria().andIdIn(ids); return advertiseMapper.deleteByExample(example); } @Override public int updateStatus(Long id, Integer status) { SmsHomeAdvertise record = new SmsHomeAdvertise(); record.setId(id); record.setStatus(status); return advertiseMapper.updateByPrimaryKeySelective(record); } @Override public SmsHomeAdvertise getItem(Long id) { return advertiseMapper.selectByPrimaryKey(id); } @Override public int update(Long id, SmsHomeAdvertise advertise) { advertise.setId(id); return advertiseMapper.updateByPrimaryKeySelective(advertise); } @Override
public List<SmsHomeAdvertise> list(String name, Integer type, String endTime, Integer pageSize, Integer pageNum) { PageHelper.startPage(pageNum, pageSize); SmsHomeAdvertiseExample example = new SmsHomeAdvertiseExample(); SmsHomeAdvertiseExample.Criteria criteria = example.createCriteria(); if (!StrUtil.isEmpty(name)) { criteria.andNameLike("%" + name + "%"); } if (type != null) { criteria.andTypeEqualTo(type); } if (!StrUtil.isEmpty(endTime)) { String startStr = endTime + " 00:00:00"; String endStr = endTime + " 23:59:59"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); Date start = null; try { start = sdf.parse(startStr); } catch (ParseException e) { e.printStackTrace(); } Date end = null; try { end = sdf.parse(endStr); } catch (ParseException e) { e.printStackTrace(); } if (start != null && end != null) { criteria.andEndTimeBetween(start, end); } } example.setOrderByClause("sort desc"); return advertiseMapper.selectByExample(example); } }
repos\mall-master\mall-admin\src\main\java\com\macro\mall\service\impl\SmsHomeAdvertiseServiceImpl.java
2
请完成以下Java代码
List<UserProfile> getUserProfiles(){ return userProfileDataAccessService.getUserProfile(); } @Async void uploadUserProfileImage(String userProfileId, MultipartFile multipartFile) throws Exception { final File file = convertMultiPartFileToFile(multipartFile); String extension = FilenameUtils.getExtension(multipartFile.getOriginalFilename()); uploadFileToS3Bucket(bucketName, file, extension); file.delete(); } private void uploadFileToS3Bucket(final String bucketName, final File file, String filename) { final PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, filename, file);
amazonS3Client.putObject(putObjectRequest); } private File convertMultiPartFileToFile(final MultipartFile multipartFile) throws Exception{ final File file = new File(multipartFile.getOriginalFilename()); try (final FileOutputStream outputStream = new FileOutputStream(file)) { outputStream.write(multipartFile.getBytes()); } catch (final IOException ex) { } return file; } }
repos\Spring-Boot-Advanced-Projects-main\Project-4.SpringBoot-AWS-S3\backend\src\main\java\com\urunov\profile\UserProfileService.java
1
请在Spring Boot框架中完成以下Java代码
public Resource getLocation() { return this.location; } public void setLocation(Resource location) { this.location = location; } public Charset getEncoding() { return this.encoding; } public void setEncoding(Charset encoding) { this.encoding = encoding; } } /** * Git specific info properties. */ public static class Git { /** * Location of the generated git.properties file. */ private Resource location = new ClassPathResource("git.properties"); /** * File encoding. */ private Charset encoding = StandardCharsets.UTF_8;
public Resource getLocation() { return this.location; } public void setLocation(Resource location) { this.location = location; } public Charset getEncoding() { return this.encoding; } public void setEncoding(Charset encoding) { this.encoding = encoding; } } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\info\ProjectInfoProperties.java
2
请完成以下Java代码
protected static class SimplePatternBasedHeaderMatcher implements HeaderMatcher { private static final LogAccessor LOGGER = new LogAccessor(LogFactory.getLog(SimplePatternBasedHeaderMatcher.class)); private final String pattern; private final boolean negate; protected SimplePatternBasedHeaderMatcher(String pattern) { this(pattern.startsWith("!") ? pattern.substring(1) : pattern, pattern.startsWith("!")); } SimplePatternBasedHeaderMatcher(String pattern, boolean negate) { Assert.notNull(pattern, "Pattern must no be null"); this.pattern = pattern.toLowerCase(Locale.ROOT); this.negate = negate; } @Override
public boolean matchHeader(String headerName) { String header = headerName.toLowerCase(Locale.ROOT); if (PatternMatchUtils.simpleMatch(this.pattern, header)) { LOGGER.debug(() -> MessageFormat.format( "headerName=[{0}] WILL " + (this.negate ? "NOT " : "") + "be mapped, matched pattern=" + (this.negate ? "!" : "") + "{1}", headerName, this.pattern)); return true; } return false; } @Override public boolean isNegated() { return this.negate; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\AbstractKafkaHeaderMapper.java
1
请完成以下Java代码
public void setAD_SchedulerRecipient_ID (int AD_SchedulerRecipient_ID) { if (AD_SchedulerRecipient_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_SchedulerRecipient_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_SchedulerRecipient_ID, Integer.valueOf(AD_SchedulerRecipient_ID)); } /** Get Empfänger. @return Recipient of the Scheduler Notification */ @Override public int getAD_SchedulerRecipient_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_SchedulerRecipient_ID); if (ii == null) return 0; return ii.intValue(); } @Override public org.compiere.model.I_AD_User getAD_User() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class); } @Override public void setAD_User(org.compiere.model.I_AD_User AD_User) { set_ValueFromPO(COLUMNNAME_AD_User_ID, org.compiere.model.I_AD_User.class, AD_User); } /** Set Ansprechpartner. @param AD_User_ID User within the system - Internal or Business Partner Contact */ @Override
public void setAD_User_ID (int AD_User_ID) { if (AD_User_ID < 0) set_Value (COLUMNNAME_AD_User_ID, null); else set_Value (COLUMNNAME_AD_User_ID, Integer.valueOf(AD_User_ID)); } /** Get Ansprechpartner. @return User within the system - Internal or Business Partner Contact */ @Override public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_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_AD_SchedulerRecipient.java
1
请完成以下Java代码
public WebuiLetter createNewLetter(final WebuiLetterBuilder createRequest) { final WebuiLetter letter = createRequest .letterId(String.valueOf(nextLetterId.getAndIncrement())) .build(); Check.assumeNotNull(letter.getOwnerUserId(), "ownerUserId is not null"); lettersById.put(letter.getLetterId(), new WebuiLetterEntry(letter)); return letter; } private WebuiLetterEntry getLetterEntry(final String letterId) { final WebuiLetterEntry letterEntry = lettersById.getIfPresent(letterId); if (letterEntry == null) { throw new EntityNotFoundException("Letter not found").setParameter("letterId", letterId); } return letterEntry; } public WebuiLetter getLetter(final String letterId) { return getLetterEntry(letterId).getLetter(); } public WebuiLetterChangeResult changeLetter(final String letterId, @NonNull final UnaryOperator<WebuiLetter> letterModifier) { return getLetterEntry(letterId).compute(letterModifier); } public void removeLetterById(final String letterId) { lettersById.invalidate(letterId); } public void createC_Letter(@NonNull final WebuiLetter letter) { final I_C_Letter persistentLetter = InterfaceWrapperHelper.newInstance(I_C_Letter.class); persistentLetter.setLetterSubject(letter.getSubject()); persistentLetter.setLetterBody(Strings.nullToEmpty(letter.getContent())); persistentLetter.setLetterBodyParsed(letter.getContent()); persistentLetter.setAD_BoilerPlate_ID(letter.getTextTemplateId()); persistentLetter.setC_BPartner_ID(letter.getBpartnerId()); persistentLetter.setC_BPartner_Location_ID(letter.getBpartnerLocationId()); persistentLetter.setC_BP_Contact_ID(letter.getBpartnerContactId()); persistentLetter.setBPartnerAddress(Strings.nullToEmpty(letter.getBpartnerAddress())); InterfaceWrapperHelper.save(persistentLetter); } @ToString private static final class WebuiLetterEntry
{ private WebuiLetter letter; public WebuiLetterEntry(@NonNull final WebuiLetter letter) { this.letter = letter; } public synchronized WebuiLetter getLetter() { return letter; } public synchronized WebuiLetterChangeResult compute(final UnaryOperator<WebuiLetter> modifier) { final WebuiLetter letterOld = letter; final WebuiLetter letterNew = modifier.apply(letterOld); if (letterNew == null) { throw new NullPointerException("letter"); } letter = letterNew; return WebuiLetterChangeResult.builder().letter(letterNew).originalLetter(letterOld).build(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\letter\WebuiLetterRepository.java
1
请完成以下Java代码
public int signum() {return source.signum();} public CurrencyId getSourceCurrencyId() {return source.getCurrencyId();} private MoneySourceAndAcct newOfSourceAndAcct(@NonNull final Money newSource, @NonNull final Money newAcct) { if (Money.equals(this.source, newSource) && Money.equals(this.acct, newAcct)) { return this; } return ofSourceAndAcct(newSource, newAcct); } public MoneySourceAndAcct divide(@NonNull final MoneySourceAndAcct divisor, @NonNull final CurrencyPrecision precision) { return newOfSourceAndAcct(source.divide(divisor.source, precision), acct.divide(divisor.acct, precision)); } public MoneySourceAndAcct multiply(@NonNull final BigDecimal multiplicand) { return newOfSourceAndAcct(source.multiply(multiplicand), acct.multiply(multiplicand)); }
public MoneySourceAndAcct negate() { return newOfSourceAndAcct(source.negate(), acct.negate()); } public MoneySourceAndAcct negateIf(final boolean condition) { return condition ? negate() : this; } public MoneySourceAndAcct toZero() { return newOfSourceAndAcct(source.toZero(), acct.toZero()); } public MoneySourceAndAcct roundIfNeeded(@NonNull final CurrencyPrecision sourcePrecision, @NonNull final CurrencyPrecision acctPrecision) { return newOfSourceAndAcct(source.roundIfNeeded(sourcePrecision), acct.roundIfNeeded(acctPrecision)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java-legacy\org\compiere\acct\MoneySourceAndAcct.java
1
请完成以下Java代码
protected Mono<Health> doHealthCheck(Health.Builder builder) { return runHealthCheckQuery() .doOnError(SessionExpiredException.class, (ex) -> logger.warn(Neo4jHealthIndicator.MESSAGE_SESSION_EXPIRED)) .retryWhen(Retry.max(1).filter(SessionExpiredException.class::isInstance)) .map((healthDetails) -> { this.healthDetailsHandler.addHealthDetails(builder, healthDetails); return builder.build(); }); } Mono<Neo4jHealthDetails> runHealthCheckQuery() { return Mono.using(this::session, this::healthDetails, ReactiveSession::close); } private ReactiveSession session() { return this.driver.session(ReactiveSession.class, Neo4jHealthIndicator.DEFAULT_SESSION_CONFIG); } private Mono<Neo4jHealthDetails> healthDetails(ReactiveSession session) { return Mono.from(session.run(Neo4jHealthIndicator.CYPHER)).flatMap(this::healthDetails); } private Mono<? extends Neo4jHealthDetails> healthDetails(ReactiveResult result) { Flux<Record> records = Flux.from(result.records()); Mono<ResultSummary> summary = Mono.from(result.consume()); Neo4jHealthDetailsBuilder builder = new Neo4jHealthDetailsBuilder(); return records.single().doOnNext(builder::record).then(summary).map(builder::build); } /** * Builder used to create a {@link Neo4jHealthDetails} from a {@link Record} and a * {@link ResultSummary}.
*/ private static final class Neo4jHealthDetailsBuilder { private @Nullable Record record; void record(Record record) { this.record = record; } private Neo4jHealthDetails build(ResultSummary summary) { Assert.state(this.record != null, "'record' must not be null"); return new Neo4jHealthDetails(this.record, summary); } } }
repos\spring-boot-4.0.1\module\spring-boot-neo4j\src\main\java\org\springframework\boot\neo4j\health\Neo4jReactiveHealthIndicator.java
1
请完成以下Java代码
public void setName(String value) { set(1, value); } /** * Getter for <code>public.BookAuthor.name</code>. */ public String getName() { return (String) get(1); } /** * Setter for <code>public.BookAuthor.country</code>. */ public void setCountry(String value) { set(2, value); } /** * Getter for <code>public.BookAuthor.country</code>. */ public String getCountry() { return (String) get(2); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- @Override public Record1<Integer> key() { return (Record1) super.key(); } // -------------------------------------------------------------------------
// Constructors // ------------------------------------------------------------------------- /** * Create a detached BookauthorRecord */ public BookauthorRecord() { super(Bookauthor.BOOKAUTHOR); } /** * Create a detached, initialised BookauthorRecord */ public BookauthorRecord(Integer id, String name, String country) { super(Bookauthor.BOOKAUTHOR); setId(id); setName(name); setCountry(country); resetChangedOnNotNull(); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\records\BookauthorRecord.java
1
请完成以下Java代码
public Timestamp getDateFrom () { return (Timestamp)get_Value(COLUMNNAME_DateFrom); } /** Set Date To. @param DateTo End date of a date range */ public void setDateTo (Timestamp DateTo) { set_Value (COLUMNNAME_DateTo, DateTo); } /** Get Date To. @return End date of a date range */ public Timestamp getDateTo () { return (Timestamp)get_Value(COLUMNNAME_DateTo); } /** 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); } public I_S_Resource getS_Resource() throws RuntimeException { return (I_S_Resource)MTable.get(getCtx(), I_S_Resource.Table_Name) .getPO(getS_Resource_ID(), get_TrxName()); } /** Set Resource. @param S_Resource_ID Resource */ public void setS_Resource_ID (int S_Resource_ID) {
if (S_Resource_ID < 1) set_ValueNoCheck (COLUMNNAME_S_Resource_ID, null); else set_ValueNoCheck (COLUMNNAME_S_Resource_ID, Integer.valueOf(S_Resource_ID)); } /** Get Resource. @return Resource */ public int getS_Resource_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_Resource_ID); if (ii == null) return 0; return ii.intValue(); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), String.valueOf(getS_Resource_ID())); } /** Set Resource Unavailability. @param S_ResourceUnAvailable_ID Resource Unavailability */ public void setS_ResourceUnAvailable_ID (int S_ResourceUnAvailable_ID) { if (S_ResourceUnAvailable_ID < 1) set_ValueNoCheck (COLUMNNAME_S_ResourceUnAvailable_ID, null); else set_ValueNoCheck (COLUMNNAME_S_ResourceUnAvailable_ID, Integer.valueOf(S_ResourceUnAvailable_ID)); } /** Get Resource Unavailability. @return Resource Unavailability */ public int getS_ResourceUnAvailable_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_ResourceUnAvailable_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_ResourceUnAvailable.java
1
请完成以下Java代码
public String getURI() { return uri; } /** * Sets the value of the uri property. * * @param value * allowed object is * {@link String } * */ public void setURI(String value) { this.uri = value; } /** * Gets the value of the type property. * * @return * possible object is * {@link String } * */ public String getType() {
return type; } /** * Sets the value of the type property. * * @param value * allowed object is * {@link String } * */ public void setType(String value) { this.type = value; } }
repos\metasfresh-new_dawn_uat\backend\vertical-healthcare_ch\forum_datenaustausch_ch.invoice_440_request\src\main\java-xjc\de\metas\vertical\healthcare_ch\forum_datenaustausch_ch\invoice_440\request\RetrievalMethodType.java
1
请完成以下Java代码
private List<TableRecordReference> extractTableRecordReferences(@NonNull final JsonAttachmentRequest request) { final ImmutableList.Builder<TableRecordReference> tableRecordReferenceBuilder = ImmutableList.builder(); request.getTargets() .stream() .map(target -> extractTableRecordReference(request.getOrgCode(), target)) .forEach(tableRecordReferenceBuilder::add); request.getReferences() .stream() .map(AttachmentRestService::extractTableRecordReference) .forEach(tableRecordReferenceBuilder::add); return tableRecordReferenceBuilder.build(); } @NonNull private static TableRecordReference extractTableRecordReference(@NonNull final JsonTableRecordReference reference) { return TableRecordReference.of(reference.getTableName(), reference.getRecordId().getValue()); } private static void validateLocalFileURL(@NonNull final URL url) {
if (!url.getProtocol().equals("file")) { throw new AdempiereException("Protocol " + url.getProtocol() + " not supported!"); } final Path filePath = FileUtil.getFilePath(url); if (!filePath.toFile().isFile()) { throw new AdempiereException("Provided local file with URL: " + url + " is not accessible!") .appendParametersToMessage() .setParameter("ParsedPath", filePath.toString()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\attachment\AttachmentRestService.java
1
请在Spring Boot框架中完成以下Java代码
public BigDecimal getQtyEnteredInBPartnerUOM() { return qtyEnteredInBPartnerUOM; } /** * Sets the value of the qtyEnteredInBPartnerUOM property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setQtyEnteredInBPartnerUOM(BigDecimal value) { this.qtyEnteredInBPartnerUOM = value; } /** * Gets the value of the externalSeqNo property. * * @return * possible object is * {@link BigInteger } * */ public BigInteger getExternalSeqNo() { return externalSeqNo;
} /** * Sets the value of the externalSeqNo property. * * @param value * allowed object is * {@link BigInteger } * */ public void setExternalSeqNo(BigInteger value) { this.externalSeqNo = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_metasfreshinhousev1\de\metas\edi\esb\jaxb\metasfreshinhousev1\EDICctopInvoic500VType.java
2
请完成以下Java代码
public String toString() { return getSql(); } @Override public String getSql() { buildSqlIfNeeded(); return sqlWhereClause; } @Override public List<Object> getSqlParams(final Properties ctx_NOTUSED) { return getSqlParams(); } public List<Object> getSqlParams() { buildSqlIfNeeded(); return sqlParams; } private void buildSqlIfNeeded() { if (sqlWhereClause != null) { return; } if (isConstantTrue()) { final ConstantQueryFilter<Object> acceptAll = ConstantQueryFilter.of(true); sqlParams = acceptAll.getSqlParams(); sqlWhereClause = acceptAll.getSql();
} else { sqlParams = Arrays.asList(lowerBoundValue, upperBoundValue); sqlWhereClause = "NOT ISEMPTY(" + "TSTZRANGE(" + lowerBoundColumnName.getColumnName() + ", " + upperBoundColumnName.getColumnName() + ", '[)')" + " * " + "TSTZRANGE(?, ?, '[)')" + ")"; } } private boolean isConstantTrue() { return lowerBoundValue == null && upperBoundValue == null; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\dao\impl\DateIntervalIntersectionQueryFilter.java
1
请完成以下Java代码
public boolean isDate() { if (m_displayType == 0) return m_value instanceof Timestamp; return DisplayType.isDate(m_displayType); } // isDate /** * Is Value an ID * @return true if value is an ID */ public boolean isID() { // ID columns are considered numbers - teo_sarca [ 1673363 ] if (DisplayType.ID == m_displayType) return false; return DisplayType.isID(m_displayType); } // isID /** * Is Value boolean * @return true if value is a boolean */ public boolean isYesNo() { if (m_displayType == 0) return m_value instanceof Boolean; return DisplayType.YesNo == m_displayType; } // isYesNo /** * Is Value the primary key of row * @return true if value is the PK */ public boolean isPKey() { return m_isPKey; } // isPKey /** * Column value forces page break * @return true if page break */ public boolean isPageBreak() { return m_isPageBreak; } // isPageBreak /*************************************************************************/ /** * HashCode * @return hash code */ public int hashCode() { if (m_value == null) return m_columnName.hashCode(); return m_columnName.hashCode() + m_value.hashCode(); } // hashCode /** * Equals * @param compare compare object * @return true if equals */ public boolean equals (Object compare) { if (compare instanceof PrintDataElement) { PrintDataElement pde = (PrintDataElement)compare; if (pde.getColumnName().equals(m_columnName)) { if (pde.getValue() != null && pde.getValue().equals(m_value)) return true; if (pde.getValue() == null && m_value == null) return true; } } return false;
} // equals /** * String representation * @return info */ public String toString() { StringBuffer sb = new StringBuffer(m_columnName).append("=").append(m_value); if (m_isPKey) sb.append("(PK)"); return sb.toString(); } // toString /** * Value Has Key * @return true if value has a key */ public boolean hasKey() { return m_value instanceof NamePair; } // hasKey /** * String representation with key info * @return info */ public String toStringX() { if (m_value instanceof NamePair) { NamePair pp = (NamePair)m_value; StringBuffer sb = new StringBuffer(m_columnName); sb.append("(").append(pp.getID()).append(")") .append("=").append(pp.getName()); if (m_isPKey) sb.append("(PK)"); return sb.toString(); } else return toString(); } // toStringX public String getM_formatPattern() { return m_formatPattern; } public void setM_formatPattern(String pattern) { m_formatPattern = pattern; } } // PrintDataElement
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\PrintDataElement.java
1
请完成以下Java代码
public void setM_AttributeSearch(final org.compiere.model.I_M_AttributeSearch M_AttributeSearch) { set_ValueFromPO(COLUMNNAME_M_AttributeSearch_ID, org.compiere.model.I_M_AttributeSearch.class, M_AttributeSearch); } @Override public void setM_AttributeSearch_ID (final int M_AttributeSearch_ID) { if (M_AttributeSearch_ID < 1) set_Value (COLUMNNAME_M_AttributeSearch_ID, null); else set_Value (COLUMNNAME_M_AttributeSearch_ID, M_AttributeSearch_ID); } @Override public int getM_AttributeSearch_ID() { return get_ValueAsInt(COLUMNNAME_M_AttributeSearch_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setPrintValue_Override (final @Nullable java.lang.String PrintValue_Override) { set_Value (COLUMNNAME_PrintValue_Override, PrintValue_Override); } @Override public java.lang.String getPrintValue_Override() { return get_ValueAsString(COLUMNNAME_PrintValue_Override); } @Override public void setValue (final java.lang.String Value) { set_ValueNoCheck (COLUMNNAME_Value, Value); } @Override public java.lang.String getValue() {
return get_ValueAsString(COLUMNNAME_Value); } @Override public void setValueMax (final @Nullable BigDecimal ValueMax) { set_Value (COLUMNNAME_ValueMax, ValueMax); } @Override public BigDecimal getValueMax() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMax); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setValueMin (final @Nullable BigDecimal ValueMin) { set_Value (COLUMNNAME_ValueMin, ValueMin); } @Override public BigDecimal getValueMin() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_ValueMin); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Attribute.java
1
请完成以下Java代码
public void setC_Channel_ID (int C_Channel_ID) { if (C_Channel_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Channel_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Channel_ID, Integer.valueOf(C_Channel_ID)); } /** Get Channel. @return Sales Channel */ public int getC_Channel_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Channel_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 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_Channel.java
1
请完成以下Java代码
public BigDecimal getManualActual () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ManualActual); if (bd == null) return Env.ZERO; return bd; } /** 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 Note. @param Note Optional additional user defined information */ public void setNote (String Note) { set_Value (COLUMNNAME_Note, Note); } /** Get Note. @return Optional additional user defined information */ public String getNote () { return (String)get_Value(COLUMNNAME_Note); } /** Set Achievement. @param PA_Achievement_ID Performance Achievement */ public void setPA_Achievement_ID (int PA_Achievement_ID) { if (PA_Achievement_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Achievement_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Achievement_ID, Integer.valueOf(PA_Achievement_ID)); } /** Get Achievement. @return Performance Achievement */ public int getPA_Achievement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Achievement_ID); if (ii == null)
return 0; return ii.intValue(); } public I_PA_Measure getPA_Measure() throws RuntimeException { return (I_PA_Measure)MTable.get(getCtx(), I_PA_Measure.Table_Name) .getPO(getPA_Measure_ID(), get_TrxName()); } /** Set Measure. @param PA_Measure_ID Concrete Performance Measurement */ public void setPA_Measure_ID (int PA_Measure_ID) { if (PA_Measure_ID < 1) set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, null); else set_ValueNoCheck (COLUMNNAME_PA_Measure_ID, Integer.valueOf(PA_Measure_ID)); } /** Get Measure. @return Concrete Performance Measurement */ public int getPA_Measure_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_PA_Measure_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_PA_Achievement.java
1
请完成以下Java代码
protected EngineClientException exceptionWhileReceivingResponse(HttpRequest httpRequest, RestException e) { return new EngineClientException(exceptionMessage( "001", "Request '{}' returned error: status code '{}' - message: {}", httpRequest, e.getHttpStatusCode(), e.getMessage()), e); } protected EngineClientException exceptionWhileEstablishingConnection(HttpRequest httpRequest, IOException e) { return new EngineClientException(exceptionMessage( "002", "Exception while establishing connection for request '{}'", httpRequest), e); } protected <T> void exceptionWhileClosingResourceStream(T response, IOException e) { logError( "003", "Exception while closing resource stream of response '" + response + "': ", e); } protected <T> EngineClientException exceptionWhileParsingJsonObject(Class<T> responseDtoClass, Throwable t) { return new EngineClientException(exceptionMessage( "004", "Exception while parsing json object to response dto class '{}'", responseDtoClass), t); } protected <T> EngineClientException exceptionWhileMappingJsonObject(Class<T> responseDtoClass, Throwable t) { return new EngineClientException(exceptionMessage( "005", "Exception while mapping json object to response dto class '{}'", responseDtoClass), t); } protected <T> EngineClientException exceptionWhileDeserializingJsonObject(Class<T> responseDtoClass, Throwable t) {
return new EngineClientException(exceptionMessage( "006", "Exception while deserializing json object to response dto class '{}'", responseDtoClass), t); } protected <D extends RequestDto> EngineClientException exceptionWhileSerializingJsonObject(D dto, Throwable t) { return new EngineClientException(exceptionMessage( "007", "Exception while serializing json object to '{}'", dto), t); } public void requestInterceptorException(Throwable e) { logError( "008", "Exception while executing request interceptor: {}", e); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\impl\EngineClientLogger.java
1
请在Spring Boot框架中完成以下Java代码
public class MultiCustomerHUReturnsResult { @NonNull @Singular ImmutableList<CustomerHUReturnsResult> items; public List<I_M_InOut> getCustomerReturns() { return items.stream().map(CustomerHUReturnsResult::getCustomerReturn).collect(Collectors.toList()); } public Set<HuId> getReturnedHUIds() { return items.stream() .flatMap(CustomerHUReturnsResult::streamReturnedHUIds) .collect(ImmutableSet.toImmutableSet()); } @Value @Builder public static class CustomerHUReturnsResult {
@NonNull I_M_InOut customerReturn; @NonNull List<I_M_HU> returnedHUs; private Stream<HuId> streamReturnedHUIds() { return streamReturnedHUs().map(returnedHU -> HuId.ofRepoId(returnedHU.getM_HU_ID())); } private Stream<I_M_HU> streamReturnedHUs() { return returnedHUs.stream(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\inout\returns\customer\MultiCustomerHUReturnsResult.java
2
请在Spring Boot框架中完成以下Java代码
public class QuoteCriteria implements Serializable { private static final long serialVersionUID = 1L; private LongFilter id; private StringFilter symbol; private BigDecimalFilter price; private ZonedDateTimeFilter lastTrade; public QuoteCriteria() { } public LongFilter getId() { return id; } public void setId(LongFilter id) { this.id = id; } public StringFilter getSymbol() { return symbol; } public void setSymbol(StringFilter symbol) { this.symbol = symbol; } public BigDecimalFilter getPrice() { return price; } public void setPrice(BigDecimalFilter price) { this.price = price; } public ZonedDateTimeFilter getLastTrade() { return lastTrade; } public void setLastTrade(ZonedDateTimeFilter lastTrade) { this.lastTrade = lastTrade; } @Override public boolean equals(Object o) { if (this == o) { return true; }
if (o == null || getClass() != o.getClass()) { return false; } final QuoteCriteria that = (QuoteCriteria) o; return Objects.equals(id, that.id) && Objects.equals(symbol, that.symbol) && Objects.equals(price, that.price) && Objects.equals(lastTrade, that.lastTrade); } @Override public int hashCode() { return Objects.hash( id, symbol, price, lastTrade ); } @Override public String toString() { return "QuoteCriteria{" + (id != null ? "id=" + id + ", " : "") + (symbol != null ? "symbol=" + symbol + ", " : "") + (price != null ? "price=" + price + ", " : "") + (lastTrade != null ? "lastTrade=" + lastTrade + ", " : "") + "}"; } }
repos\tutorials-master\jhipster-modules\jhipster-uaa\quotes\src\main\java\com\baeldung\jhipster\quotes\service\dto\QuoteCriteria.java
2
请在Spring Boot框架中完成以下Java代码
public void savaMenu(PmsMenu menu) { pmsMenuDao.insert(menu); } /** * 根据父菜单ID获取该菜单下的所有子孙菜单.<br/> * * @param parentId * (如果为空,则为获取所有的菜单).<br/> * @return menuList. */ @SuppressWarnings("rawtypes") public List getListByParent(Long parentId) { return pmsMenuDao.listByParent(parentId); } /** * 根据id删除菜单 */ public void delete(Long id) { this.pmsMenuDao.delete(id); } /** * 根据角色id串获取菜单 * * @param roleIdsStr * @return */ @SuppressWarnings("rawtypes") public List listByRoleIds(String roleIdsStr) { return this.pmsMenuDao.listByRoleIds(roleIdsStr); } /** * 根据菜单ID查找菜单(可用于判断菜单下是否还有子菜单). * * @param parentId * . * @return menuList. */ public List<PmsMenu> listByParentId(Long parentId) { return pmsMenuDao.listByParentId(parentId); } /*** * 根据名称和是否叶子节点查询数据 * * @param isLeaf * 是否是叶子节点 * @param name
* 节点名称 * @return */ public List<PmsMenu> getMenuByNameAndIsLeaf(Map<String, Object> map) { return pmsMenuDao.getMenuByNameAndIsLeaf(map); } /** * 根据菜单ID获取菜单. * * @param pid * @return */ public PmsMenu getById(Long pid) { return pmsMenuDao.getById(pid); } /** * 更新菜单. * * @param menu */ public void update(PmsMenu menu) { pmsMenuDao.update(menu); } /** * 根据角色查找角色对应的菜单ID集 * * @param roleId * @return */ public String getMenuIdsByRoleId(Long roleId) { List<PmsMenuRole> menuList = pmsMenuRoleDao.listByRoleId(roleId); StringBuffer menuIds = new StringBuffer(""); if (menuList != null && !menuList.isEmpty()) { for (PmsMenuRole rm : menuList) { menuIds.append(rm.getMenuId()).append(","); } } return menuIds.toString(); } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\permission\service\impl\PmsMenuServiceImpl.java
2
请完成以下Java代码
public DeploymentEntity findLatestDeploymentByName(String deploymentName) { List<?> list = getDbEntityManager().selectList("selectDeploymentsByName", deploymentName, 0, 1); if (list!=null && !list.isEmpty()) { return (DeploymentEntity) list.get(0); } return null; } public DeploymentEntity findDeploymentById(String deploymentId) { return getDbEntityManager().selectById(DeploymentEntity.class, deploymentId); } @SuppressWarnings("unchecked") public List<DeploymentEntity> findDeploymentsByIds(String... deploymentsIds) { return getDbEntityManager().selectList("selectDeploymentsByIds", deploymentsIds); } public long findDeploymentCountByQueryCriteria(DeploymentQueryImpl deploymentQuery) { configureQuery(deploymentQuery); return (Long) getDbEntityManager().selectOne("selectDeploymentCountByQueryCriteria", deploymentQuery); } @SuppressWarnings("unchecked") public List<Deployment> findDeploymentsByQueryCriteria(DeploymentQueryImpl deploymentQuery, Page page) { configureQuery(deploymentQuery); return getDbEntityManager().selectList("selectDeploymentsByQueryCriteria", deploymentQuery, page); } @SuppressWarnings("unchecked") public List<String> getDeploymentResourceNames(String deploymentId) { return getDbEntityManager().selectList("selectResourceNamesByDeploymentId", deploymentId); } @SuppressWarnings("unchecked") public List<String> findDeploymentIdsByProcessInstances(List<String> processInstanceIds) { return getDbEntityManager().selectList("selectDeploymentIdsByProcessInstances", processInstanceIds); } @Override public void close() { }
@Override public void flush() { } // helper ///////////////////////////////////////////////// protected void createDefaultAuthorizations(DeploymentEntity deployment) { if(isAuthorizationEnabled()) { ResourceAuthorizationProvider provider = getResourceAuthorizationProvider(); AuthorizationEntity[] authorizations = provider.newDeployment(deployment); saveDefaultAuthorizations(authorizations); } } protected void configureQuery(DeploymentQueryImpl query) { getAuthorizationManager().configureDeploymentQuery(query); getTenantManager().configureQuery(query); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\DeploymentManager.java
1
请完成以下Java代码
public class BM25 { /** * 文档句子的个数 */ int D; /** * 文档句子的平均长度 */ double avgdl; /** * 拆分为[句子[单词]]形式的文档 */ List<List<String>> docs; /** * 文档中每个句子中的每个词与词频 */ Map<String, Integer>[] f; /** * 文档中全部词语与出现在几个句子中 */ Map<String, Integer> df; /** * IDF */ Map<String, Double> idf; /** * 调节因子 */ final static float k1 = 1.5f; /** * 调节因子 */ final static float b = 0.75f; public BM25(List<List<String>> docs) { this.docs = docs; D = docs.size(); for (List<String> sentence : docs) { avgdl += sentence.size(); } avgdl /= D; f = new Map[D]; df = new TreeMap<String, Integer>(); idf = new TreeMap<String, Double>(); init(); } /** * 在构造时初始化自己的所有参数 */ private void init() { int index = 0; for (List<String> sentence : docs) { Map<String, Integer> tf = new TreeMap<String, Integer>(); for (String word : sentence) { Integer freq = tf.get(word); freq = (freq == null ? 0 : freq) + 1; tf.put(word, freq); } f[index] = tf; for (Map.Entry<String, Integer> entry : tf.entrySet()) { String word = entry.getKey(); Integer freq = df.get(word); freq = (freq == null ? 0 : freq) + 1; df.put(word, freq); } ++index; }
for (Map.Entry<String, Integer> entry : df.entrySet()) { String word = entry.getKey(); Integer freq = entry.getValue(); idf.put(word, Math.log(D - freq + 0.5) - Math.log(freq + 0.5)); } } /** * 计算一个句子与一个文档的BM25相似度 * * @param sentence 句子(查询语句) * @param index 文档(用语料库中的下标表示) * @return BM25 score */ public double sim(List<String> sentence, int index) { double score = 0; for (String word : sentence) { if (!f[index].containsKey(word)) continue; int d = docs.get(index).size(); Integer tf = f[index].get(word); score += (idf.get(word) * tf * (k1 + 1) / (tf + k1 * (1 - b + b * d / avgdl))); } return score; } public double[] simAll(List<String> sentence) { double[] scores = new double[D]; for (int i = 0; i < D; ++i) { scores[i] = sim(sentence, i); } return scores; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\summary\BM25.java
1
请完成以下Java代码
public class NERTagSet extends TagSet { public final String O_TAG = "O"; public final char O_TAG_CHAR = 'O'; public final String B_TAG_PREFIX = "B-"; public final char B_TAG_CHAR = 'B'; public final String M_TAG_PREFIX = "M-"; public final String E_TAG_PREFIX = "E-"; public final String S_TAG = "S"; public final char S_TAG_CHAR = 'S'; public final Set<String> nerLabels = new HashSet<String>(); /** * 非NER */ public final int O; public NERTagSet() { super(TaskType.NER); O = add(O_TAG); } public NERTagSet(int o, Collection<String> tags) { super(TaskType.NER); O = o; for (String tag : tags) { add(tag); String label = NERTagSet.posOf(tag); if (label.length() != tag.length()) nerLabels.add(label); } } public static String posOf(String tag) { int index = tag.indexOf('-'); if (index == -1) { return tag; }
return tag.substring(index + 1); } @Override public boolean load(ByteArray byteArray) { super.load(byteArray); nerLabels.clear(); for (Map.Entry<String, Integer> entry : this) { String tag = entry.getKey(); int index = tag.indexOf('-'); if (index != -1) { nerLabels.add(tag.substring(index + 1)); } } return true; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\tagset\NERTagSet.java
1
请完成以下Java代码
public int getC_PaymentTerm_ID() { return get_ValueAsInt(COLUMNNAME_C_PaymentTerm_ID); } @Override public void setC_PaySchedule_ID (final int C_PaySchedule_ID) { if (C_PaySchedule_ID < 1) set_ValueNoCheck (COLUMNNAME_C_PaySchedule_ID, null); else set_ValueNoCheck (COLUMNNAME_C_PaySchedule_ID, C_PaySchedule_ID); } @Override public int getC_PaySchedule_ID() { return get_ValueAsInt(COLUMNNAME_C_PaySchedule_ID); } @Override public void setDiscount (final BigDecimal Discount) { set_Value (COLUMNNAME_Discount, Discount); } @Override public BigDecimal getDiscount() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Discount); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setDiscountDays (final int DiscountDays) { set_Value (COLUMNNAME_DiscountDays, DiscountDays); } @Override public int getDiscountDays() { return get_ValueAsInt(COLUMNNAME_DiscountDays); } @Override public void setGraceDays (final int GraceDays) { set_Value (COLUMNNAME_GraceDays, GraceDays); } @Override public int getGraceDays() { return get_ValueAsInt(COLUMNNAME_GraceDays); } @Override public void setIsValid (final boolean IsValid) { set_Value (COLUMNNAME_IsValid, IsValid); } @Override public boolean isValid() { return get_ValueAsBoolean(COLUMNNAME_IsValid); } /** * NetDay AD_Reference_ID=167 * Reference name: Weekdays */ public static final int NETDAY_AD_Reference_ID=167;
/** Sunday = 7 */ public static final String NETDAY_Sunday = "7"; /** Monday = 1 */ public static final String NETDAY_Monday = "1"; /** Tuesday = 2 */ public static final String NETDAY_Tuesday = "2"; /** Wednesday = 3 */ public static final String NETDAY_Wednesday = "3"; /** Thursday = 4 */ public static final String NETDAY_Thursday = "4"; /** Friday = 5 */ public static final String NETDAY_Friday = "5"; /** Saturday = 6 */ public static final String NETDAY_Saturday = "6"; @Override public void setNetDay (final @Nullable java.lang.String NetDay) { set_Value (COLUMNNAME_NetDay, NetDay); } @Override public java.lang.String getNetDay() { return get_ValueAsString(COLUMNNAME_NetDay); } @Override public void setNetDays (final int NetDays) { set_Value (COLUMNNAME_NetDays, NetDays); } @Override public int getNetDays() { return get_ValueAsInt(COLUMNNAME_NetDays); } @Override public void setPercentage (final BigDecimal Percentage) { set_Value (COLUMNNAME_Percentage, Percentage); } @Override public BigDecimal getPercentage() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Percentage); return bd != null ? bd : BigDecimal.ZERO; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_PaySchedule.java
1
请完成以下Java代码
public static void deleteScheduledSelections() { final ITrxManager trxManager = Services.get(ITrxManager.class); final int maxQuerySelectionToDeleteToProcess = 1; boolean tryRemove = true; while (tryRemove) { final boolean removedSomething = trxManager.callInNewTrx(() -> deleteScheduledSelections0(maxQuerySelectionToDeleteToProcess)); logger.debug("Last invocation of deleteScheduledSelections0 returned removedSomething+{}", removedSomething); tryRemove = removedSomething; } } private static boolean deleteScheduledSelections0(final int maxQuerySelectionToDeleteToProcess) { final IQueryBL queryBL = Services.get(IQueryBL.class); final String executorId = UIDStringUtil.createRandomUUID(); // Tag scheduled IDs { final String sql = "UPDATE " + I_T_Query_Selection_ToDelete.Table_Name + " t" + " SET Executor_UUID=?" + " WHERE" + " UUID IN (SELECT distinct UUID FROM T_Query_Selection_ToDelete WHERE Executor_UUID IS NULL LIMIT ?)"; final int querySelectionToDeleteCount = DB.executeUpdateAndThrowExceptionOnFail(sql, new Object[] { executorId, maxQuerySelectionToDeleteToProcess }, ITrx.TRXNAME_ThreadInherited); logger.debug("Tagged {} selectionIds to be deleted", querySelectionToDeleteCount); if (querySelectionToDeleteCount <= 0) { return false; } } final IQuery<I_T_Query_Selection_ToDelete> selectionToDeleteQuery = queryBL .createQueryBuilder(I_T_Query_Selection_ToDelete.class) .addEqualsFilter(I_T_Query_Selection_ToDelete.COLUMNNAME_Executor_UUID, executorId) .create(); // Delete from T_Query_Selection { final int count = queryBL.createQueryBuilder(I_T_Query_Selection.class) .addInSubQueryFilter( I_T_Query_Selection.COLUMN_UUID, I_T_Query_Selection_ToDelete.COLUMN_UUID, selectionToDeleteQuery) .create() .deleteDirectly(); logger.debug("Deleted {} rows from {}", count, I_T_Query_Selection.Table_Name);
} // Delete from T_Query_Selection_Pagination { final int count = queryBL.createQueryBuilder(I_T_Query_Selection_Pagination.class) .addInSubQueryFilter( I_T_Query_Selection_Pagination.COLUMN_UUID, I_T_Query_Selection_ToDelete.COLUMN_UUID, selectionToDeleteQuery) .create() .deleteDirectly(); logger.debug("Deleted {} rows from {}", count, I_T_Query_Selection.Table_Name); } // Delete scheduled IDs { final int count = selectionToDeleteQuery.deleteDirectly(); logger.debug("Deleted {} rows from {}", count, I_T_Query_Selection_ToDelete.Table_Name); } return true; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dao\selection\QuerySelectionToDeleteHelper.java
1
请完成以下Java代码
public static long getTimeDiff(Date date1, Date date2){ if (date1 == null || date1 == null) { return 0L; } long diff = (date1.getTime() - date2.getTime()) > 0 ? (date1.getTime() - date2 .getTime()) : (date2.getTime() - date1.getTime()) ; return diff; } /* * 判断两个时间是不是在一个周中 */ public static boolean isSameWeekWithToday(Date date) { if (date == null) { return false; } // 0.先把Date类型的对象转换Calendar类型的对象 Calendar todayCal = Calendar.getInstance(); Calendar dateCal = Calendar.getInstance(); todayCal.setTime(new Date()); dateCal.setTime(date); int subYear = todayCal.get(Calendar.YEAR) - dateCal.get(Calendar.YEAR); // subYear==0,说明是同一年 if (subYear == 0) { if (todayCal.get(Calendar.WEEK_OF_YEAR) == dateCal.get(Calendar.WEEK_OF_YEAR)) return true; } else if (subYear == 1 && dateCal.get(Calendar.MONTH) == 11 && todayCal.get(Calendar.MONTH) == 0) { if (todayCal.get(Calendar.WEEK_OF_YEAR) == dateCal.get(Calendar.WEEK_OF_YEAR)) return true; } else if (subYear == -1 && todayCal.get(Calendar.MONTH) == 11 && dateCal.get(Calendar.MONTH) == 0) { if (todayCal.get(Calendar.WEEK_OF_YEAR) == dateCal.get(Calendar.WEEK_OF_YEAR)) return true; } return false; } /** * getStrFormTime: <br/> * * @param form * 格式时间 * @param date * 时间 * @return */ public static String getStrFormTime(String form, Date date) { SimpleDateFormat sdf = new SimpleDateFormat(form); return sdf.format(date); } /**
* 获取几天内日期 return 2014-5-4、2014-5-3 */ public static List<String> getLastDays(int countDay) { List<String> listDate = new ArrayList<String>(); for (int i = 0; i < countDay; i++) { listDate.add(DateUtils.getReqDateyyyyMMdd(DateUtils.getDate(-i))); } return listDate; } /** * 对时间进行格式化 * * @param date * @return */ public static Date dateFormat(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date value = new Date(); try { value = sdf.parse(sdf.format(date)); } catch (ParseException e) { e.printStackTrace(); } return value; } public static boolean isSameDayWithToday(Date date) { if (date == null) { return false; } Calendar todayCal = Calendar.getInstance(); Calendar dateCal = Calendar.getInstance(); todayCal.setTime(new Date()); dateCal.setTime(date); int subYear = todayCal.get(Calendar.YEAR) - dateCal.get(Calendar.YEAR); int subMouth = todayCal.get(Calendar.MONTH) - dateCal.get(Calendar.MONTH); int subDay = todayCal.get(Calendar.DAY_OF_MONTH) - dateCal.get(Calendar.DAY_OF_MONTH); if (subYear == 0 && subMouth == 0 && subDay == 0) { return true; } return false; } }
repos\roncoo-pay-master\roncoo-pay-common-core\src\main\java\com\roncoo\pay\common\core\utils\DateUtils.java
1
请完成以下Java代码
public class POReplicationTrxLineDraft { private final PO poDraft; private final I_EXP_ReplicationTrxLine trxLineDraft; private final boolean lookup; /** * Creates a POReplicationTrxLineDraft with <code>trxLine=null</code> and <code>doLookup=false</code> * * @param po */ public POReplicationTrxLineDraft(final PO po) { poDraft = po; trxLineDraft = null; lookup = false; } public POReplicationTrxLineDraft(final PO po, final I_EXP_ReplicationTrxLine trxLine, final boolean doLookup) { poDraft = po; trxLineDraft = trxLine; lookup = doLookup; }
public PO getPODraft() { return poDraft; } public I_EXP_ReplicationTrxLine getTrxLineDraftOrNull() { return trxLineDraft; } public boolean isDoLookup() { return lookup; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\server\rpl\trx\api\impl\POReplicationTrxLineDraft.java
1
请完成以下Java代码
public Criteria andMemberLevelNotBetween(Integer value1, Integer value2) { addCriterion("member_level not between", value1, value2, "memberLevel"); return (Criteria) this; } } public static class Criteria extends GeneratedCriteria { protected Criteria() { super(); } } public static class Criterion { private String condition; private Object value; private Object secondValue; private boolean noValue; private boolean singleValue; private boolean betweenValue; private boolean listValue; private String typeHandler; public String getCondition() { return condition; } public Object getValue() { return value; } public Object getSecondValue() { return secondValue; } public boolean isNoValue() { return noValue; } public boolean isSingleValue() { return singleValue; } public boolean isBetweenValue() { return betweenValue; } public boolean isListValue() { return listValue; }
public String getTypeHandler() { return typeHandler; } protected Criterion(String condition) { super(); this.condition = condition; this.typeHandler = null; this.noValue = true; } protected Criterion(String condition, Object value, String typeHandler) { super(); this.condition = condition; this.value = value; this.typeHandler = typeHandler; if (value instanceof List<?>) { this.listValue = true; } else { this.singleValue = true; } } protected Criterion(String condition, Object value) { this(condition, value, null); } protected Criterion(String condition, Object value, Object secondValue, String typeHandler) { super(); this.condition = condition; this.value = value; this.secondValue = secondValue; this.typeHandler = typeHandler; this.betweenValue = true; } protected Criterion(String condition, Object value, Object secondValue) { this(condition, value, secondValue, null); } } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\SmsCouponExample.java
1
请完成以下Java代码
public List<I_M_DeliveryDay> retrieveDeliveryDays(final I_M_Tour tour, final Timestamp deliveryDate) { final IQueryBL queryBL = Services.get(IQueryBL.class); final IQueryBuilder<I_M_DeliveryDay> queryBuilder = queryBL.createQueryBuilder(I_M_DeliveryDay.class, tour) .addEqualsFilter(I_M_DeliveryDay.COLUMN_M_Tour_ID, tour.getM_Tour_ID()) .addEqualsFilter(I_M_DeliveryDay.COLUMN_DeliveryDate, deliveryDate, DateTruncQueryFilterModifier.DAY) .addOnlyActiveRecordsFilter(); queryBuilder.orderBy() .addColumn(I_M_DeliveryDay.COLUMN_DeliveryDate, Direction.Ascending, Nulls.Last); return queryBuilder .create() .list(); } @Override public I_M_DeliveryDay_Alloc retrieveDeliveryDayAllocForModel(final IContextAware context, final IDeliveryDayAllocable deliveryDayAllocable) { Check.assumeNotNull(deliveryDayAllocable, "deliveryDayAllocable not null"); final String tableName = deliveryDayAllocable.getTableName(); final int adTableId = Services.get(IADTableDAO.class).retrieveTableId(tableName); final int recordId = deliveryDayAllocable.getRecord_ID(); return Services.get(IQueryBL.class) .createQueryBuilder(I_M_DeliveryDay_Alloc.class, context) .addEqualsFilter(I_M_DeliveryDay_Alloc.COLUMN_AD_Table_ID, adTableId)
.addEqualsFilter(I_M_DeliveryDay_Alloc.COLUMN_Record_ID, recordId) .addOnlyActiveRecordsFilter() .create() .firstOnly(I_M_DeliveryDay_Alloc.class); } @Override public boolean hasAllocations(final I_M_DeliveryDay deliveryDay) { Check.assumeNotNull(deliveryDay, "deliveryDay not null"); return Services.get(IQueryBL.class) .createQueryBuilder(I_M_DeliveryDay_Alloc.class, deliveryDay) .addEqualsFilter(I_M_DeliveryDay_Alloc.COLUMN_M_DeliveryDay_ID, deliveryDay.getM_DeliveryDay_ID()) .addOnlyActiveRecordsFilter() .create() .anyMatch(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\tourplanning\api\impl\DeliveryDayDAO.java
1
请完成以下Java代码
public String[] tag(String... words) { POSInstance instance = new POSInstance(words, model.featureMap); return tag(instance); } public String[] tag(POSInstance instance) { instance.tagArray = new int[instance.featureMatrix.length]; model.viterbiDecode(instance, instance.tagArray); return instance.tags(model.tagSet()); } /** * 标注 * * @param wordList * @return */ @Override public String[] tag(List<String> wordList) { String[] termArray = new String[wordList.size()]; wordList.toArray(termArray); return tag(termArray); } /** * 在线学习 * * @param segmentedTaggedSentence 人民日报2014格式的句子 * @return 是否学习成功(失败的原因是参数错误) */ public boolean learn(String segmentedTaggedSentence) { return learn(POSInstance.create(segmentedTaggedSentence, model.featureMap)); }
/** * 在线学习 * * @param wordTags [单词]/[词性]数组 * @return 是否学习成功(失败的原因是参数错误) */ public boolean learn(String... wordTags) { String[] words = new String[wordTags.length]; String[] tags = new String[wordTags.length]; for (int i = 0; i < wordTags.length; i++) { String[] wordTag = wordTags[i].split("//"); words[i] = wordTag[0]; tags[i] = wordTag[1]; } return learn(new POSInstance(words, tags, model.featureMap)); } @Override protected Instance createInstance(Sentence sentence, FeatureMap featureMap) { for (Word word : sentence.toSimpleWordList()) { if (!model.featureMap.tagSet.contains(word.getLabel())) throw new IllegalArgumentException("在线学习不可能学习新的标签: " + word + " ;请标注语料库后重新全量训练。"); } return POSInstance.create(sentence, featureMap); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronPOSTagger.java
1
请在Spring Boot框架中完成以下Java代码
public void postProcessBeanFactory(ConfigurableListableBeanFactory bf) throws BeansException { Class<?> contextSourceClass = getContextSourceClass(); String[] sources = bf.getBeanNamesForType(contextSourceClass, false, false); if (sources.length == 0) { throw new ApplicationContextException("No BaseLdapPathContextSource instances found. Have you " + "added an <" + Elements.LDAP_SERVER + " /> element to your application context? If you have " + "declared an explicit bean, do not use lazy-init"); } if (!bf.containsBean(BeanIds.CONTEXT_SOURCE) && this.defaultNameRequired) { if (sources.length > 1) { throw new ApplicationContextException("More than one BaseLdapPathContextSource instance found. " + "Please specify a specific server id using the 'server-ref' attribute when configuring your <" + Elements.LDAP_PROVIDER + "> " + "or <" + Elements.LDAP_USER_SERVICE + ">."); } bf.registerAlias(sources[0], BeanIds.CONTEXT_SOURCE); } } private Class<?> getContextSourceClass() throws LinkageError { try { return ClassUtils.forName(REQUIRED_CONTEXT_SOURCE_CLASS_NAME, ClassUtils.getDefaultClassLoader()); } catch (ClassNotFoundException ex) { throw new ApplicationContextException("Couldn't locate: " + REQUIRED_CONTEXT_SOURCE_CLASS_NAME + ". "
+ " If you are using LDAP with Spring Security, please ensure that you include the spring-ldap " + "jar file in your application", ex); } } public void setDefaultNameRequired(boolean defaultNameRequired) { this.defaultNameRequired = defaultNameRequired; } @Override public int getOrder() { return LOWEST_PRECEDENCE; } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\ldap\ContextSourceSettingPostProcessor.java
2
请完成以下Java代码
public ReferenceWalker<T> addPreVisitor(TreeVisitor<T> collector) { this.preVisitor.add(collector); return this; } public ReferenceWalker<T> addPostVisitor(TreeVisitor<T> collector) { this.postVisitor.add(collector); return this; } public T walkWhile() { return walkWhile(new ReferenceWalker.NullCondition<T>()); } public T walkUntil() { return walkUntil(new ReferenceWalker.NullCondition<T>()); } public T walkWhile(ReferenceWalker.WalkCondition<T> condition) { while (!condition.isFulfilled(getCurrentElement())) { for (TreeVisitor<T> collector : preVisitor) { collector.visit(getCurrentElement()); } currentElements.addAll(nextElements()); currentElements.remove(0); for (TreeVisitor<T> collector : postVisitor) { collector.visit(getCurrentElement()); } } return getCurrentElement(); } public T walkUntil(ReferenceWalker.WalkCondition<T> condition) { do { for (TreeVisitor<T> collector : preVisitor) { collector.visit(getCurrentElement()); } currentElements.addAll(nextElements()); currentElements.remove(0); for (TreeVisitor<T> collector : postVisitor) {
collector.visit(getCurrentElement()); } } while (!condition.isFulfilled(getCurrentElement())); return getCurrentElement(); } public T getCurrentElement() { return currentElements.isEmpty() ? null : currentElements.get(0); } public interface WalkCondition<S> { boolean isFulfilled(S element); } public static class NullCondition<S> implements ReferenceWalker.WalkCondition<S> { public boolean isFulfilled(S element) { return element == null; } public static <S> ReferenceWalker.WalkCondition<S> notNull() { return new NullCondition<S>(); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\tree\ReferenceWalker.java
1
请完成以下Java代码
public List<JSONObject> queryUserBySuperQuery(String superQuery, String matchType) { return null; } @Override public JSONObject queryUserById(String id) { return null; } @Override public List<JSONObject> queryDeptBySuperQuery(String superQuery, String matchType) { return null; } @Override public List<JSONObject> queryRoleBySuperQuery(String superQuery, String matchType) { return null; } @Override public List<String> selectUserIdByTenantId(String tenantId) { return null; } @Override public List<String> queryUserIdsByDeptIds(List<String> deptIds) { return null; } @Override public List<String> queryUserIdsByDeptPostIds(List<String> deptPostIds) { return List.of(); } @Override public List<String> queryUserAccountsByDeptIds(List<String> deptIds) { return null; } @Override public List<String> queryUserIdsByRoleds(List<String> roleCodes) { return null; } @Override public List<String> queryUsernameByIds(List<String> userIds) { return List.of(); } @Override public List<String> queryUsernameByDepartPositIds(List<String> positionIds) { return null; } @Override public List<String> queryUserIdsByPositionIds(List<String> positionIds) { return null; } @Override public List<String> getUserAccountsByDepCode(String orgCode) { return null; } @Override
public boolean dictTableWhiteListCheckBySql(String selectSql) { return false; } @Override public boolean dictTableWhiteListCheckByDict(String tableOrDictCode, String... fields) { return false; } @Override public void announcementAutoRelease(String dataId, String currentUserName) { } @Override public SysDepartModel queryCompByOrgCode(String orgCode) { return null; } @Override public SysDepartModel queryCompByOrgCodeAndLevel(String orgCode, Integer level) { return null; } @Override public Object runAiragFlow(AiragFlowDTO airagFlowDTO) { return null; } @Override public void uniPushMsgToUser(PushMessageDTO pushMessageDTO) { } @Override public String getDepartPathNameByOrgCode(String orgCode, String depId) { return ""; } @Override public List<String> queryUserIdsByCascadeDeptIds(List<String> deptIds) { return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-api\jeecg-system-cloud-api\src\main\java\org\jeecg\common\system\api\fallback\SysBaseAPIFallback.java
1
请完成以下Java代码
public void onSuccess(TsKvLatestRemovingResult result) { log.trace("removeLatest onSuccess [{}][{}][{}]", entityId, query.getKey(), query); } @Override public void onFailure(Throwable t) { log.info("removeLatest onFailure [{}][{}][{}]", entityId, query.getKey(), query, t); } }, MoreExecutors.directExecutor()); } return future; } @Override public ListenableFuture<Optional<TsKvEntry>> findLatestOpt(TenantId tenantId, EntityId entityId, String key) { log.trace("findLatestOpt"); return doFindLatest(tenantId, entityId, key); } @Override public ListenableFuture<TsKvEntry> findLatest(TenantId tenantId, EntityId entityId, String key) { return Futures.transform(doFindLatest(tenantId, entityId, key), x -> sqlDao.wrapNullTsKvEntry(key, x.orElse(null)), MoreExecutors.directExecutor()); } public ListenableFuture<Optional<TsKvEntry>> doFindLatest(TenantId tenantId, EntityId entityId, String key) { final TsLatestCacheKey cacheKey = new TsLatestCacheKey(entityId, key); ListenableFuture<TbCacheValueWrapper<TsKvEntry>> cacheFuture = cacheExecutorService.submit(() -> cache.get(cacheKey)); return Futures.transformAsync(cacheFuture, (cacheValueWrap) -> { if (cacheValueWrap != null) { final TsKvEntry tsKvEntry = cacheValueWrap.get(); log.debug("findLatest cache hit [{}][{}][{}]", entityId, key, tsKvEntry);
return Futures.immediateFuture(Optional.ofNullable(tsKvEntry)); } log.debug("findLatest cache miss [{}][{}]", entityId, key); ListenableFuture<Optional<TsKvEntry>> daoFuture = sqlDao.findLatestOpt(tenantId, entityId, key); return Futures.transform(daoFuture, daoValue -> { cache.put(cacheKey, daoValue.orElse(null)); return daoValue; }, MoreExecutors.directExecutor()); }, MoreExecutors.directExecutor()); } @Override public ListenableFuture<List<TsKvEntry>> findAllLatest(TenantId tenantId, EntityId entityId) { return sqlDao.findAllLatest(tenantId, entityId); } @Override public List<String> findAllKeysByDeviceProfileId(TenantId tenantId, DeviceProfileId deviceProfileId) { return sqlDao.findAllKeysByDeviceProfileId(tenantId, deviceProfileId); } @Override public List<String> findAllKeysByEntityIds(TenantId tenantId, List<EntityId> entityIds) { return sqlDao.findAllKeysByEntityIds(tenantId, entityIds); } @Override public ListenableFuture<List<String>> findAllKeysByEntityIdsAsync(TenantId tenantId, List<EntityId> entityIds) { return sqlDao.findAllKeysByEntityIdsAsync(tenantId, entityIds); } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sqlts\CachedRedisSqlTimeseriesLatestDao.java
1
请完成以下Java代码
void setObserver(Runnable observer) { this.observer = observer; } private Object tryConsume(MethodInvocation invocation, Consumer<MessageAndChannel> successHandler, BiConsumer<MessageAndChannel, Throwable> errorHandler) throws Throwable { MessageAndChannel mac = new MessageAndChannel((Message) invocation.getArguments()[1], (Channel) invocation.getArguments()[0]); Object ret = null; try { ret = invocation.proceed(); successHandler.accept(mac); } catch (Throwable e) { errorHandler.accept(mac, e); } return ret; } private void ack(MessageAndChannel mac) { try { mac.channel.basicAck(mac.message.getMessageProperties() .getDeliveryTag(), false); } catch (Exception e) { throw new RuntimeException(e); } } private int tryGetRetryCountOrFail(MessageAndChannel mac, Throwable originalError) throws Throwable { MessageProperties props = mac.message.getMessageProperties(); String xRetriedCountHeader = (String) props.getHeader("x-retried-count"); final int xRetriedCount = xRetriedCountHeader == null ? 0 : Integer.valueOf(xRetriedCountHeader); if (retryQueues.retriesExhausted(xRetriedCount)) { mac.channel.basicReject(props.getDeliveryTag(), false); throw originalError; } return xRetriedCount; } private void sendToNextRetryQueue(MessageAndChannel mac, int retryCount) throws Exception { String retryQueueName = retryQueues.getQueueName(retryCount); rabbitTemplate.convertAndSend(retryQueueName, mac.message, m -> {
MessageProperties props = m.getMessageProperties(); props.setExpiration(String.valueOf(retryQueues.getTimeToWait(retryCount))); props.setHeader("x-retried-count", String.valueOf(retryCount + 1)); props.setHeader("x-original-exchange", props.getReceivedExchange()); props.setHeader("x-original-routing-key", props.getReceivedRoutingKey()); return m; }); mac.channel.basicReject(mac.message.getMessageProperties() .getDeliveryTag(), false); } private class MessageAndChannel { private Message message; private Channel channel; private MessageAndChannel(Message message, Channel channel) { this.message = message; this.channel = channel; } } }
repos\tutorials-master\messaging-modules\spring-amqp\src\main\java\com\baeldung\springamqp\exponentialbackoff\RetryQueuesInterceptor.java
1
请在Spring Boot框架中完成以下Java代码
public String getNotifyRule() { return notifyRule; } /** 通知规则 */ public void setNotifyRule(String notifyRule) { this.notifyRule = notifyRule; } /** * 获取通知规则的Map<String, Integer>. * @return */ @SuppressWarnings({ "unchecked", "rawtypes" }) public Map<Integer, Integer> getNotifyRuleMap(){ return (Map) JSONObject.parseObject(getNotifyRule()); } /** 最后一次通知时间 **/ public Date getLastNotifyTime() { return lastNotifyTime; } /** 最后一次通知时间 **/ public void setLastNotifyTime(Date lastNotifyTime) { this.lastNotifyTime = lastNotifyTime; } /** 通知次数 **/ public Integer getNotifyTimes() { return notifyTimes; }
/** 通知次数 **/ public void setNotifyTimes(Integer notifyTimes) { this.notifyTimes = notifyTimes; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } /** 限制通知次数 **/ public Integer getLimitNotifyTimes() { return limitNotifyTimes; } /** 限制通知次数 **/ public void setLimitNotifyTimes(Integer limitNotifyTimes) { this.limitNotifyTimes = limitNotifyTimes; } public String getBankOrderNo() { return bankOrderNo; } public void setBankOrderNo(String bankOrderNo) { this.bankOrderNo = bankOrderNo; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\notify\entity\RpOrderResultQueryVo.java
2
请完成以下Java代码
protected String getHealthPath(ServiceInstance instance) { String healthPath = getMetadataValue(instance, KEYS_HEALTH_PATH); if (hasText(healthPath)) { return healthPath; } return this.healthEndpointPath; } protected URI getManagementUrl(ServiceInstance instance) { URI serviceUrl = this.getServiceUrl(instance); String managementScheme = this.getManagementScheme(instance); String managementHost = this.getManagementHost(instance); int managementPort = this.getManagementPort(instance); UriComponentsBuilder builder; if (serviceUrl.getHost().equals(managementHost) && serviceUrl.getScheme().equals(managementScheme) && serviceUrl.getPort() == managementPort) { builder = UriComponentsBuilder.fromUri(serviceUrl); } else { builder = UriComponentsBuilder.newInstance().scheme(managementScheme).host(managementHost); if (managementPort != -1) { builder.port(managementPort); } } return builder.path("/").path(getManagementPath(instance)).build().toUri(); } private String getManagementScheme(ServiceInstance instance) { String managementServerScheme = getMetadataValue(instance, KEYS_MANAGEMENT_SCHEME); if (hasText(managementServerScheme)) { return managementServerScheme; } return getServiceUrl(instance).getScheme(); } protected String getManagementHost(ServiceInstance instance) { String managementServerHost = getMetadataValue(instance, KEYS_MANAGEMENT_ADDRESS); if (hasText(managementServerHost)) { return managementServerHost; } return getServiceUrl(instance).getHost(); }
protected int getManagementPort(ServiceInstance instance) { String managementPort = getMetadataValue(instance, KEYS_MANAGEMENT_PORT); if (hasText(managementPort)) { return Integer.parseInt(managementPort); } return getServiceUrl(instance).getPort(); } protected String getManagementPath(ServiceInstance instance) { String managementPath = getMetadataValue(instance, KEYS_MANAGEMENT_PATH); if (hasText(managementPath)) { return managementPath; } return this.managementContextPath; } protected URI getServiceUrl(ServiceInstance instance) { return instance.getUri(); } protected Map<String, String> getMetadata(ServiceInstance instance) { return (instance.getMetadata() != null) ? instance.getMetadata() .entrySet() .stream() .filter((e) -> e.getKey() != null && e.getValue() != null) .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)) : emptyMap(); } public String getManagementContextPath() { return this.managementContextPath; } public void setManagementContextPath(String managementContextPath) { this.managementContextPath = managementContextPath; } public String getHealthEndpointPath() { return this.healthEndpointPath; } public void setHealthEndpointPath(String healthEndpointPath) { this.healthEndpointPath = healthEndpointPath; } }
repos\spring-boot-admin-master\spring-boot-admin-server-cloud\src\main\java\de\codecentric\boot\admin\server\cloud\discovery\DefaultServiceInstanceConverter.java
1
请完成以下Java代码
String getShowHelp(final Supplier<String> defaultValueSupplier) { return showHelp != null ? showHelp : defaultValueSupplier.get(); } ProcessDialogBuilder skipResultsPanel() { skipResultsPanel = true; return this; } boolean isSkipResultsPanel() { return skipResultsPanel; } public ProcessDialogBuilder setAllowProcessReRun(final Boolean allowProcessReRun) { this.allowProcessReRun = allowProcessReRun; return this; } boolean isAllowProcessReRun(final Supplier<Boolean> defaultValueSupplier) { return allowProcessReRun != null ? allowProcessReRun : defaultValueSupplier.get(); } public ProcessDialogBuilder setFromGridTab(GridTab gridTab) { final int windowNo = gridTab.getWindowNo(); final int tabNo = gridTab.getTabNo(); setWindowAndTabNo(windowNo, tabNo); setAdWindowId(gridTab.getAdWindowId()); setIsSOTrx(Env.isSOTrx(gridTab.getCtx(), windowNo)); setTableAndRecord(gridTab.getAD_Table_ID(), gridTab.getRecord_ID()); setWhereClause(gridTab.getTableModel().getSelectWhereClauseFinal()); skipResultsPanel(); return this; } public ProcessDialogBuilder setProcessExecutionListener(final IProcessExecutionListener processExecutionListener) {
this.processExecutionListener = processExecutionListener; return this; } IProcessExecutionListener getProcessExecutionListener() { return processExecutionListener; } public ProcessDialogBuilder setPrintPreview(final boolean printPreview) { this._printPreview = printPreview; return this; } boolean isPrintPreview() { if (_printPreview != null) { return _printPreview; } return Ini.isPropertyBool(Ini.P_PRINTPREVIEW); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\de\metas\process\ui\ProcessDialogBuilder.java
1
请完成以下Java代码
public static IndentingWriterFactory create(Function<Integer, String> defaultIndentingStrategy) { return new IndentingWriterFactory(new Builder(defaultIndentingStrategy)); } /** * Create a {@link IndentingWriterFactory}. * @param defaultIndentingStrategy the default indenting strategy to use * @param factory a consumer of the builder to apply further customizations * @return an {@link IndentingWriterFactory} */ public static IndentingWriterFactory create(Function<Integer, String> defaultIndentingStrategy, Consumer<Builder> factory) { Builder factoryBuilder = new Builder(defaultIndentingStrategy); factory.accept(factoryBuilder); return new IndentingWriterFactory(factoryBuilder); } /** * Settings customizer for {@link IndentingWriterFactory}. */ public static final class Builder { private final Function<Integer, String> defaultIndentingStrategy; private final Map<String, Function<Integer, String>> indentingStrategies = new HashMap<>(); private Builder(Function<Integer, String> defaultIndentingStrategy) {
this.defaultIndentingStrategy = defaultIndentingStrategy; } /** * Register an indenting strategy for the specified content. * @param contentId the identifier of the content to configure * @param indentingStrategy the indent strategy for that particular content * @return this for method chaining * @see #createIndentingWriter(String, Writer) */ public Builder indentingStrategy(String contentId, Function<Integer, String> indentingStrategy) { this.indentingStrategies.put(contentId, indentingStrategy); return this; } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\io\IndentingWriterFactory.java
1
请完成以下Java代码
public class VariableListenerSession implements Session { protected CommandContext commandContext; protected Map<String, List<VariableListenerSessionData>> variableData; public void addVariableData(String variableName, String changeType, String scopeId, String scopeType, String scopeDefinitionId) { if (variableData == null) { variableData = new LinkedHashMap<>(); } if (!variableData.containsKey(variableName)) { variableData.put(variableName, new ArrayList<>()); } VariableListenerSessionData sessionData = new VariableListenerSessionData(changeType, scopeId, scopeType, scopeDefinitionId); variableData.get(variableName).add(sessionData); }
@Override public void flush() { } @Override public void close() { } public Map<String, List<VariableListenerSessionData>> getVariableData() { return variableData; } public void setVariableData(Map<String, List<VariableListenerSessionData>> variableData) { this.variableData = variableData; } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\variablelistener\VariableListenerSession.java
1
请完成以下Java代码
public class SocialUser { @Getter private String username; @Getter private List<SocialUser> followers; public SocialUser(String username) { super(); this.username = username; this.followers = new ArrayList<>(); } public SocialUser(String username, List<SocialUser> followers) { super(); this.username = username; this.followers = followers;
} public long getFollowersCount() { return followers.size(); } public void addFollowers(List<SocialUser> followers) { this.followers.addAll(followers); } @Override public boolean equals(Object obj) { return ((SocialUser) obj).getUsername().equals(username); } }
repos\tutorials-master\algorithms-modules\algorithms-miscellaneous-6\src\main\java\com\baeldung\algorithms\greedy\SocialUser.java
1
请完成以下Java代码
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 int getM_Shipper_ID() { return get_ValueAsInt(COLUMNNAME_M_Shipper_ID); } @Override public void setM_ShipperTransportation_ID (final int M_ShipperTransportation_ID) { if (M_ShipperTransportation_ID < 1) set_Value (COLUMNNAME_M_ShipperTransportation_ID, null); else set_Value (COLUMNNAME_M_ShipperTransportation_ID, M_ShipperTransportation_ID); } @Override public int getM_ShipperTransportation_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipperTransportation_ID); } @Override public void setNetWeightKg (final @Nullable BigDecimal NetWeightKg) { set_Value (COLUMNNAME_NetWeightKg, NetWeightKg); } @Override public BigDecimal getNetWeightKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_NetWeightKg); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPackageDescription (final @Nullable java.lang.String PackageDescription) { set_Value (COLUMNNAME_PackageDescription, PackageDescription); } @Override
public java.lang.String getPackageDescription() { return get_ValueAsString(COLUMNNAME_PackageDescription); } @Override public void setPdfLabelData (final @Nullable byte[] PdfLabelData) { set_Value (COLUMNNAME_PdfLabelData, PdfLabelData); } @Override public byte[] getPdfLabelData() { return (byte[])get_Value(COLUMNNAME_PdfLabelData); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_DHL_ShipmentOrder.java
1
请完成以下Java代码
public Object invoke(Message<?> message, @Nullable Object... providedArgs) throws Exception { //NOSONAR if (this.invokerHandlerMethod != null) { return this.invokerHandlerMethod.invoke(message, providedArgs); // NOSONAR } else if (Objects.requireNonNull(this.delegatingHandler).hasDefaultHandler()) { // Needed to avoid returning raw Message which matches Object Object[] args = new Object[providedArgs.length + 1]; args[0] = message.getPayload(); System.arraycopy(providedArgs, 0, args, 1, providedArgs.length); return this.delegatingHandler.invoke(message, args); } else { return this.delegatingHandler.invoke(message, providedArgs); } } public String getMethodAsString(Object payload) { if (this.invokerHandlerMethod != null) { return this.invokerHandlerMethod.getMethod().toGenericString(); } else { return Objects.requireNonNull(this.delegatingHandler).getMethodNameFor(payload);
} } public Object getBean() { if (this.invokerHandlerMethod != null) { return this.invokerHandlerMethod.getBean(); } else { return Objects.requireNonNull(this.delegatingHandler).getBean(); } } @Nullable public InvocationResult getInvocationResultFor(Object result, @Nullable Object inboundPayload) { if (this.delegatingHandler != null && inboundPayload != null) { return this.delegatingHandler.getInvocationResultFor(result, inboundPayload); } return null; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\HandlerAdapter.java
1
请完成以下Java代码
private static HUQRCodeProductInfo fromJson(@Nullable final JsonHUQRCodeProductInfoV1 json) { if (json == null) { return null; } return HUQRCodeProductInfo.builder() .id(json.getId()) .code(json.getCode()) .name(json.getName()) .build(); } private static JsonHUQRCodeAttributeV1 toJson(@NonNull final HUQRCodeAttribute attribute) { return JsonHUQRCodeAttributeV1.builder() .code(attribute.getCode()) .displayName(attribute.getDisplayName()) .value(attribute.getValue()) // NOTE: in order to make the generated JSON shorter,
// we will set valueRendered only if it's different from value. .valueRendered( !Objects.equals(attribute.getValue(), attribute.getValueRendered()) ? attribute.getValueRendered() : null) .build(); } private static HUQRCodeAttribute fromJson(@NonNull final JsonHUQRCodeAttributeV1 json) { return HUQRCodeAttribute.builder() .code(json.getCode()) .displayName(json.getDisplayName()) .value(json.getValue()) .valueRendered(json.getValueRendered()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\qrcodes\model\json\v1\JsonConverterV1.java
1
请完成以下Java代码
public boolean apply(IAllocableDocRow row) { return !row.isTaboo(); } }; Ordering<IAllocableDocRow> ORDERING_DocumentDate_DocumentNo = new Ordering<IAllocableDocRow>() { @Override public int compare(IAllocableDocRow row1, IAllocableDocRow row2) { return ComparisonChain.start() .compare(row1.getDocumentDate(), row2.getDocumentDate()) .compare(row1.getDocumentNo(), row2.getDocumentNo()) .result(); } }; //@formatter:off String PROPERTY_Selected = "Selected"; boolean isSelected(); void setSelected(boolean selected); //@formatter:on String getDocumentNo(); //@formatter:off BigDecimal getOpenAmtConv(); BigDecimal getOpenAmtConv_APAdjusted(); //@formatter:on //@formatter:off String PROPERTY_AppliedAmt = "AppliedAmt"; BigDecimal getAppliedAmt(); BigDecimal getAppliedAmt_APAdjusted(); void setAppliedAmt(BigDecimal appliedAmt); /** Sets applied amount and update the other write-off amounts, if needed. */ void setAppliedAmtAndUpdate(PaymentAllocationContext context, BigDecimal appliedAmt); //@formatter:on /** @return true if automatic calculations and updating are allowed on this row; false if user manually set the amounts and we don't want to change them for him/her */ boolean isTaboo(); /** * @param taboo <ul> * <li>true if automatic calculations shall be disallowed on this row * <li>false if automatic calculations are allowed on this row
* </ul> */ void setTaboo(boolean taboo); /** @return document's date */ Date getDocumentDate(); // task 09643: separate the accounting date from the transaction date Date getDateAcct(); int getC_BPartner_ID(); /** @return AP Multiplier, i.e. Vendor=-1, Customer=+1 */ BigDecimal getMultiplierAP(); boolean isVendorDocument(); boolean isCustomerDocument(); boolean isCreditMemo(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\IAllocableDocRow.java
1
请完成以下Java代码
private ViewRowIdsOrderedSelections addRemoveChangedRows( @NonNull final ViewRowIdsOrderedSelections selections, @NonNull final Set<DocumentId> rowIds, @NonNull final AddRemoveChangedRowIdsCollector changesCollector) { final ViewRowIdsOrderedSelection defaultSelectionBeforeFacetsFiltering = viewDataRepository.addRemoveChangedRows( selections.getDefaultSelectionBeforeFacetsFiltering(), filtersExcludingFacets, rowIds, changesCollector); final ViewRowIdsOrderedSelection defaultSelection; if (!facetFilters.isEmpty()) { defaultSelection = viewDataRepository.addRemoveChangedRows( selections.getDefaultSelection(), facetFilters, rowIds, changesCollector); } else { defaultSelection = defaultSelectionBeforeFacetsFiltering; } return selections.withDefaultSelection(defaultSelectionBeforeFacetsFiltering, defaultSelection); } public ViewRowIdsOrderedSelection getOrderedSelection(@Nullable final DocumentQueryOrderByList orderBys) { if(orderBys == null || orderBys.isEmpty()) { return getDefaultSelection(); } return computeCurrentSelections(selections -> computeOrderBySelectionIfAbsent(selections, orderBys)) .getSelection(orderBys); } private ViewRowIdsOrderedSelections computeOrderBySelectionIfAbsent( @NonNull final ViewRowIdsOrderedSelections selections, @Nullable final DocumentQueryOrderByList orderBys) { return selections.withOrderBysSelectionIfAbsent( orderBys, this::createSelectionFromSelection); } private ViewRowIdsOrderedSelection createSelectionFromSelection( @NonNull final ViewRowIdsOrderedSelection fromSelection, @Nullable final DocumentQueryOrderByList orderBys) {
final ViewEvaluationCtx viewEvaluationCtx = getViewEvaluationCtx(); final SqlDocumentFilterConverterContext filterConverterContext = SqlDocumentFilterConverterContext.builder() .userRolePermissionsKey(viewEvaluationCtx.getPermissionsKey()) .build(); return viewDataRepository.createOrderedSelectionFromSelection( viewEvaluationCtx, fromSelection, DocumentFilterList.EMPTY, orderBys, filterConverterContext); } public Set<DocumentId> retainExistingRowIds(@NonNull final Set<DocumentId> rowIds) { if (rowIds.isEmpty()) { return ImmutableSet.of(); } return viewDataRepository.retrieveRowIdsMatchingFilters( viewId, DocumentFilterList.EMPTY, rowIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRowIdsOrderedSelectionsHolder.java
1
请在Spring Boot框架中完成以下Java代码
public class DemoApplicationConfiguration { private Logger logger = LoggerFactory.getLogger(DemoApplicationConfiguration.class); @Bean public UserDetailsService myUserDetailsService() { InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager(); String[][] usersGroupsAndRoles = { { "system", "password", "ROLE_ACTIVITI_USER" }, { "reviewer", "password", "ROLE_ACTIVITI_USER" }, { "admin", "password", "ROLE_ACTIVITI_ADMIN" }, }; for (String[] user : usersGroupsAndRoles) { List<String> authoritiesStrings = asList(Arrays.copyOfRange(user, 2, user.length)); logger.info( "> Registering new user: " + user[0] + " with the following Authorities[" + authoritiesStrings + "]" ); inMemoryUserDetailsManager.createUser( new User(
user[0], passwordEncoder().encode(user[1]), authoritiesStrings .stream() .map(s -> new SimpleGrantedAuthority(s)) .collect(Collectors.toList()) ) ); } return inMemoryUserDetailsManager; } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } }
repos\Activiti-develop\activiti-examples\activiti-api-basic-connector-example\src\main\java\org\activiti\examples\DemoApplicationConfiguration.java
2
请完成以下Java代码
public PrintPackage getPrintPackage() { return printPackage; } public PrintPackageInfo getPrintPackageInfo() { return printPackageInfo; } public PrintRequestAttributeSet getAttributes() { return attributes; } public String getPrintJobName() { return printJobName; } public void setPrintJobName(final String printJobName) { this.printJobName = printJobName; } public Printable getPrintable() { return printable; }
public void setPrintable(final Printable printable) { this.printable = printable; } public int getNumPages() { return numPages; } public void setNumPages(final int numPages) { this.numPages = numPages; } @Override public String toString() { return "PrintPackageRequest [" + "printPackage=" + printPackage + ", printPackageInfo=" + printPackageInfo + ", attributes=" + attributes + ", printService=" + printService + ", printJobName=" + printJobName + ", printable=" + printable + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing.client\src\main\java\de\metas\printing\client\engine\PrintPackageRequest.java
1
请完成以下Java代码
public void sendAppChatSocket(String userId) { } @Override public String getRoleCodeById(String id) { return null; } @Override public List<DictModel> queryRoleDictByCode(String roleCodes) { return null; } @Override public List<JSONObject> queryUserBySuperQuery(String superQuery, String matchType) { return null; } @Override public JSONObject queryUserById(String id) { return null; } @Override public List<JSONObject> queryDeptBySuperQuery(String superQuery, String matchType) { return null; } @Override public List<JSONObject> queryRoleBySuperQuery(String superQuery, String matchType) { return null; } @Override public List<String> selectUserIdByTenantId(String tenantId) { return null; } @Override public List<String> queryUserIdsByDeptIds(List<String> deptIds) { return null; } @Override public List<String> queryUserIdsByDeptPostIds(List<String> deptPostIds) { return List.of(); } @Override public List<String> queryUserAccountsByDeptIds(List<String> deptIds) { return null; } @Override public List<String> queryUserIdsByRoleds(List<String> roleCodes) { return null; } @Override public List<String> queryUsernameByIds(List<String> userIds) { return List.of(); } @Override
public List<String> queryUsernameByDepartPositIds(List<String> positionIds) { return null; } @Override public List<String> queryUserIdsByPositionIds(List<String> positionIds) { return null; } @Override public List<String> getUserAccountsByDepCode(String orgCode) { return null; } @Override public boolean dictTableWhiteListCheckBySql(String selectSql) { return false; } @Override public boolean dictTableWhiteListCheckByDict(String tableOrDictCode, String... fields) { return false; } @Override public void announcementAutoRelease(String dataId, String currentUserName) { } @Override public SysDepartModel queryCompByOrgCode(String orgCode) { return null; } @Override public SysDepartModel queryCompByOrgCodeAndLevel(String orgCode, Integer level) { return null; } @Override public Object runAiragFlow(AiragFlowDTO airagFlowDTO) { return null; } @Override public void uniPushMsgToUser(PushMessageDTO pushMessageDTO) { } @Override public String getDepartPathNameByOrgCode(String orgCode, String depId) { return ""; } @Override public List<String> queryUserIdsByCascadeDeptIds(List<String> deptIds) { return null; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-api\jeecg-system-cloud-api\src\main\java\org\jeecg\common\system\api\fallback\SysBaseAPIFallback.java
1
请完成以下Java代码
public List<VariableInstanceEntity> findVariableInstancesByExecutionIdAndVariableNames(String executionId, Collection<String> variableNames) { Map<String, Object> parameter = new HashMap<String, Object>(); parameter.put("executionId", executionId); parameter.put("variableNames", variableNames); return getDbEntityManager().selectList("selectVariablesByExecutionId", parameter); } @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByProcessInstanceId(String processInstanceId) { return getDbEntityManager().selectList("selectVariablesByProcessInstanceId", processInstanceId); } public List<VariableInstanceEntity> findVariableInstancesByCaseExecutionId(String caseExecutionId) { return findVariableInstancesByCaseExecutionIdAndVariableNames(caseExecutionId, null); } @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByCaseExecutionIdAndVariableNames(String caseExecutionId, Collection<String> variableNames) { Map<String, Object> parameter = new HashMap<String, Object>(); parameter.put("caseExecutionId", caseExecutionId); parameter.put("variableNames", variableNames); return getDbEntityManager().selectList("selectVariablesByCaseExecutionId", parameter); } public void deleteVariableInstanceByTask(TaskEntity task) { List<VariableInstanceEntity> variableInstances = task.variableStore.getVariables(); for (VariableInstanceEntity variableInstance: variableInstances) { variableInstance.delete(); } } public long findVariableInstanceCountByQueryCriteria(VariableInstanceQueryImpl variableInstanceQuery) { configureQuery(variableInstanceQuery);
return (Long) getDbEntityManager().selectOne("selectVariableInstanceCountByQueryCriteria", variableInstanceQuery); } @SuppressWarnings("unchecked") public List<VariableInstance> findVariableInstanceByQueryCriteria(VariableInstanceQueryImpl variableInstanceQuery, Page page) { configureQuery(variableInstanceQuery); return getDbEntityManager().selectList("selectVariableInstanceByQueryCriteria", variableInstanceQuery, page); } protected void configureQuery(VariableInstanceQueryImpl query) { getAuthorizationManager().configureVariableInstanceQuery(query); getTenantManager().configureQuery(query); } @SuppressWarnings("unchecked") public List<VariableInstanceEntity> findVariableInstancesByBatchId(String batchId) { Map<String, String> parameters = Collections.singletonMap("batchId", batchId); return getDbEntityManager().selectList("selectVariableInstancesByBatchId", parameters); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\VariableInstanceManager.java
1
请完成以下Java代码
protected void configureScriptEngines(String language, ScriptEngine scriptEngine) { if (ScriptingEngines.GROOVY_SCRIPTING_LANGUAGE.equals(language)) { configureGroovyScriptEngine(scriptEngine); } if (ScriptingEngines.GRAAL_JS_SCRIPT_ENGINE_NAME.equals(scriptEngine.getFactory().getEngineName())) { configureGraalJsScriptEngine(scriptEngine); } } /** * Allows providing custom configuration for the groovy script engine. * @param scriptEngine the groovy script engine to configure. */ protected void configureGroovyScriptEngine(ScriptEngine scriptEngine) { // make sure Groovy compiled scripts only hold weak references to java methods scriptEngine.getContext().setAttribute("#jsr223.groovy.engine.keep.globals", "weak", ScriptContext.ENGINE_SCOPE); } /** * Allows providing custom configuration for the Graal JS script engine. * @param scriptEngine the Graal JS script engine to configure. */ protected void configureGraalJsScriptEngine(ScriptEngine scriptEngine) {
ProcessEngineConfigurationImpl config = Context.getProcessEngineConfiguration(); if (config != null) { if (config.isConfigureScriptEngineHostAccess()) { // make sure Graal JS can provide access to the host and can lookup classes scriptEngine.getContext().setAttribute("polyglot.js.allowHostAccess", true, ScriptContext.ENGINE_SCOPE); scriptEngine.getContext().setAttribute("polyglot.js.allowHostClassLookup", true, ScriptContext.ENGINE_SCOPE); } if (config.isEnableScriptEngineLoadExternalResources()) { // make sure Graal JS can load external scripts scriptEngine.getContext().setAttribute("polyglot.js.allowIO", true, ScriptContext.ENGINE_SCOPE); } if (config.isEnableScriptEngineNashornCompatibility()) { // enable Nashorn compatibility mode scriptEngine.getContext().setAttribute("polyglot.js.nashorn-compat", true, ScriptContext.ENGINE_SCOPE); } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\scripting\engine\DefaultScriptEngineResolver.java
1
请在Spring Boot框架中完成以下Java代码
private Optional<JsonOrderPaymentCreateRequest> buildOrderPaymentCreateRequest(@NonNull final ImportOrdersRouteContext context) { final JsonPaymentMethod paymentMethod = context.getCompositeOrderNotNull().getJsonPaymentMethod(); final JsonOrderTransaction orderTransaction = context.getCompositeOrderNotNull().getOrderTransaction(); final JsonOrder order = context.getOrderNotNull().getJsonOrder(); final boolean isPaypalType = PaymentMethodType.PAY_PAL_PAYMENT_HANDLER.getValue().equals(paymentMethod.getShortName()); final boolean isPaid = TechnicalNameEnum.PAID.getValue().equals(orderTransaction.getStateMachine().getTechnicalName()); if (!(isPaypalType && isPaid)) { processLogger.logMessage("Order " + order.getOrderNumber() + " (ID=" + order.getId() + "): Not sending current payment to metasfresh; it would have to be 'paypal' and 'paid'!" + " PaymentId = " + orderTransaction.getId() + " paidStatus = " + isPaid + " paypalType = " + isPaypalType, JsonMetasfreshId.toValue(context.getPInstanceId())); return Optional.empty(); }
final String currencyCode = context.getCurrencyInfoProvider().getIsoCodeByCurrencyIdNotNull(order.getCurrencyId()); final String bPartnerIdentifier = context.getBPExternalIdentifier().getIdentifier(); return Optional.of(JsonOrderPaymentCreateRequest.builder() .orgCode(context.getOrgCode()) .externalPaymentId(orderTransaction.getId()) .bpartnerIdentifier(bPartnerIdentifier) .amount(orderTransaction.getAmount().getTotalPrice()) .currencyCode(currencyCode) .orderIdentifier(ExternalIdentifierFormat.formatOldStyleExternalId(order.getId())) .transactionDate(orderTransaction.getCreatedAt().toLocalDate()) .build()); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\de-metas-camel-shopware6\src\main\java\de\metas\camel\externalsystems\shopware6\order\processor\PaymentRequestProcessor.java
2
请完成以下Java代码
public TrackData1 createTrackData1() { return new TrackData1(); } /** * Create an instance of {@link TransactionAgents3 } * */ public TransactionAgents3 createTransactionAgents3() { return new TransactionAgents3(); } /** * Create an instance of {@link TransactionDates2 } * */ public TransactionDates2 createTransactionDates2() { return new TransactionDates2(); } /** * Create an instance of {@link TransactionIdentifier1 } * */ public TransactionIdentifier1 createTransactionIdentifier1() { return new TransactionIdentifier1(); } /** * Create an instance of {@link TransactionInterest3 } * */ public TransactionInterest3 createTransactionInterest3() { return new TransactionInterest3(); } /** * Create an instance of {@link TransactionParties3 } * */ public TransactionParties3 createTransactionParties3() { return new TransactionParties3(); } /** * Create an instance of {@link TransactionPrice3Choice } * */ public TransactionPrice3Choice createTransactionPrice3Choice() { return new TransactionPrice3Choice();
} /** * Create an instance of {@link TransactionQuantities2Choice } * */ public TransactionQuantities2Choice createTransactionQuantities2Choice() { return new TransactionQuantities2Choice(); } /** * Create an instance of {@link TransactionReferences3 } * */ public TransactionReferences3 createTransactionReferences3() { return new TransactionReferences3(); } /** * Create an instance of {@link YieldedOrValueType1Choice } * */ public YieldedOrValueType1Choice createYieldedOrValueType1Choice() { return new YieldedOrValueType1Choice(); } /** * 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:camt.053.001.04", 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.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_04\ObjectFactory.java
1
请完成以下Java代码
public Queue findQueueByTenantIdAndTopic(TenantId tenantId, String topic) { return DaoUtil.getData(queueRepository.findByTenantIdAndTopic(tenantId.getId(), topic)); } @Override public Queue findQueueByTenantIdAndName(TenantId tenantId, String name) { return DaoUtil.getData(queueRepository.findByTenantIdAndName(tenantId.getId(), name)); } @Override public List<Queue> findAllByTenantId(TenantId tenantId) { List<QueueEntity> entities = queueRepository.findByTenantId(tenantId.getId()); return DaoUtil.convertDataList(entities); } @Override public List<Queue> findAllMainQueues() { List<QueueEntity> entities = Lists.newArrayList(queueRepository.findAllByName(DataConstants.MAIN_QUEUE_NAME)); return DaoUtil.convertDataList(entities); } @Override
public List<Queue> findAllQueues() { List<QueueEntity> entities = Lists.newArrayList(queueRepository.findAll()); return DaoUtil.convertDataList(entities); } @Override public PageData<Queue> findQueuesByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(queueRepository .findByTenantId(tenantId.getId(), pageLink.getTextSearch(), DaoUtil.toPageable(pageLink))); } @Override public PageData<Queue> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return findQueuesByTenantId(tenantId, pageLink); } @Override public EntityType getEntityType() { return EntityType.QUEUE; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\queue\JpaQueueDao.java
1
请在Spring Boot框架中完成以下Java代码
public class DataEntry_Section { public DataEntry_Section() { Services.get(IProgramaticCalloutProvider.class).registerAnnotatedCallout(this); } @ModelChange(timings = ModelValidator.TYPE_BEFORE_DELETE) public void deleteChildRecords(@NonNull final I_DataEntry_Section dataEntrySectionRecord) { Services.get(IQueryBL.class) .createQueryBuilder(I_DataEntry_Line.class) .addEqualsFilter(I_DataEntry_Line.COLUMN_DataEntry_Section_ID, dataEntrySectionRecord.getDataEntry_Section_ID()) .create() .delete(); } @CalloutMethod(columnNames = I_DataEntry_Section.COLUMNNAME_DataEntry_SubTab_ID) public void setSeqNo(@NonNull final I_DataEntry_Section dataEntrySectionRecord) {
if (dataEntrySectionRecord.getDataEntry_SubTab_ID() <= 0) { return; } dataEntrySectionRecord.setSeqNo(maxSeqNo(dataEntrySectionRecord) + 10); } private int maxSeqNo(@NonNull final I_DataEntry_Section dataEntrySectionRecord) { return Services .get(IQueryBL.class) .createQueryBuilder(I_DataEntry_Section.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DataEntry_Section.COLUMN_DataEntry_SubTab_ID, dataEntrySectionRecord.getDataEntry_SubTab_ID()) .create() .maxInt(I_DataEntry_Tab.COLUMNNAME_SeqNo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\dataentry\layout\interceptor\DataEntry_Section.java
2
请完成以下Java代码
public class MaterialTrackingReportBL implements IMaterialTrackingReportBL { @Override public I_M_Material_Tracking_Report_Line createMaterialTrackingReportLine(final I_M_Material_Tracking_Report report, final I_M_InOutLine iol, final String lineAggregationKey) { final I_M_Material_Tracking_Report_Line newLine = InterfaceWrapperHelper.newInstance(I_M_Material_Tracking_Report_Line.class, iol); newLine.setM_Material_Tracking_Report(report); newLine.setM_Product_ID(iol.getM_Product_ID()); final I_M_AttributeSetInstance asi = createASIFromRef(iol); newLine.setM_AttributeSetInstance(asi); newLine.setLineAggregationKey(lineAggregationKey); return newLine; } private I_M_AttributeSetInstance createASIFromRef(final I_M_InOutLine iol) { final IDimensionspecDAO dimSpecDAO = Services.get(IDimensionspecDAO.class); final ISysConfigBL sysConfigBL = Services.get(ISysConfigBL.class); final String internalName = sysConfigBL.getValue(MaterialTrackingConstants.SYSCONFIG_M_Material_Tracking_Report_Dimension); final DimensionSpec dimensionSpec = dimSpecDAO.retrieveForInternalNameOrNull(internalName); Check.errorIf(dimensionSpec == null, "Unable to load DIM_Dimension_Spec record with InternalName={}", internalName); final I_M_AttributeSetInstance resultASI = dimensionSpec.createASIForDimensionSpec(iol.getM_AttributeSetInstance());
return resultASI; } @Override public void createMaterialTrackingReportLineAllocation(final I_M_Material_Tracking_Report_Line reportLine, final MaterialTrackingReportAgregationItem items) { final I_M_Material_Tracking_Report_Line_Alloc alloc = InterfaceWrapperHelper.newInstance(I_M_Material_Tracking_Report_Line_Alloc.class, reportLine); alloc.setM_Material_Tracking_Report_Line(reportLine); alloc.setPP_Order(items.getPPOrder()); alloc.setM_InOutLine(items.getInOutLine()); alloc.setM_Material_Tracking(items.getMaterialTracking()); if (items.getPPOrder() != null) { alloc.setQtyIssued(items.getQty()); } else { alloc.setQtyReceived(items.getQty()); } InterfaceWrapperHelper.save(alloc); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingReportBL.java
1
请完成以下Java代码
public void onDeviceDeleted(DeviceSessionContext sessionContext) { destroyDeviceSession(sessionContext); } public void onDeviceProfileUpdated(DeviceProfile deviceProfile, DeviceSessionContext sessionContext) { log.debug("Handling device profile {} update event for device {}", deviceProfile.getId(), sessionContext.getDeviceId()); updateDeviceSession(sessionContext, sessionContext.getDevice(), deviceProfile); } public void onSnmpTransportListChanged() { log.trace("SNMP transport list changed. Updating sessions"); List<DeviceId> deleted = new LinkedList<>(); for (DeviceId deviceId : allSnmpDevicesIds) { if (balancingService.isManagedByCurrentTransport(deviceId.getId())) { if (!sessions.containsKey(deviceId)) { Device device = protoEntityService.getDeviceById(deviceId); if (device != null) { log.info("SNMP device {} is now managed by current transport node", deviceId); establishDeviceSession(device); } else { deleted.add(deviceId); } } } else { Optional.ofNullable(sessions.get(deviceId)) .ifPresent(sessionContext -> { log.info("SNMP session for device {} is not managed by current transport node anymore", deviceId); destroyDeviceSession(sessionContext); }); }
} log.trace("Removing deleted SNMP devices: {}", deleted); allSnmpDevicesIds.removeAll(deleted); } public Collection<DeviceSessionContext> getSessions() { return sessions.values(); } @PreDestroy public void destroy() { snmpExecutor.shutdown(); } }
repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\SnmpTransportContext.java
1
请完成以下Java代码
@Nullable AnsiElement getElement(String postfix) { for (Enum<?> candidate : this.enums) { if (candidate.name().equals(postfix)) { return (AnsiElement) candidate; } } return null; } } /** * {@link Mapping} for {@link Ansi8BitColor}. */ private static class Ansi8BitColorMapping extends Mapping { private final IntFunction<Ansi8BitColor> factory; Ansi8BitColorMapping(String prefix, IntFunction<Ansi8BitColor> factory) { super(prefix); this.factory = factory; } @Override @Nullable AnsiElement getElement(String postfix) { if (containsOnlyDigits(postfix)) {
try { return this.factory.apply(Integer.parseInt(postfix)); } catch (IllegalArgumentException ex) { // Ignore } } return null; } private boolean containsOnlyDigits(String postfix) { for (int i = 0; i < postfix.length(); i++) { if (!Character.isDigit(postfix.charAt(i))) { return false; } } return !postfix.isEmpty(); } } }
repos\spring-boot-4.0.1\core\spring-boot\src\main\java\org\springframework\boot\ansi\AnsiPropertySource.java
1
请完成以下Java代码
private boolean isEndedContract(@NonNull final I_I_Flatrate_Term importRecord) { final Timestamp contractEndDate = importRecord.getEndDate(); final Timestamp today = SystemTime.asDayTimestamp(); return contractEndDate != null && today.after(contractEndDate); } private void endContractIfNeeded(@NonNull final I_I_Flatrate_Term importRecord, @NonNull final I_C_Flatrate_Term contract) { if (isEndedContract(importRecord)) { contract.setContractStatus(X_C_Flatrate_Term.CONTRACTSTATUS_Quit); contract.setNoticeDate(contract.getEndDate()); contract.setIsAutoRenew(false); contract.setProcessed(true); contract.setDocAction(X_C_Flatrate_Term.DOCACTION_None); contract.setDocStatus(X_C_Flatrate_Term.DOCSTATUS_Completed); } }
private void setTaxCategoryAndIsTaxIncluded(@NonNull final I_C_Flatrate_Term newTerm) { final IPricingResult pricingResult = calculateFlatrateTermPrice(newTerm); newTerm.setC_TaxCategory_ID(TaxCategoryId.toRepoId(pricingResult.getTaxCategoryId())); newTerm.setIsTaxIncluded(pricingResult.isTaxIncluded()); } private IPricingResult calculateFlatrateTermPrice(@NonNull final I_C_Flatrate_Term newTerm) { return FlatrateTermPricing.builder() .termRelatedProductId(ProductId.ofRepoId(newTerm.getM_Product_ID())) .qty(newTerm.getPlannedQtyPerUnit()) .term(newTerm) .priceDate(TimeUtil.asLocalDate(newTerm.getStartDate())) .build() .computeOrThrowEx(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\flatrate\impexp\FlatrateTermImporter.java
1
请完成以下Java代码
public void setDataEntry_SubTab(de.metas.dataentry.model.I_DataEntry_SubTab DataEntry_SubTab) { set_ValueFromPO(COLUMNNAME_DataEntry_SubTab_ID, de.metas.dataentry.model.I_DataEntry_SubTab.class, DataEntry_SubTab); } /** Set Unterregister. @param DataEntry_SubTab_ID Unterregister */ @Override public void setDataEntry_SubTab_ID (int DataEntry_SubTab_ID) { if (DataEntry_SubTab_ID < 1) set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, null); else set_ValueNoCheck (COLUMNNAME_DataEntry_SubTab_ID, Integer.valueOf(DataEntry_SubTab_ID)); } /** Get Unterregister. @return Unterregister */ @Override public int getDataEntry_SubTab_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_DataEntry_SubTab_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Datensatz-ID. @param Record_ID
Direct internal record ID */ @Override public void setRecord_ID (int Record_ID) { if (Record_ID < 0) set_ValueNoCheck (COLUMNNAME_Record_ID, null); else set_ValueNoCheck (COLUMNNAME_Record_ID, Integer.valueOf(Record_ID)); } /** Get Datensatz-ID. @return Direct internal record ID */ @Override public int getRecord_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_Record_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\dataentry\model\X_DataEntry_Record.java
1
请完成以下Java代码
public class TelegramNotifier extends AbstractContentNotifier { private static final String DEFAULT_MESSAGE = "<strong>#{name}</strong>/#{id} is <strong>#{status}</strong>"; private RestTemplate restTemplate; /** * base url for telegram (i.e. https://api.telegram.org) */ private String apiUrl = "https://api.telegram.org"; /** * Unique identifier for the target chat or username of the target channel */ @Nullable private String chatId; /** * The token identifying und authorizing your Telegram bot (e.g. * `123456:ABC-DEF1234ghIkl-zyx57W2v1u123ew11`) */ @Nullable private String authToken; /** * Send Markdown or HTML, if you want Telegram apps to show bold, italic, fixed-width * text or inline URLs in your bot's message. */ private String parseMode = "HTML"; /** * If true users will receive a notification with no sound. */ private boolean disableNotify = false; public TelegramNotifier(InstanceRepository repository, RestTemplate restTemplate) { super(repository); this.restTemplate = restTemplate; } @Override protected Mono<Void> doNotify(InstanceEvent event, Instance instance) { return Mono .fromRunnable(() -> restTemplate.getForObject(buildUrl(), Void.class, createMessage(event, instance))); } protected String buildUrl() { return String.format("%s/bot%s/sendmessage?chat_id={chat_id}&text={text}&parse_mode={parse_mode}" + "&disable_notification={disable_notification}", this.apiUrl, this.authToken); } private Map<String, Object> createMessage(InstanceEvent event, Instance instance) { Map<String, Object> parameters = new HashMap<>(); parameters.put("chat_id", this.chatId); parameters.put("parse_mode", this.parseMode); parameters.put("disable_notification", this.disableNotify); parameters.put("text", createContent(event, instance)); return parameters; } @Override protected String getDefaultMessage() { return DEFAULT_MESSAGE; } public void setRestTemplate(RestTemplate restTemplate) { this.restTemplate = restTemplate; } public String getApiUrl() { return apiUrl; }
public void setApiUrl(String apiUrl) { this.apiUrl = apiUrl; } @Nullable public String getChatId() { return chatId; } public void setChatId(@Nullable String chatId) { this.chatId = chatId; } @Nullable public String getAuthToken() { return authToken; } public void setAuthToken(@Nullable String authToken) { this.authToken = authToken; } public boolean isDisableNotify() { return disableNotify; } public void setDisableNotify(boolean disableNotify) { this.disableNotify = disableNotify; } public String getParseMode() { return parseMode; } public void setParseMode(String parseMode) { this.parseMode = parseMode; } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\notify\TelegramNotifier.java
1
请完成以下Java代码
public void close() { // No-op } /** * Get the addTypeInfo property. * @return the addTypeInfo */ public boolean isAddTypeInfo() { return this.addTypeInfo; } /** * Set to false to disable adding type info headers. * @param addTypeInfo true to add headers */ public void setAddTypeInfo(boolean addTypeInfo) { this.addTypeInfo = addTypeInfo; } /**
* Set a charset to use when converting {@link String} to byte[]. Default UTF-8. * @param charset the charset. */ public void setCharset(Charset charset) { Assert.notNull(charset, "'charset' cannot be null"); this.charset = charset; } /** * Get the configured charset. * @return the charset. */ public Charset getCharset() { return this.charset; } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\support\serializer\ToStringSerializer.java
1
请完成以下Java代码
public BigDecimal getVolume() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Volume); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWarehouse_temperature (final @Nullable java.lang.String Warehouse_temperature) { set_Value (COLUMNNAME_Warehouse_temperature, Warehouse_temperature); } @Override public java.lang.String getWarehouse_temperature() { return get_ValueAsString(COLUMNNAME_Warehouse_temperature); } @Override public void setWeight (final @Nullable BigDecimal Weight) { set_Value (COLUMNNAME_Weight, Weight); } @Override public BigDecimal getWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Weight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setWeight_UOM_ID (final int Weight_UOM_ID) {
if (Weight_UOM_ID < 1) set_Value (COLUMNNAME_Weight_UOM_ID, null); else set_Value (COLUMNNAME_Weight_UOM_ID, Weight_UOM_ID); } @Override public int getWeight_UOM_ID() { return get_ValueAsInt(COLUMNNAME_Weight_UOM_ID); } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product.java
1
请完成以下Java代码
public int getPOD_ID() { return get_ValueAsInt(COLUMNNAME_POD_ID); } @Override public org.compiere.model.I_C_Postal getPOL() { return get_ValueAsPO(COLUMNNAME_POL_ID, org.compiere.model.I_C_Postal.class); } @Override public void setPOL(final org.compiere.model.I_C_Postal POL) { set_ValueFromPO(COLUMNNAME_POL_ID, org.compiere.model.I_C_Postal.class, POL); } @Override public void setPOL_ID (final int POL_ID) { if (POL_ID < 1) set_Value (COLUMNNAME_POL_ID, null); else set_Value (COLUMNNAME_POL_ID, POL_ID); } @Override public int getPOL_ID() { return get_ValueAsInt(COLUMNNAME_POL_ID); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setSalesRep_ID (final int SalesRep_ID) { if (SalesRep_ID < 1) set_Value (COLUMNNAME_SalesRep_ID, null); else set_Value (COLUMNNAME_SalesRep_ID, SalesRep_ID); } @Override public int getSalesRep_ID() { return get_ValueAsInt(COLUMNNAME_SalesRep_ID); } @Override public void setShipper_BPartner_ID (final int Shipper_BPartner_ID) { if (Shipper_BPartner_ID < 1) set_Value (COLUMNNAME_Shipper_BPartner_ID, null); else set_Value (COLUMNNAME_Shipper_BPartner_ID, Shipper_BPartner_ID); } @Override
public int getShipper_BPartner_ID() { return get_ValueAsInt(COLUMNNAME_Shipper_BPartner_ID); } @Override public void setShipper_Location_ID (final int Shipper_Location_ID) { if (Shipper_Location_ID < 1) set_Value (COLUMNNAME_Shipper_Location_ID, null); else set_Value (COLUMNNAME_Shipper_Location_ID, Shipper_Location_ID); } @Override public int getShipper_Location_ID() { return get_ValueAsInt(COLUMNNAME_Shipper_Location_ID); } @Override public void setTrackingID (final @Nullable java.lang.String TrackingID) { set_Value (COLUMNNAME_TrackingID, TrackingID); } @Override public java.lang.String getTrackingID() { return get_ValueAsString(COLUMNNAME_TrackingID); } @Override public void setVesselName (final @Nullable java.lang.String VesselName) { set_Value (COLUMNNAME_VesselName, VesselName); } @Override public java.lang.String getVesselName() { return get_ValueAsString(COLUMNNAME_VesselName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\de\metas\shipping\model\X_M_ShipperTransportation.java
1
请完成以下Java代码
public I_M_InventoryLine getM_InventoryLine() throws RuntimeException { return (I_M_InventoryLine)MTable.get(getCtx(), I_M_InventoryLine.Table_Name) .getPO(getM_InventoryLine_ID(), get_TrxName()); } /** Set Phys.Inventory Line. @param M_InventoryLine_ID Unique line in an Inventory document */ public void setM_InventoryLine_ID (int M_InventoryLine_ID) { if (M_InventoryLine_ID < 1) set_Value (COLUMNNAME_M_InventoryLine_ID, null); else set_Value (COLUMNNAME_M_InventoryLine_ID, Integer.valueOf(M_InventoryLine_ID)); } /** Get Phys.Inventory Line. @return Unique line in an Inventory document */ public int getM_InventoryLine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_InventoryLine_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Processed. @param Processed The document has been processed */ public void setProcessed (boolean Processed) { set_Value (COLUMNNAME_Processed, Boolean.valueOf(Processed)); } /** Get Processed. @return The document has been processed */ public boolean isProcessed () { Object oo = get_Value(COLUMNNAME_Processed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Scrapped Quantity. @param ScrappedQty The Quantity scrapped due to QA issues */ public void setScrappedQty (BigDecimal ScrappedQty) { set_Value (COLUMNNAME_ScrappedQty, ScrappedQty); }
/** Get Scrapped Quantity. @return The Quantity scrapped due to QA issues */ public BigDecimal getScrappedQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ScrappedQty); if (bd == null) return Env.ZERO; return bd; } /** Set Target Quantity. @param TargetQty Target Movement Quantity */ public void setTargetQty (BigDecimal TargetQty) { set_ValueNoCheck (COLUMNNAME_TargetQty, TargetQty); } /** Get Target Quantity. @return Target Movement Quantity */ public BigDecimal getTargetQty () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_TargetQty); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_InOutLineConfirm.java
1
请完成以下Java代码
public boolean isInternationalDelivery() { return get_ValueAsBoolean(COLUMNNAME_InternationalDelivery); } @Override public org.compiere.model.I_M_Package getM_Package() { return get_ValueAsPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class); } @Override public void setM_Package(final org.compiere.model.I_M_Package M_Package) { set_ValueFromPO(COLUMNNAME_M_Package_ID, org.compiere.model.I_M_Package.class, M_Package); } @Override public void setM_Package_ID (final int M_Package_ID) { if (M_Package_ID < 1) set_Value (COLUMNNAME_M_Package_ID, null); else set_Value (COLUMNNAME_M_Package_ID, M_Package_ID); } @Override public int getM_Package_ID() { return get_ValueAsInt(COLUMNNAME_M_Package_ID); } @Override public org.compiere.model.I_M_Shipper getM_Shipper() { return get_ValueAsPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class); } @Override public void setM_Shipper(final org.compiere.model.I_M_Shipper M_Shipper) { set_ValueFromPO(COLUMNNAME_M_Shipper_ID, org.compiere.model.I_M_Shipper.class, M_Shipper); } @Override 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_ShipperTransportation_ID (final int M_ShipperTransportation_ID) { if (M_ShipperTransportation_ID < 1)
set_Value (COLUMNNAME_M_ShipperTransportation_ID, null); else set_Value (COLUMNNAME_M_ShipperTransportation_ID, M_ShipperTransportation_ID); } @Override public int getM_ShipperTransportation_ID() { return get_ValueAsInt(COLUMNNAME_M_ShipperTransportation_ID); } @Override public void setNetWeightKg (final @Nullable BigDecimal NetWeightKg) { set_Value (COLUMNNAME_NetWeightKg, NetWeightKg); } @Override public BigDecimal getNetWeightKg() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_NetWeightKg); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPackageDescription (final @Nullable java.lang.String PackageDescription) { set_Value (COLUMNNAME_PackageDescription, PackageDescription); } @Override public java.lang.String getPackageDescription() { return get_ValueAsString(COLUMNNAME_PackageDescription); } @Override public void setPdfLabelData (final @Nullable byte[] PdfLabelData) { set_Value (COLUMNNAME_PdfLabelData, PdfLabelData); } @Override public byte[] getPdfLabelData() { return (byte[])get_Value(COLUMNNAME_PdfLabelData); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java-gen\de\metas\shipper\gateway\dhl\model\X_DHL_ShipmentOrder.java
1
请在Spring Boot框架中完成以下Java代码
public class UserService { @Autowired UserRepository userRepository; public ResponseEntity<?> saveUserProfile(UserPrincipal userPrincipal, UserProfile userProfileForm){ Optional<User> userDto = userRepository.findById(userPrincipal.getId()); User user = userDto.orElse(null); if(user !=null && user.getPhone().equals(userProfileForm.getPhone()) && userRepository.existsByPhone(userProfileForm.getPhone())) return new ResponseEntity<>( new ApiResponse(false, "Please, you may show phone number for register!, Or show other number"), HttpStatus.BAD_REQUEST); if(user != null && user.getEmail() !=null && !user.getEmail().equals(userProfileForm.getEmail()) && userRepository.existsByEmail(userProfileForm.getEmail())) return new ResponseEntity<>( new ApiResponse (false, "Please email you may register, or different one."), HttpStatus.BAD_REQUEST); if (user != null) { user.setSurname(userProfileForm.getSurname()); user.setName(userProfileForm.getName()); user.setLastname(userProfileForm.getLastname()); user.setEmail(userProfileForm.getEmail());
user.setPhone(userProfileForm.getPhone()); userRepository.save(user); return new ResponseEntity<>(new ApiResponse(true, "change already saved"), HttpStatus.OK); } else { return new ResponseEntity<>( new ApiResponse(false, "Oops, issues! Please update page!"), HttpStatus.BAD_REQUEST); } } public Boolean saveCity(UserPrincipal userPrincipal, String city){ Optional<User> userDto = userRepository.findById(userPrincipal.getId()); User user = userDto.orElse(null); if(user!= null) { user.setCity(city); userRepository.save(user); return true; } else{ return false; } } }
repos\SpringBoot-Projects-FullStack-master\Part-9.SpringBoot-React-Projects\Project-2.SpringBoot-React-ShoppingMall\fullstack\backend\src\main\java\com\urunov\service\UserService.java
2
请在Spring Boot框架中完成以下Java代码
public class WFProcessHeaderProperty { @NonNull ITranslatableString caption; @NonNull ITranslatableString value; public boolean isValueNotBlank() {return !TranslatableStrings.isBlank(value);} @SuppressWarnings("unused") public static class WFProcessHeaderPropertyBuilder { public WFProcessHeaderPropertyBuilder value(final ITranslatableString value) { this.value = value; return this; } public WFProcessHeaderPropertyBuilder value(final String value) { return value(TranslatableStrings.anyLanguage(value)); }
public WFProcessHeaderPropertyBuilder value(final ZonedDateTime value) { return value(TranslatableStrings.dateAndTime(value)); } @NonNull public WFProcessHeaderPropertyBuilder value(@NonNull final LocalDate value) { return value(TranslatableStrings.date(value)); } public WFProcessHeaderPropertyBuilder value(final int value) { return value(TranslatableStrings.number(value)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.workflow.rest-api\src\main\java\de\metas\workflow\rest_api\model\WFProcessHeaderProperty.java
2
请在Spring Boot框架中完成以下Java代码
public abstract class BatchReportEntryWrapper implements IStatementLineWrapper { @NonNull CurrencyRepository currencyRepository; protected BatchReportEntryWrapper(@NonNull final CurrencyRepository currencyRepository) { this.currencyRepository = currencyRepository; } @Override @NonNull public ImmutableSet<String> getDocumentReferenceCandidates() { final List<String> docRefCand = new ArrayList<>(); docRefCand.addAll(getUnstructuredRemittanceInfoList()); docRefCand.addAll(getLineDescriptionList()); return ImmutableSet.copyOf(docRefCand); } @Override @NonNull public String getUnstructuredRemittanceInfo() { return getUnstructuredRemittanceInfo("\n"); } @Override @NonNull public String getLineDescription() { return getLineDescription("\n"); } @Override @NonNull public Amount getStatementAmount() { final BigDecimal value = getStatementAmountValue(); final CurrencyCode currencyCode = CurrencyCode.ofThreeLetterCode(getCcy()); return Amount.of(value, currencyCode); } @NonNull protected CurrencyId getCurrencyIdByCurrencyCode(@NonNull final CurrencyCode currencyCode) { return currencyRepository.getCurrencyIdByCurrencyCode(currencyCode); } @NonNull private BigDecimal getStatementAmountValue() { return Optional.ofNullable(getAmtValue())
.map(value -> isCRDT() ? value : value.negate()) .orElse(BigDecimal.ZERO); } @NonNull protected abstract String getUnstructuredRemittanceInfo(@NonNull final String delimiter); @NonNull protected abstract List<String> getUnstructuredRemittanceInfoList(); @NonNull protected abstract String getLineDescription(@NonNull final String delimiter); @NonNull protected abstract List<String> getLineDescriptionList(); @Nullable protected abstract String getCcy(); @Nullable protected abstract BigDecimal getAmtValue(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java\de\metas\banking\camt53\wrapper\BatchReportEntryWrapper.java
2
请在Spring Boot框架中完成以下Java代码
protected Optional<String> getDurableClientId() { return Optional.ofNullable(this.durableClientId) .filter(StringUtils::hasText); } protected Integer getDurableClientTimeout() { return this.durableClientTimeout != null ? this.durableClientTimeout : DEFAULT_DURABLE_CLIENT_TIMEOUT; } protected Boolean getKeepAlive() { return this.keepAlive != null ? this.keepAlive : DEFAULT_KEEP_ALIVE; } protected Boolean getReadyForEvents() { return this.readyForEvents != null ? this.readyForEvents : DEFAULT_READY_FOR_EVENTS; } protected Logger getLogger() { return this.logger; } @Bean ClientCacheConfigurer clientCacheDurableClientConfigurer() { return (beanName, clientCacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> { clientCacheFactoryBean.setDurableClientId(durableClientId); clientCacheFactoryBean.setDurableClientTimeout(getDurableClientTimeout()); clientCacheFactoryBean.setKeepAlive(getKeepAlive());
clientCacheFactoryBean.setReadyForEvents(getReadyForEvents()); }); } @Bean PeerCacheConfigurer peerCacheDurableClientConfigurer() { return (beanName, cacheFactoryBean) -> getDurableClientId().ifPresent(durableClientId -> { Logger logger = getLogger(); if (logger.isWarnEnabled()) { logger.warn("Durable Client ID [{}] was set on a peer Cache instance, which will not have any effect", durableClientId); } }); } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\DurableClientConfiguration.java
2
请在Spring Boot框架中完成以下Java代码
public String getBankType() { return bankType; } public void setBankType(String bankType) { this.bankType = bankType; } public Date getOrderTime() { return orderTime; } public void setOrderTime(Date orderTime) { this.orderTime = orderTime; } public Date getBankTradeTime() { return bankTradeTime; } public void setBankTradeTime(Date bankTradeTime) { this.bankTradeTime = bankTradeTime; } public String getBankOrderNo() { return bankOrderNo; } public void setBankOrderNo(String bankOrderNo) { this.bankOrderNo = bankOrderNo; } public String getBankTrxNo() { return bankTrxNo; } public void setBankTrxNo(String bankTrxNo) {
this.bankTrxNo = bankTrxNo; } public String getBankTradeStatus() { return bankTradeStatus; } public void setBankTradeStatus(String bankTradeStatus) { this.bankTradeStatus = bankTradeStatus; } public BigDecimal getBankAmount() { return bankAmount; } public void setBankAmount(BigDecimal bankAmount) { this.bankAmount = bankAmount; } public BigDecimal getBankRefundAmount() { return bankRefundAmount; } public void setBankRefundAmount(BigDecimal bankRefundAmount) { this.bankRefundAmount = bankRefundAmount; } public BigDecimal getBankFee() { return bankFee; } public void setBankFee(BigDecimal bankFee) { this.bankFee = bankFee; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\vo\ReconciliationEntityVo.java
2
请完成以下Java代码
public Builder append(@NonNull final IStringExpression sqlToAppend) { sql.append(sqlToAppend); return this; } public Builder append(@Nullable final String sqlToAppend) { if (sqlToAppend != null) { sql.append(sqlToAppend); } return this; } public Builder appendSqlList(@NonNull final String sqlColumnName, @NonNull final Collection<?> values) { final String sqlToAppend = DB.buildSqlList(sqlColumnName, values, sqlParams);
sql.append(sqlToAppend); return this; } public boolean isEmpty() { return sql.isEmpty() && sqlParams.isEmpty(); } public Builder wrap(@NonNull final IStringExpressionWrapper wrapper) { sql.wrap(wrapper); return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\descriptor\SqlAndParamsExpression.java
1
请完成以下Java代码
protected ConditionEvaluationBuilder createConditionEvaluationBuilder(EvaluationConditionDto conditionDto) { RuntimeService runtimeService = getProcessEngine().getRuntimeService(); ObjectMapper objectMapper = getObjectMapper(); VariableMap variables = VariableValueDto.toMap(conditionDto.getVariables(), getProcessEngine(), objectMapper); ConditionEvaluationBuilder builder = runtimeService.createConditionEvaluation(); if (variables != null && !variables.isEmpty()) { builder.setVariables(variables); } if (conditionDto.getBusinessKey() != null) { builder.processInstanceBusinessKey(conditionDto.getBusinessKey());
} if (conditionDto.getProcessDefinitionId() != null) { builder.processDefinitionId(conditionDto.getProcessDefinitionId()); } if (conditionDto.getTenantId() != null) { builder.tenantId(conditionDto.getTenantId()); } else if (conditionDto.isWithoutTenantId()) { builder.withoutTenantId(); } return builder; } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\ConditionRestServiceImpl.java
1
请完成以下Java代码
protected int get_AccessLevel() { return accessLevel.intValue(); } /** Load Meta Data */ protected POInfo initPO (Properties ctx) { POInfo poi = POInfo.getPOInfo (ctx, Table_ID, get_TrxName()); return poi; } public String toString() { StringBuffer sb = new StringBuffer ("X_ImpEx_Connector[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Beschreibung. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Konnektor. @param ImpEx_Connector_ID Konnektor */ public void setImpEx_Connector_ID (int ImpEx_Connector_ID) { if (ImpEx_Connector_ID < 1) set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, null); else set_ValueNoCheck (COLUMNNAME_ImpEx_Connector_ID, Integer.valueOf(ImpEx_Connector_ID)); } /** Get Konnektor. @return Konnektor */ public int getImpEx_Connector_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_Connector_ID); if (ii == null) return 0; return ii.intValue(); } public de.metas.impex.model.I_ImpEx_ConnectorType getImpEx_ConnectorType() throws RuntimeException { return (de.metas.impex.model.I_ImpEx_ConnectorType)MTable.get(getCtx(), de.metas.impex.model.I_ImpEx_ConnectorType.Table_Name) .getPO(getImpEx_ConnectorType_ID(), get_TrxName()); } /** Set Konnektor-Typ. @param ImpEx_ConnectorType_ID Konnektor-Typ */ public void setImpEx_ConnectorType_ID (int ImpEx_ConnectorType_ID) { if (ImpEx_ConnectorType_ID < 1) set_Value (COLUMNNAME_ImpEx_ConnectorType_ID, null); else set_Value (COLUMNNAME_ImpEx_ConnectorType_ID, Integer.valueOf(ImpEx_ConnectorType_ID)); } /** Get Konnektor-Typ. @return Konnektor-Typ */ public int getImpEx_ConnectorType_ID ()
{ Integer ii = (Integer)get_Value(COLUMNNAME_ImpEx_ConnectorType_ID); if (ii == null) return 0; return ii.intValue(); } /** 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.swat\de.metas.swat.base\src\main\java-gen\de\metas\impex\model\X_ImpEx_Connector.java
1
请完成以下Java代码
private ViewChangesCollector getParentOrNull() { final ViewChangesCollector threadLocalCollector = getCurrentOrNull(); if (threadLocalCollector != null && threadLocalCollector != this) { return threadLocalCollector; } return null; } void flush() { final ImmutableList<ViewChanges> changesList = getAndClean(); if (changesList.isEmpty()) { return; } // // Try flushing to parent collector if any final ViewChangesCollector parentCollector = getParentOrNull(); if (parentCollector != null) { logger.trace("Flushing {} to parent collector: {}", this, parentCollector); changesList.forEach(parentCollector::collectFromChanges); } // // Fallback: flush to websocket else { logger.trace("Flushing {} to websocket", this); final ImmutableList<JSONViewChanges> jsonChangeEvents = changesList.stream() .filter(ViewChanges::hasChanges) .map(JSONViewChanges::of) .collect(ImmutableList.toImmutableList()); sendToWebsocket(jsonChangeEvents); } } private void autoflushIfEnabled() {
if (!autoflush) { return; } flush(); } private ImmutableList<ViewChanges> getAndClean() { if (viewChangesMap.isEmpty()) { return ImmutableList.of(); } final ImmutableList<ViewChanges> changesList = ImmutableList.copyOf(viewChangesMap.values()); viewChangesMap.clear(); return changesList; } private void sendToWebsocket(@NonNull final List<JSONViewChanges> jsonChangeEvents) { if (jsonChangeEvents.isEmpty()) { return; } WebsocketSender websocketSender = _websocketSender; if (websocketSender == null) { websocketSender = this._websocketSender = SpringContextHolder.instance.getBean(WebsocketSender.class); } try { websocketSender.convertAndSend(jsonChangeEvents); logger.debug("Sent to websocket: {}", jsonChangeEvents); } catch (final Exception ex) { logger.warn("Failed sending to websocket {}: {}", jsonChangeEvents, ex); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\event\ViewChangesCollector.java
1
请完成以下Java代码
public BigDecimal getValue() { return _netAmtToInvoice; } /** * Asserts aggregated net amount to invoice equals with given expected value (if set). * * The expected amount is set using {@link #setNetAmtToInvoiceExpected(BigDecimal)}. * * @see #assertExpectedNetAmtToInvoice(BigDecimal) */ public void assertExpectedNetAmtToInvoiceIfSet() { if (_netAmtToInvoiceExpected == null) { return; } assertExpectedNetAmtToInvoice(_netAmtToInvoiceExpected); } /** * Asserts aggregated net amount to invoice equals with given expected value. * * If it's not equal, an error message will be logged to {@link ILoggable}. * * @throws AdempiereException if the checksums are not equal and {@link #isFailIfNetAmtToInvoiceChecksumNotMatch()}. */ public void assertExpectedNetAmtToInvoice(@NonNull final BigDecimal netAmtToInvoiceExpected) { Check.assume(netAmtToInvoiceExpected.signum() != 0, "netAmtToInvoiceExpected != 0"); final BigDecimal netAmtToInvoiceActual = getValue(); if (netAmtToInvoiceExpected.compareTo(netAmtToInvoiceActual) != 0) { final String errmsg = "NetAmtToInvoice checksum not match" + "\n Expected: " + netAmtToInvoiceExpected + "\n Actual: " + netAmtToInvoiceActual
+ "\n Invoice candidates count: " + _countInvoiceCandidates; Loggables.addLog(errmsg); if (isFailIfNetAmtToInvoiceChecksumNotMatch()) { throw new AdempiereException(errmsg); } } } /** * @return true if we shall fail if the net amount to invoice checksum does not match. */ public final boolean isFailIfNetAmtToInvoiceChecksumNotMatch() { final boolean failIfNetAmtToInvoiceChecksumNotMatchDefault = true; return Services.get(ISysConfigBL.class).getBooleanValue(SYSCONFIG_FailIfNetAmtToInvoiceChecksumNotMatch, failIfNetAmtToInvoiceChecksumNotMatchDefault); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\ICNetAmtToInvoiceChecker.java
1
请完成以下Java代码
public static void main(String[] args) throws IOException { Selector selector = Selector.open(); ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.bind(new InetSocketAddress("localhost", 5454)); serverSocket.configureBlocking(false); serverSocket.register(selector, SelectionKey.OP_ACCEPT); ByteBuffer buffer = ByteBuffer.allocate(256); while (true) { selector.select(); Set<SelectionKey> selectedKeys = selector.selectedKeys(); Iterator<SelectionKey> iter = selectedKeys.iterator(); while (iter.hasNext()) { SelectionKey key = iter.next(); if (key.isAcceptable()) { register(selector, serverSocket); } if (key.isReadable()) { answerWithEcho(buffer, key); } iter.remove(); } } } private static void answerWithEcho(ByteBuffer buffer, SelectionKey key) throws IOException { SocketChannel client = (SocketChannel) key.channel();
int r = client.read(buffer); if (r == -1 || new String(buffer.array()).trim() .equals(POISON_PILL)) { client.close(); System.out.println("Not accepting client messages anymore"); } else { buffer.flip(); client.write(buffer); buffer.clear(); } } private static void register(Selector selector, ServerSocketChannel serverSocket) throws IOException { SocketChannel client = serverSocket.accept(); client.configureBlocking(false); client.register(selector, SelectionKey.OP_READ); } public static Process start() throws IOException, InterruptedException { String javaHome = System.getProperty("java.home"); String javaBin = javaHome + File.separator + "bin" + File.separator + "java"; String classpath = System.getProperty("java.class.path"); String className = EchoServer.class.getCanonicalName(); ProcessBuilder builder = new ProcessBuilder(javaBin, "-cp", classpath, className); return builder.start(); } }
repos\tutorials-master\core-java-modules\core-java-nio\src\main\java\com\baeldung\selector\EchoServer.java
1
请完成以下Java代码
public static IAllocationResult nullResult() { return NullAllocationResult.instance; } /** * Creates an immutable allocation result. For cross-package use. * * @return {@link AllocationResult} */ public static IAllocationResult createQtyAllocationResult(final BigDecimal qtyToAllocate, final BigDecimal qtyAllocated, final List<IHUTransactionCandidate> trxs, final List<IHUTransactionAttribute> attributeTrxs) { return new AllocationResult(qtyToAllocate, qtyAllocated, trxs, attributeTrxs); } @Nullable public static Object getReferencedModel(final IAllocationRequest request) { final ITableRecordReference tableRecord = request.getReference(); if (tableRecord == null) { return null; } final IContextAware context = request.getHuContext(); return tableRecord.getModel(context); } /** * Gets relative request qty (negated if deallocation). */ public static Quantity getQuantity( @NonNull final IAllocationRequest request, @NonNull final AllocationDirection direction) { return request .getQuantity() // => Quantity (absolute) .negateIf(direction.isOutboundDeallocation()); // => Quantity (relative) } /** * Use this to create a new allocation request, using the given request as template. */ public static IAllocationRequestBuilder derive(@NonNull final IAllocationRequest request) { return builder().setBaseAllocationRequest(request); }
@Nullable private static BPartnerId getBPartnerId(final IAllocationRequest request) { final Object referencedModel = AllocationUtils.getReferencedModel(request); if (referencedModel == null) { return null; } final Integer bpartnerId = InterfaceWrapperHelper.getValueOrNull(referencedModel, I_M_HU_PI_Item.COLUMNNAME_C_BPartner_ID); return BPartnerId.ofRepoIdOrNull(bpartnerId); } /** * Creates and configures an {@link IHUBuilder} based on the given <code>request</code> (bPartner and date). * * @return HU builder */ public static IHUBuilder createHUBuilder(final IAllocationRequest request) { final IHUContext huContext = request.getHuContext(); final IHUBuilder huBuilder = Services.get(IHandlingUnitsDAO.class).createHUBuilder(huContext); huBuilder.setDate(request.getDate()); huBuilder.setBPartnerId(getBPartnerId(request)); // TODO: huBuilder.setC_BPartner_Location if any // TODO: set the HU Storage from context to builder return huBuilder; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\AllocationUtils.java
1
请在Spring Boot框架中完成以下Java代码
SpringCliDistributionController cliDistributionController(InitializrMetadataProvider metadataProvider) { return new SpringCliDistributionController(metadataProvider); } @Bean InitializrModule InitializrJacksonModule() { return new InitializrModule(); } } /** * Initializr cache configuration. */ @Configuration @ConditionalOnClass(javax.cache.CacheManager.class) static class InitializrCacheConfiguration { @Bean JCacheManagerCustomizer initializrCacheManagerCustomizer() { return new InitializrJCacheManagerCustomizer(); } } @Order(0) private static final class InitializrJCacheManagerCustomizer implements JCacheManagerCustomizer { @Override public void customize(javax.cache.CacheManager cacheManager) { createMissingCache(cacheManager, "initializr.metadata", () -> config().setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(Duration.TEN_MINUTES))); createMissingCache(cacheManager, "initializr.dependency-metadata", this::config); createMissingCache(cacheManager, "initializr.project-resources", this::config);
createMissingCache(cacheManager, "initializr.templates", this::config); } private void createMissingCache(javax.cache.CacheManager cacheManager, String cacheName, Supplier<MutableConfiguration<Object, Object>> config) { boolean cacheExist = StreamSupport.stream(cacheManager.getCacheNames().spliterator(), true) .anyMatch((name) -> name.equals(cacheName)); if (!cacheExist) { cacheManager.createCache(cacheName, config.get()); } } private MutableConfiguration<Object, Object> config() { return new MutableConfiguration<>().setStoreByValue(false) .setManagementEnabled(true) .setStatisticsEnabled(true); } } }
repos\initializr-main\initializr-web\src\main\java\io\spring\initializr\web\autoconfigure\InitializrAutoConfiguration.java
2
请完成以下Java代码
public class DefaultInboundEvent implements InboundEvent { protected final Object rawEvent; protected final Map<String, Object> headers; public DefaultInboundEvent(Object rawEvent) { this(rawEvent, Collections.emptyMap()); } public DefaultInboundEvent(Object rawEvent, Map<String, Object> headers) { this.rawEvent = rawEvent; this.headers = headers; } @Override public Object getRawEvent() { return rawEvent; } @Override
public Object getBody() { return rawEvent; } @Override public Map<String, Object> getHeaders() { return headers; } @Override public String toString() { return "DefaultInboundEvent{" + "rawEvent=" + rawEvent + ", headers=" + headers + '}'; } }
repos\flowable-engine-main\modules\flowable-event-registry\src\main\java\org\flowable\eventregistry\impl\DefaultInboundEvent.java
1
请在Spring Boot框架中完成以下Java代码
protected AdmissionReviewData processAnnotations(ObjectNode body, JsonNode annotations) { if (annotations.path(admissionControllerProperties.getAnnotation()) .isMissingNode()) { log.info("[I78] processAnnotations: Annotation {} not found in deployment deployment.", admissionControllerProperties.getAnnotation()); return createSimpleAllowedReview(body); } else { log.info("[I163] annotation found: {}", annotations.path(admissionControllerProperties.getAnnotation())); } // Get wait-for-it arguments from the annotation String waitForArgs = annotations.path(admissionControllerProperties.getAnnotation()) .asText(); log.info("[I169] waitForArgs={}", waitForArgs); // Create a PATCH object String patch = injectInitContainer(body, waitForArgs); return AdmissionReviewData.builder() .allowed(true) .uid(body.path("request") .required("uid") .asText()) .patch(Base64.getEncoder() .encodeToString(patch.getBytes())) .patchType("JSONPatch") .build(); } /** * Creates the JSONPatch to be included in the admission response * @param body * @param waitForArgs * @return JSONPatch string */ protected String injectInitContainer(ObjectNode body, String waitForArgs) { // Recover original init containers from the request JsonNode originalSpec = body.path("request") .path("object") .path("spec") .path("template") .path("spec") .require();
JsonNode maybeInitContainers = originalSpec.path("initContainers"); ArrayNode initContainers = maybeInitContainers.isMissingNode()? om.createArrayNode():(ArrayNode) maybeInitContainers; // Create the patch array ArrayNode patchArray = om.createArrayNode(); ObjectNode addNode = patchArray.addObject(); addNode.put("op", "add"); addNode.put("path", "/spec/template/spec/initContainers"); ArrayNode values = addNode.putArray("value"); // Preserve original init containers values.addAll(initContainers); // append the "wait-for-it" container ObjectNode wfi = values.addObject(); wfi.put("name", "wait-for-it-" + UUID.randomUUID()); // Create an unique name, JIC wfi.put("image", admissionControllerProperties.getWaitForItImage()); ArrayNode args = wfi.putArray("args"); for (String s : waitForArgs.split("\\s")) { args.add(s); } return patchArray.toString(); } }
repos\tutorials-master\kubernetes-modules\k8s-admission-controller\src\main\java\com\baeldung\kubernetes\admission\service\AdmissionService.java
2
请在Spring Boot框架中完成以下Java代码
public static Throwable validateRuleNode(RuleNode ruleNode) { String errorPrefix = "'" + ruleNode.getName() + "' node configuration is invalid: "; ConstraintValidator.validateFields(ruleNode, errorPrefix); Object nodeConfig; try { Class<Object> nodeConfigType = ReflectionUtils.getAnnotationProperty(ruleNode.getType(), "org.thingsboard.rule.engine.api.RuleNode", "configClazz"); nodeConfig = JacksonUtil.treeToValue(ruleNode.getConfiguration(), nodeConfigType); } catch (Throwable t) { log.warn("Failed to validate node configuration: {}", ExceptionUtils.getRootCauseMessage(t)); return t; } ConstraintValidator.validateFields(nodeConfig, errorPrefix); return null; } private static void validateCircles(List<NodeConnectionInfo> connectionInfos) { Map<Integer, Set<Integer>> connectionsMap = new HashMap<>(); for (NodeConnectionInfo nodeConnection : connectionInfos) { if (nodeConnection.getFromIndex() == nodeConnection.getToIndex()) { throw new DataValidationException("Can't create the relation to yourself."); }
connectionsMap .computeIfAbsent(nodeConnection.getFromIndex(), from -> new HashSet<>()) .add(nodeConnection.getToIndex()); } connectionsMap.keySet().forEach(key -> validateCircles(key, connectionsMap.get(key), connectionsMap)); } private static void validateCircles(int from, Set<Integer> toList, Map<Integer, Set<Integer>> connectionsMap) { if (toList == null) { return; } for (Integer to : toList) { if (from == to) { throw new DataValidationException("Can't create circling relations in rule chain."); } validateCircles(from, connectionsMap.get(to), connectionsMap); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\service\validator\RuleChainDataValidator.java
2
请完成以下Java代码
public class ConversionServiceParameterValueMapper implements ParameterValueMapper { private final ConversionService conversionService; /** * Create a new {@link ConversionServiceParameterValueMapper} instance. */ public ConversionServiceParameterValueMapper() { this(ApplicationConversionService.getSharedInstance()); } /** * Create a new {@link ConversionServiceParameterValueMapper} instance backed by a * specific conversion service. * @param conversionService the conversion service */ public ConversionServiceParameterValueMapper(ConversionService conversionService) { Assert.notNull(conversionService, "'conversionService' must not be null");
this.conversionService = conversionService; } @Override public @Nullable Object mapParameterValue(OperationParameter parameter, @Nullable Object value) throws ParameterMappingException { try { return this.conversionService.convert(value, parameter.getType()); } catch (Exception ex) { throw new ParameterMappingException(parameter, value, ex); } } }
repos\spring-boot-4.0.1\module\spring-boot-actuator\src\main\java\org\springframework\boot\actuate\endpoint\invoke\convert\ConversionServiceParameterValueMapper.java
1
请完成以下Java代码
public PageData<AlarmCommentInfo> findAlarmComments(TenantId tenantId, AlarmId id, PageLink pageLink) { log.trace("Try to find alarm comments by alarm id using [{}]", id); return DaoUtil.toPageData( alarmCommentRepository.findAllByAlarmId(id.getId(), DaoUtil.toPageable(pageLink))); } @Override public AlarmComment findAlarmCommentById(TenantId tenantId, UUID key) { log.trace("Try to find alarm comment by id using [{}]", key); return DaoUtil.getData(alarmCommentRepository.findById(key)); } @Override public ListenableFuture<AlarmComment> findAlarmCommentByIdAsync(TenantId tenantId, UUID key) { log.trace("Try to find alarm comment by id using [{}]", key); return findByIdAsync(tenantId, key); } @Override public void createPartition(AlarmCommentEntity entity) { partitioningRepository.createPartitionIfNotExists(ALARM_COMMENT_TABLE_NAME, entity.getCreatedTime(), TimeUnit.HOURS.toMillis(partitionSizeInHours)); }
@Override public PageData<AlarmComment> findAllByTenantId(TenantId tenantId, PageLink pageLink) { return DaoUtil.toPageData(alarmCommentRepository.findByTenantId(tenantId.getId(), DaoUtil.toPageable(pageLink))); } @Override protected Class<AlarmCommentEntity> getEntityClass() { return AlarmCommentEntity.class; } @Override protected JpaRepository<AlarmCommentEntity, UUID> getRepository() { return alarmCommentRepository; } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\sql\alarm\JpaAlarmCommentDao.java
1
请在Spring Boot框架中完成以下Java代码
private URI getPermissionsUri(String applicationId) { try { return new URI(this.cloudControllerUrl + "/v2/apps/" + applicationId + "/permissions"); } catch (URISyntaxException ex) { throw new IllegalStateException(ex); } } /** * Return all token keys known by the UAA. * @return a map of token keys */ Map<String, String> fetchTokenKeys() { try { Map<?, ?> response = this.restTemplate.getForObject(getUaaUrl() + "/token_keys", Map.class); Assert.state(response != null, "'response' must not be null"); return extractTokenKeys(response); } catch (HttpStatusCodeException ex) { throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "UAA not reachable"); } } private Map<String, String> extractTokenKeys(Map<?, ?> response) { Map<String, String> tokenKeys = new HashMap<>(); List<?> keys = (List<?>) response.get("keys"); Assert.state(keys != null, "'keys' must not be null"); for (Object key : keys) { Map<?, ?> tokenKey = (Map<?, ?>) key; tokenKeys.put((String) tokenKey.get("kid"), (String) tokenKey.get("value"));
} return tokenKeys; } /** * Return the URL of the UAA. * @return the UAA url */ String getUaaUrl() { if (this.uaaUrl == null) { try { Map<?, ?> response = this.restTemplate.getForObject(this.cloudControllerUrl + "/info", Map.class); Assert.state(response != null, "'response' must not be null"); String tokenEndpoint = (String) response.get("token_endpoint"); Assert.state(tokenEndpoint != null, "'tokenEndpoint' must not be null"); this.uaaUrl = tokenEndpoint; } catch (HttpStatusCodeException ex) { throw new CloudFoundryAuthorizationException(Reason.SERVICE_UNAVAILABLE, "Unable to fetch token keys from UAA"); } } return this.uaaUrl; } }
repos\spring-boot-4.0.1\module\spring-boot-cloudfoundry\src\main\java\org\springframework\boot\cloudfoundry\autoconfigure\actuate\endpoint\servlet\SecurityService.java
2
请在Spring Boot框架中完成以下Java代码
public MADBoilerPlate getDefaultTextPreset() { return DEFAULT_TEXT_PRESET; } /** * @return the title of the process */ @Override public String getExportFilePrefix() { return exportFilePrefix; } @Override public I_AD_User getFrom() { return from; } /** * @return <code>null</code> */ @Override public String getMessage() { return MESSAGE; } /**
* @return the title of the process */ @Override public String getSubject() { return subject; } /** * @return the title of the process */ @Override public String getTitle() { return title; } @Override public String getTo() { return to; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\org\compiere\report\email\service\impl\BPartnerEmailParams.java
2
请完成以下Java代码
public String getAttribute() { return null; } @Override public int hashCode() { return Objects.hash(this.accessPredicate); } @Override public boolean equals(final Object obj) { if (this == obj) { return true; } if (obj == null) {
return false; } if (getClass() != obj.getClass()) { return false; } final AccessPredicateConfigAttribute other = (AccessPredicateConfigAttribute) obj; return Objects.equals(this.accessPredicate, other.accessPredicate); } @Override public String toString() { return "AccessPredicateConfigAttribute [" + this.accessPredicate + "]"; } }
repos\grpc-spring-master\grpc-server-spring-boot-starter\src\main\java\net\devh\boot\grpc\server\security\check\AccessPredicateConfigAttribute.java
1
请完成以下Java代码
public SpinFileNotFoundException fileNotFoundException(String filename) { return fileNotFoundException(filename, null); } public SpinRuntimeException unableToReadFromReader(Exception e) { return new SpinRuntimeException(exceptionMessage("003", "Unable to read from reader"), e); } public SpinDataFormatException unrecognizableDataFormatException() { return new SpinDataFormatException(exceptionMessage("004", "No matching data format detected")); } public SpinScriptException noScriptEnvFoundForLanguage(String scriptLanguage, String path) { return new SpinScriptException(exceptionMessage("006", "No script script env found for script language '{}' at path '{}'", scriptLanguage, path)); } public IOException unableToRewindReader() { return new IOException(exceptionMessage("007", "Unable to rewind input stream: rewind buffering limit exceeded")); } public SpinDataFormatException multipleProvidersForDataformat(String dataFormatName) { return new SpinDataFormatException(exceptionMessage("008", "Multiple providers found for dataformat '{}'", dataFormatName)); } public void logDataFormats(Collection<DataFormat<?>> formats) { if (isInfoEnabled()) { for (DataFormat<?> format : formats) { logDataFormat(format); } }
} protected void logDataFormat(DataFormat<?> dataFormat) { logInfo("009", "Discovered Spin data format: {}[name = {}]", dataFormat.getClass().getName(), dataFormat.getName()); } public void logDataFormatProvider(DataFormatProvider provider) { if (isInfoEnabled()) { logInfo("010", "Discovered Spin data format provider: {}[name = {}]", provider.getClass().getName(), provider.getDataFormatName()); } } @SuppressWarnings("rawtypes") public void logDataFormatConfigurator(DataFormatConfigurator configurator) { if (isInfoEnabled()) { logInfo("011", "Discovered Spin data format configurator: {}[dataformat = {}]", configurator.getClass(), configurator.getDataFormatClass().getName()); } } public SpinDataFormatException classNotFound(String classname, ClassNotFoundException cause) { return new SpinDataFormatException(exceptionMessage("012", "Class {} not found ", classname), cause); } public void tryLoadingClass(String classname, ClassLoader cl) { logDebug("013", "Try loading class '{}' using classloader '{}'.", classname, cl); } }
repos\camunda-bpm-platform-master\spin\core\src\main\java\org\camunda\spin\impl\logging\SpinCoreLogger.java
1