instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
protected void registerCallouts(@NonNull final IProgramaticCalloutProvider programaticCalloutProvider) { // Do not initialize if the printing module is disabled if (!checkPrintingEnabled()) { return; } // task 09417 programaticCalloutProvider.registerAnnotatedCallout(de.metas.printing.callout.C_Doc_Outbound_Config.instance); } @Override protected void setupCaching(final IModelCacheService cachingService) { // task 09417: while we are in the area, also make sure that config changes are propagated final CacheMgt cacheMgt = CacheMgt.get(); cacheMgt.enableRemoteCacheInvalidationForTableName(I_AD_PrinterRouting.Table_Name); cacheMgt.enableRemoteCacheInvalidationForTableName(I_AD_Printer_Config.Table_Name); cacheMgt.enableRemoteCacheInvalidationForTableName(I_AD_Printer_Matching.Table_Name); } @Override protected void onAfterInit() { // Do not initialize if the printing module is disabled if (!checkPrintingEnabled()) { return; } Services.get(IPrintingQueueBL.class).registerHandler(DocumentPrintingQueueHandler.instance); // task 09833 // Register the Default Printing Info ctx provider Services.get(INotificationBL.class).setDefaultCtxProvider(DefaultPrintingRecordTextProvider.instance); Services.get(IAsyncBatchListeners.class).registerAsyncBatchNoticeListener(new PDFPrintingAsyncBatchListener(), Printing_Constants.C_Async_Batch_InternalName_PDFPrinting); Services.get(IAsyncBatchListeners.class).registerAsyncBatchNoticeListener(new AutomaticallyInvoicePdfPrintinAsyncBatchListener(), Async_Constants.C_Async_Batch_InternalName_AutomaticallyInvoicePdfPrinting); } @Override
protected List<Topic> getAvailableUserNotificationsTopics() { return ImmutableList.of(Printing_Constants.USER_NOTIFICATIONS_TOPIC); } @Override public void onUserLogin(final int AD_Org_ID, final int AD_Role_ID, final int AD_User_ID) { // make sure that the host key is set in the context if (checkPrintingEnabled()) { final Properties ctx = Env.getCtx(); final MFSession session = Services.get(ISessionBL.class).getCurrentSession(ctx); session.getOrCreateHostKey(ctx); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.printing\de.metas.printing.base\src\main\java\de\metas\printing\model\validator\Main.java
1
请完成以下Java代码
public static String encode(String password) { password = password + SALT; MessageDigest md5 = null; try { md5 = MessageDigest.getInstance("MD5"); } catch (Exception e) { throw new RuntimeException(e); } char[] charArray = password.toCharArray(); byte[] byteArray = new byte[charArray.length]; for (int i = 0; i < charArray.length; i++) byteArray[i] = (byte) charArray[i]; byte[] md5Bytes = md5.digest(byteArray); StringBuffer hexValue = new StringBuffer(); for (int i = 0; i < md5Bytes.length; i++) {
int val = ((int) md5Bytes[i]) & 0xff; if (val < 16) { hexValue.append("0"); } hexValue.append(Integer.toHexString(val)); } return hexValue.toString(); } public static void main(String[] args) { System.out.println(MD5Util.encode("abel")); } }
repos\springBoot-master\springboot-SpringSecurity0\src\main\java\com\us\example\util\MD5Util.java
1
请完成以下Java代码
private void captureMoneyIfNeeded(@NonNull final I_C_Invoice salesInvoice) { // // We capture money only for sales invoices if (!salesInvoice.isSOTrx()) { return; } // // Avoid reversals if (invoiceBL.isReversal(salesInvoice)) { return; } // // We capture money only for regular invoices (not credit memos) // TODO: for credit memos we shall refund a part of already reserved money if (invoiceBL.isCreditMemo(salesInvoice)) { return; } // // // If there is no order, we cannot capture money because we don't know which is the payment reservation final OrderId salesOrderId = OrderId.ofRepoIdOrNull(salesInvoice.getC_Order_ID()); if (salesOrderId == null) { return; } // // No payment reservation if (!paymentReservationService.hasPaymentReservation(salesOrderId))
{ return; } final LocalDate dateTrx = TimeUtil.asLocalDate(salesInvoice.getDateInvoiced()); final Money grandTotal = extractGrandTotal(salesInvoice); paymentReservationService.captureAmount(PaymentReservationCaptureRequest.builder() .salesOrderId(salesOrderId) .salesInvoiceId(InvoiceId.ofRepoId(salesInvoice.getC_Invoice_ID())) .customerId(BPartnerId.ofRepoId(salesInvoice.getC_BPartner_ID())) .dateTrx(dateTrx) .amount(grandTotal) .build()); } private static Money extractGrandTotal(@NonNull final I_C_Invoice salesInvoice) { return Money.of(salesInvoice.getGrandTotal(), CurrencyId.ofRepoId(salesInvoice.getC_Currency_ID())); } @ModelChange(timings = { ModelValidator.TYPE_AFTER_NEW, ModelValidator.TYPE_AFTER_CHANGE }, ifColumnsChanged = { I_C_Invoice.COLUMNNAME_M_Warehouse_ID, I_C_Invoice.COLUMNNAME_DateInvoiced }) public void updateInvoiceLinesTax(@NonNull final I_C_Invoice invoice) { invoiceBL.setInvoiceLineTaxes(invoice); } @DocValidate(timings = { ModelValidator.TIMING_AFTER_COMPLETE }) public void updateOrderPaySchedules(@NonNull final I_C_Invoice invoice) { final OrderId orderId = OrderId.ofRepoIdOrNull(invoice.getC_Order_ID()); if (orderId != null && invoice.getDateInvoiced() != null) { orderBL.syncDateInvoicedFromInvoice(orderId, invoice); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\invoice\interceptor\C_Invoice.java
1
请完成以下Java代码
public T getDefaultValue() { return defaultValue; } public void setDefaultValue(T defaultValue) { this.defaultValue = defaultValue; } public boolean isRequired() { return isRequired; } /** */ public void setRequired(boolean required) { this.isRequired = required; } /** * @param namespaceUri the namespaceUri to set */ public void setNamespaceUri(String namespaceUri) { this.namespaceUri = namespaceUri; } /** * @return the namespaceUri */ public String getNamespaceUri() { return namespaceUri; } public boolean isIdAttribute() { return isIdAttribute; } /** * Indicate whether this attribute is an Id attribute * */ public void setId() { this.isIdAttribute = true; } /** * @return the attributeName */ public String getAttributeName() { return attributeName; } /** * @param attributeName the attributeName to set */ public void setAttributeName(String attributeName) { this.attributeName = attributeName;
} public void removeAttribute(ModelElementInstance modelElement) { if (namespaceUri == null) { modelElement.removeAttribute(attributeName); } else { modelElement.removeAttributeNs(namespaceUri, attributeName); } } public void unlinkReference(ModelElementInstance modelElement, Object referenceIdentifier) { if (!incomingReferences.isEmpty()) { for (Reference<?> incomingReference : incomingReferences) { ((ReferenceImpl<?>) incomingReference).referencedElementRemoved(modelElement, referenceIdentifier); } } } /** * @return the incomingReferences */ public List<Reference<?>> getIncomingReferences() { return incomingReferences; } /** * @return the outgoingReferences */ public List<Reference<?>> getOutgoingReferences() { return outgoingReferences; } public void registerOutgoingReference(Reference<?> ref) { outgoingReferences.add(ref); } public void registerIncoming(Reference<?> ref) { incomingReferences.add(ref); } }
repos\camunda-bpm-platform-master\model-api\xml-model\src\main\java\org\camunda\bpm\model\xml\impl\type\attribute\AttributeImpl.java
1
请完成以下Java代码
public int getAD_User_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_ID); } @Override public void setAD_User_MKTG_Channels_ID (final int AD_User_MKTG_Channels_ID) { if (AD_User_MKTG_Channels_ID < 1) set_ValueNoCheck (COLUMNNAME_AD_User_MKTG_Channels_ID, null); else set_ValueNoCheck (COLUMNNAME_AD_User_MKTG_Channels_ID, AD_User_MKTG_Channels_ID); } @Override public int getAD_User_MKTG_Channels_ID() { return get_ValueAsInt(COLUMNNAME_AD_User_MKTG_Channels_ID); } @Override public de.metas.marketing.base.model.I_MKTG_Channel getMKTG_Channel() { return get_ValueAsPO(COLUMNNAME_MKTG_Channel_ID, de.metas.marketing.base.model.I_MKTG_Channel.class); }
@Override public void setMKTG_Channel(final de.metas.marketing.base.model.I_MKTG_Channel MKTG_Channel) { set_ValueFromPO(COLUMNNAME_MKTG_Channel_ID, de.metas.marketing.base.model.I_MKTG_Channel.class, MKTG_Channel); } @Override public void setMKTG_Channel_ID (final int MKTG_Channel_ID) { if (MKTG_Channel_ID < 1) set_Value (COLUMNNAME_MKTG_Channel_ID, null); else set_Value (COLUMNNAME_MKTG_Channel_ID, MKTG_Channel_ID); } @Override public int getMKTG_Channel_ID() { return get_ValueAsInt(COLUMNNAME_MKTG_Channel_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.marketing\base\src\main\java-gen\de\metas\marketing\base\model\X_AD_User_MKTG_Channels.java
1
请完成以下Java代码
public class DistributionFacetIdsCollection implements Iterable<DistributionFacetId> { public static final DistributionFacetIdsCollection EMPTY = new DistributionFacetIdsCollection(ImmutableSet.of()); private final ImmutableSet<DistributionFacetId> set; private DistributionFacetIdsCollection(@NonNull final ImmutableSet<DistributionFacetId> set) { this.set = set; } public static DistributionFacetIdsCollection ofWorkflowLaunchersFacetIds(@Nullable Collection<WorkflowLaunchersFacetId> facetIds) { if (facetIds == null || facetIds.isEmpty()) { return EMPTY; } return ofCollection(facetIds.stream().map(DistributionFacetId::ofWorkflowLaunchersFacetId).collect(ImmutableSet.toImmutableSet())); } public static DistributionFacetIdsCollection ofCollection(final Collection<DistributionFacetId> collection) { return !collection.isEmpty() ? new DistributionFacetIdsCollection(ImmutableSet.copyOf(collection)) : EMPTY; } @Override @NonNull public Iterator<DistributionFacetId> iterator() {return set.iterator();} public boolean isEmpty() {return set.isEmpty();} public Set<WarehouseId> getWarehouseFromIds() {return getValues(DistributionFacetGroupType.WAREHOUSE_FROM, DistributionFacetId::getWarehouseId);} public Set<WarehouseId> getWarehouseToIds() {return getValues(DistributionFacetGroupType.WAREHOUSE_TO, DistributionFacetId::getWarehouseId);} public Set<OrderId> getSalesOrderIds() {return getValues(DistributionFacetGroupType.SALES_ORDER, DistributionFacetId::getSalesOrderId);}
public Set<PPOrderId> getManufacturingOrderIds() {return getValues(DistributionFacetGroupType.MANUFACTURING_ORDER_NO, DistributionFacetId::getManufacturingOrderId);} public Set<LocalDate> getDatesPromised() {return getValues(DistributionFacetGroupType.DATE_PROMISED, DistributionFacetId::getDatePromised);} public Set<ProductId> getProductIds() {return getValues(DistributionFacetGroupType.PRODUCT, DistributionFacetId::getProductId);} public Set<Quantity> getQuantities() {return getValues(DistributionFacetGroupType.QUANTITY, DistributionFacetId::getQty);} public Set<ResourceId> getPlantIds() {return getValues(DistributionFacetGroupType.PLANT_RESOURCE_ID, DistributionFacetId::getPlantId);} public <T> Set<T> getValues(DistributionFacetGroupType groupType, Function<DistributionFacetId, T> valueExtractor) { if (set.isEmpty()) { return ImmutableSet.of(); } return set.stream() .filter(facetId -> facetId.getGroup().equals(groupType)) .map(valueExtractor) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\launchers\facets\DistributionFacetIdsCollection.java
1
请完成以下Java代码
public class ESR_Main_Validator extends AbstractModuleInterceptor { @Override protected void onAfterInit() { registerFactories(); } @Override protected void registerInterceptors(IModelValidationEngine engine) { engine.addModelValidator(new ESR_Import()); engine.addModelValidator(new ESR_ImportLine()); engine.addModelValidator(new C_PaySelection()); } public void registerFactories() { // // Register payment action handlers. final IESRImportBL esrImportBL = Services.get(IESRImportBL.class); esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Write_Off_Amount, new WriteoffESRActionHandler()); esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Keep_For_Dunning, new DunningESRActionHandler()); esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Money_Was_Transfered_Back_to_Partner, new MoneyTransferedBackESRActionHandler()); esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Allocate_Payment_With_Next_Invoice, new WithNextInvoiceESRActionHandler()); esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Allocate_Payment_With_Current_Invoice, new WithCurrenttInvoiceESRActionHandler()); esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Unable_To_Assign_Income, new UnableToAssignESRActionHandler()); esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Discount, new DiscountESRActionHandler()); esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Duplicate_Payment, new DuplicatePaymentESRActionHandler());
esrImportBL.registerActionHandler(X_ESR_ImportLine.ESR_PAYMENT_ACTION_Unknown_Invoice, new UnknownInvoiceESRActionHandler()); // // Register ESR Payment Parsers final IPaymentStringParserFactory paymentStringParserFactory = Services.get(IPaymentStringParserFactory.class); paymentStringParserFactory.registerParser(PaymentParserType.ESRRegular.getType(), ESRRegularLineParser.instance); paymentStringParserFactory.registerParser(PaymentParserType.ESRCreaLogix.getType(), ESRCreaLogixStringParser.instance); paymentStringParserFactory.registerParser(PaymentParserType.QRCode.getType(), new QRCodeStringParser()); // // Payment batch provider for Bank Statement matching Services.get(IPaymentBatchFactory.class).addPaymentBatchProvider(new ESRPaymentBatchProvider()); // // Bank statement listener Services.get(IBankStatementListenerService.class).addListener(new ESRBankStatementListener(esrImportBL)); // // ESR match listener Services.get(IESRLineHandlersService.class).registerESRLineListener(new DefaultESRLineHandler()); // 08741 } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.esr\src\main\java\de\metas\payment\esr\model\validator\ESR_Main_Validator.java
1
请完成以下Java代码
public class Philosopher implements Runnable { private final Object leftFork; private final Object rightFork; Philosopher(Object left, Object right) { this.leftFork = left; this.rightFork = right; } private void doAction(String action) throws InterruptedException { System.out.println(Thread.currentThread().getName() + " " + action); Thread.sleep(((int) (Math.random() * 100))); } @Override public void run() {
try { while (true) { doAction(System.nanoTime() + ": Thinking"); // thinking synchronized (leftFork) { doAction(System.nanoTime() + ": Picked up left fork"); synchronized (rightFork) { doAction(System.nanoTime() + ": Picked up right fork - eating"); // eating doAction(System.nanoTime() + ": Put down right fork"); } doAction(System.nanoTime() + ": Put down left fork. Returning to thinking"); } } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }
repos\tutorials-master\core-java-modules\core-java-concurrency-advanced-7\src\main\java\com\baeldung\diningphilosophers\Philosopher.java
1
请在Spring Boot框架中完成以下Java代码
private TenantProfile getTenantProfile(TenantId tenantId) { TenantProfile profile = null; TenantProfileId tenantProfileId = tenantIds.get(tenantId); if (tenantProfileId != null) { profile = profiles.get(tenantProfileId); } if (profile == null) { tenantProfileFetchLock.lock(); try { tenantProfileId = tenantIds.get(tenantId); if (tenantProfileId != null) { profile = profiles.get(tenantProfileId); } if (profile == null) { TransportProtos.GetEntityProfileRequestMsg msg = TransportProtos.GetEntityProfileRequestMsg.newBuilder() .setEntityType(EntityType.TENANT.name()) .setEntityIdMSB(tenantId.getId().getMostSignificantBits()) .setEntityIdLSB(tenantId.getId().getLeastSignificantBits()) .build(); TransportProtos.GetEntityProfileResponseMsg entityProfileMsg = transportService.getEntityProfile(msg); profile = ProtoUtils.fromProto(entityProfileMsg.getTenantProfile()); TenantProfile existingProfile = profiles.get(profile.getId()); if (existingProfile != null) {
profile = existingProfile; } else { profiles.put(profile.getId(), profile); } tenantProfileIds.computeIfAbsent(profile.getId(), id -> ConcurrentHashMap.newKeySet()).add(tenantId); tenantIds.put(tenantId, profile.getId()); ApiUsageState apiUsageState = ProtoUtils.fromProto(entityProfileMsg.getApiState()); rateLimitService.update(tenantId, apiUsageState.isTransportEnabled()); } } finally { tenantProfileFetchLock.unlock(); } } return profile; } }
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\service\DefaultTransportTenantProfileCache.java
2
请完成以下Java代码
public static Result removeOne(String desformCode, String dataId, String token) { String url = getBaseUrl(desformCode, dataId).toString(); HttpHeaders headers = getHeaders(token); ResponseEntity<JSONObject> result = RestUtil.request(url, HttpMethod.DELETE, headers, null, null, JSONObject.class); return packageReturn(result); } private static Result packageReturn(ResponseEntity<JSONObject> result) { if (result.getBody() != null) { return result.getBody().toJavaObject(Result.class); } return Result.error("操作失败"); } private static StringBuilder getBaseUrl() { StringBuilder builder = new StringBuilder(domain).append(path); builder.append("/desform/api"); return builder; } private static StringBuilder getBaseUrl(String desformCode, String dataId) { StringBuilder builder = getBaseUrl();
builder.append("/").append(desformCode); if (dataId != null) { builder.append("/").append(dataId); } return builder; } private static StringBuilder getBaseUrl(String desformCode) { return getBaseUrl(desformCode, null); } private static HttpHeaders getHeaders(String token) { HttpHeaders headers = new HttpHeaders(); String mediaType = MediaType.APPLICATION_JSON_UTF8_VALUE; headers.setContentType(MediaType.parseMediaType(mediaType)); headers.set("Accept", mediaType); headers.set("X-Access-Token", token); return headers; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\RestDesformUtil.java
1
请完成以下Java代码
public static boolean isExecutionRelatedEntityCountEnabled(ExecutionEntity executionEntity) { if (executionEntity.isProcessInstanceType() || executionEntity instanceof CountingExecutionEntity) { return isExecutionRelatedEntityCountEnabled((CountingExecutionEntity) executionEntity); } return false; } public static boolean isTaskRelatedEntityCountEnabled(TaskEntity taskEntity) { if (taskEntity instanceof CountingTaskEntity) { return isTaskRelatedEntityCountEnabled((CountingTaskEntity) taskEntity); } return false; } /** * There are two flags here: a global flag and a flag on the execution entity. * The global flag can be switched on and off between different reboots, however the flag on the executionEntity refers * to the state at that particular moment of the last insert/update. * * Global flag / ExecutionEntity flag : result * * T / T : T (all true, regular mode with flags enabled) * T / F : F (global is true, but execution was of a time when it was disabled, thus treating it as disabled as the counts can't be guessed)
* F / T : F (execution was of time when counting was done. But this is overruled by the global flag and thus the queries will o * be done) * F / F : F (all disabled) * * From this table it is clear that only when both are true, the result should be true, which is the regular AND rule for booleans. */ public static boolean isExecutionRelatedEntityCountEnabled(CountingExecutionEntity executionEntity) { return !executionEntity.isProcessInstanceType() && isExecutionRelatedEntityCountEnabledGlobally() && executionEntity.isCountEnabled(); } /** * Similar functionality with <b>ExecutionRelatedEntityCount</b>, but on the TaskEntity level. */ public static boolean isTaskRelatedEntityCountEnabled(CountingTaskEntity taskEntity) { return isTaskRelatedEntityCountEnabledGlobally() && taskEntity.isCountEnabled(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\util\CountingEntityUtil.java
1
请完成以下Java代码
public int getStudentId() { return studentId; } public void setStudentId(int studentId) { this.studentId = studentId; } public String getStudentName() { return studentName; } public void setStudentName(String studentName) { this.studentName = studentName; } public Course getCourse() { return course; } public void setCourse(Course course) { this.course = course; } @Override public Student clone() { Student student; try { student = (Student) super.clone(); } catch (CloneNotSupportedException e) { throw new IllegalStateException(e); } student.course = this.course.clone(); return student; } @Override
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Student that = (Student) o; return Objects.equals(studentId,that.studentId) && Objects.equals(studentName, that.studentName) && Objects.equals(course, that.course); } @Override public int hashCode() { return Objects.hash(studentId,studentName,course); } }
repos\tutorials-master\core-java-modules\core-java-lang-oop-patterns-2\src\main\java\com\baeldung\deepcopyarraylist\Student.java
1
请完成以下Java代码
public int logarithmicApproach(int number) { int length = (int) Math.log10(number) + 1; return length; } public int repeatedMultiplication(int number) { int length = 0; long temp = 1; while(temp <= number) { length++; temp *= 10; } return length; } public int shiftOperators(int number) { int length = 0; long temp = 1; while(temp <= number) { length++; temp = (temp << 3) + (temp << 1); } return length; } public int dividingWithPowersOf2(int number) { int length = 1; if (number >= 100000000) { length += 8; number /= 100000000; } if (number >= 10000) { length += 4; number /= 10000; } if (number >= 100) { length += 2; number /= 100; } if (number >= 10) { length += 1; } return length; } public int divideAndConquer(int number) { if (number < 100000){ // 5 digits or less if (number < 100){ // 1 or 2 if (number < 10) return 1; else return 2; }else{ // 3 to 5 digits if (number < 1000) return 3; else{ // 4 or 5 digits if (number < 10000) return 4;
else return 5; } } } else { // 6 digits or more if (number < 10000000) { // 6 or 7 digits if (number < 1000000) return 6; else return 7; } else { // 8 to 10 digits if (number < 100000000) return 8; else { // 9 or 10 digits if (number < 1000000000) return 9; else return 10; } } } } }
repos\tutorials-master\core-java-modules\core-java-numbers\src\main\java\com\baeldung\numberofdigits\NumberOfDigits.java
1
请完成以下Java代码
private List<HuForInventoryLine> loadEligibleHUs( @NonNull final ProductId productId, @Nullable final AttributeSetInstanceId attributeSetInstanceId, @Nullable final WarehouseId warehouseId) { final LocatorAndProductStrategy husFinder = HUsForInventoryStrategies.locatorAndProduct() .huForInventoryLineFactory(huForInventoryLineFactory) .onlyProductId(productId) .asiId(attributeSetInstanceId) .warehouseId(warehouseId) // .build(); return husFinder.streamHus() .filter(hu -> hu.getProductId().equals(productId)) .collect(ImmutableList.toImmutableList()); } private JsonOutOfStockResponse buildOutOfStockNoticeResponse( @NonNull final Map<WarehouseId, String> warehouseId2InventoryDocNo, @NonNull final Map<WarehouseId, List<ShipmentScheduleId>> warehouseId2ClosedShipmentSchedules) { final JsonOutOfStockResponse.JsonOutOfStockResponseBuilder responseBuilder = JsonOutOfStockResponse.builder(); final Set<WarehouseId> seenWarehouseIds = new HashSet<>(); warehouseId2ClosedShipmentSchedules.keySet() .stream() .map(warehouseId -> { final List<JsonMetasfreshId> closedShipmentScheduleIds = warehouseId2ClosedShipmentSchedules.get(warehouseId) .stream() .map(ShipmentScheduleId::getRepoId) .map(JsonMetasfreshId::of) .collect(ImmutableList.toImmutableList()); if (closedShipmentScheduleIds.isEmpty()) { return null; } seenWarehouseIds.add(warehouseId);
return JsonOutOfStockResponseItem.builder() .warehouseId(JsonMetasfreshId.of(warehouseId.getRepoId())) .closedShipmentSchedules(closedShipmentScheduleIds) .inventoryDocNo(warehouseId2InventoryDocNo.get(warehouseId)) .build(); }) .filter(Objects::nonNull) .forEach(responseBuilder::affectedWarehouse); warehouseId2InventoryDocNo.entrySet() .stream() .filter(warehouseId2InvEntry -> !seenWarehouseIds.contains(warehouseId2InvEntry.getKey())) .map(warehouseId2InvDocNoEntry -> JsonOutOfStockResponseItem.builder() .inventoryDocNo(warehouseId2InvDocNoEntry.getValue()) .warehouseId(JsonMetasfreshId.of(warehouseId2InvDocNoEntry.getKey().getRepoId())) .build()) .forEach(responseBuilder::affectedWarehouse); return responseBuilder.build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\warehouse\WarehouseService.java
1
请完成以下Java代码
public static PriceLimitRuleResult priceLimit(@NonNull final BigDecimal priceLimit, final String priceLimitExplanation) { return priceLimit(priceLimit, TranslatableStrings.anyLanguage(priceLimitExplanation)); } public static PriceLimitRuleResult priceLimit(@NonNull final BigDecimal priceLimit, @NonNull final ITranslatableString priceLimitExplanation) { return PriceLimitRuleResult._builder() .applicable(true) .priceLimit(priceLimit) .priceLimitExplanation(priceLimitExplanation) .build(); } private boolean applicable; private ITranslatableString notApplicableReason; private BigDecimal priceLimit; /** Explanation about how the price limit was calculated, from where it comes etc */ private ITranslatableString priceLimitExplanation; @Builder(builderMethodName = "_builder") private PriceLimitRuleResult( final boolean applicable, final ITranslatableString notApplicableReason, final BigDecimal priceLimit, final ITranslatableString priceLimitExplanation) { if (applicable) { Check.assumeNotNull(priceLimit, "Parameter priceLimit is not null"); Check.assumeNotNull(priceLimitExplanation, "Parameter priceLimitExplanation is not null"); this.applicable = true; this.priceLimit = priceLimit; this.priceLimitExplanation = priceLimitExplanation; this.notApplicableReason = null; } else { Check.assumeNotNull(notApplicableReason, "Parameter notApplicableReason is not null"); this.applicable = false; this.notApplicableReason = notApplicableReason; this.priceLimit = null; this.priceLimitExplanation = null; } }
public BooleanWithReason checkApplicableAndBelowPriceLimit(@NonNull final BigDecimal priceActual) { if (!applicable) { return BooleanWithReason.falseBecause(notApplicableReason); } if (priceLimit.signum() == 0) { return BooleanWithReason.falseBecause("limit price is ZERO"); } final boolean belowPriceLimit = priceActual.compareTo(priceLimit) < 0; if (belowPriceLimit) { return BooleanWithReason.trueBecause(priceLimitExplanation); } else { return BooleanWithReason.falseBecause("Price " + priceActual + " is above " + priceLimit + "(limit price)"); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\pricing\limit\PriceLimitRuleResult.java
1
请在Spring Boot框架中完成以下Java代码
public class CountryDto { private final Long id; private final String name; private final String code; private final String emoji; public CountryDto(Long id, String name, String code, String emoji) { this.id = id; this.name = name; this.code = code; this.emoji = emoji; } public Long getId() {
return id; } public String getName() { return name; } public String getCode() { return code; } public String getEmoji() { return emoji; } }
repos\tutorials-master\docker-modules\docker-multi-module-maven\docker-rest-api\src\main\java\com\baeldung\api\controller\CountryDto.java
2
请在Spring Boot框架中完成以下Java代码
public class SessionConfiguration { /** * 创建 {@link RedisOperationsSessionRepository} 使用的 RedisSerializer Bean 。 * * 具体可以看看 {@link RedisHttpSessionConfiguration#setDefaultRedisSerializer(RedisSerializer)} 方法, * 它会引入名字为 "springSessionDefaultRedisSerializer" 的 Bean 。 * * @return RedisSerializer Bean */ @Bean(name = "springSessionDefaultRedisSerializer") public RedisSerializer springSessionDefaultRedisSerializer() { return RedisSerializer.json(); } // @Bean // public CookieHttpSessionIdResolver sessionIdResolver() { // // 创建 CookieHttpSessionIdResolver 对象 // CookieHttpSessionIdResolver sessionIdResolver = new CookieHttpSessionIdResolver(); // // // 创建 DefaultCookieSerializer 对象
// DefaultCookieSerializer cookieSerializer = new DefaultCookieSerializer(); // sessionIdResolver.setCookieSerializer(cookieSerializer); // 设置到 sessionIdResolver 中 // cookieSerializer.setCookieName("JSESSIONID"); // // return sessionIdResolver; // } // @Bean // public HeaderHttpSessionIdResolver sessionIdResolver() { //// return HeaderHttpSessionIdResolver.xAuthToken(); //// return HeaderHttpSessionIdResolver.authenticationInfo(); // return new HeaderHttpSessionIdResolver("token"); // } }
repos\SpringBoot-Labs-master\lab-26\lab-26-distributed-session-01\src\main\java\cn\iocoder\springboot\lab26\distributedsession\config\SessionConfiguration.java
2
请完成以下Java代码
String bodyAsString() throws IOException { InputStream byteStream = new ByteArrayInputStream(bodyAsByteArray()); if (headers.getOrEmpty(HttpHeaders.CONTENT_ENCODING).contains("gzip")) { byteStream = new GZIPInputStream(byteStream); } return new String(FileCopyUtils.copyToByteArray(byteStream)); } public static class Builder { private final HttpStatusCode statusCode; private final HttpHeaders headers = new HttpHeaders(); private final List<ByteBuffer> body = new ArrayList<>(); private @Nullable Instant timestamp; public Builder(HttpStatusCode statusCode) { this.statusCode = statusCode; } public Builder header(String name, String value) { this.headers.add(name, value); return this; } public Builder headers(HttpHeaders headers) { this.headers.addAll(headers); return this; }
public Builder timestamp(Instant timestamp) { this.timestamp = timestamp; return this; } public Builder timestamp(Date timestamp) { this.timestamp = timestamp.toInstant(); return this; } public Builder body(String data) { return appendToBody(ByteBuffer.wrap(data.getBytes(StandardCharsets.UTF_8))); } public Builder appendToBody(ByteBuffer byteBuffer) { this.body.add(byteBuffer); return this; } public CachedResponse build() { return new CachedResponse(statusCode, headers, body, timestamp == null ? new Date() : Date.from(timestamp)); } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\cache\CachedResponse.java
1
请完成以下Java代码
public SecurityInfo getByOscoreIdentity(OscoreIdentity oscoreIdentity) { return null; } public SecurityInfo fetchAndPutSecurityInfo(String credentialsId) { TbLwM2MSecurityInfo securityInfo = validator.getEndpointSecurityInfoByCredentialsId(credentialsId, CLIENT); doPut(securityInfo); return securityInfo != null ? securityInfo.getSecurityInfo() : null; } private void doPut(TbLwM2MSecurityInfo securityInfo) { if (securityInfo != null) { try { securityStore.put(securityInfo); } catch (NonUniqueSecurityInfoException e) { log.trace("Failed to add security info: {}", securityInfo, e); } } } @Override public void putX509(TbLwM2MSecurityInfo securityInfo) throws NonUniqueSecurityInfoException { securityStore.put(securityInfo); }
@Override public void registerX509(String endpoint, String registrationId) { endpointRegistrations.computeIfAbsent(endpoint, ep -> new HashSet<>()).add(registrationId); } @Override public void remove(String endpoint, String registrationId) { Set<String> epRegistrationIds = endpointRegistrations.get(endpoint); boolean shouldRemove; if (epRegistrationIds == null) { shouldRemove = true; } else { epRegistrationIds.remove(registrationId); shouldRemove = epRegistrationIds.isEmpty(); } if (shouldRemove) { securityStore.remove(endpoint); } } }
repos\thingsboard-master\common\transport\lwm2m\src\main\java\org\thingsboard\server\transport\lwm2m\server\store\TbLwM2mSecurityStore.java
1
请完成以下Java代码
public Integer getState() { return state; } /** * 设置 状态 1:正常 2:禁用. * * @param state 状态 1:正常 2:禁用. */ public void setState(Integer state) { this.state = state; } /** * 获取 创建时间. * * @return 创建时间. */ public Date getCreatedTime() { return createdTime; } /** * 设置 创建时间. * * @param createdTime 创建时间. */ public void setCreatedTime(Date createdTime) { this.createdTime = createdTime; } /** * 获取 更新时间. * * @return 更新时间. */
public Date getUpdatedTime() { return updatedTime; } /** * 设置 更新时间. * * @param updatedTime 更新时间. */ public void setUpdatedTime(Date updatedTime) { this.updatedTime = updatedTime; } protected Serializable pkVal() { return this.id; } }
repos\SpringBootBucket-master\springboot-jwt\src\main\java\com\xncoding\jwt\dao\domain\Manager.java
1
请完成以下Java代码
protected String doIt() { final CopyColumnsResult result = CopyColumnsProducer.newInstance() .setLogger(this) .setTargetTable(getTargetTable()) .setSourceColumns(getSourceColumns()) .setEntityType(p_EntityType) .setDryRun(p_IsTest) .create(); // return "" + result; } protected I_AD_Table getTargetTable() { if (p_AD_Table_ID <= 0) { throw new AdempiereException("@NotFound@ @AD_Table_ID@ " + p_AD_Table_ID); } final I_AD_Table targetTable = InterfaceWrapperHelper.create(getCtx(), p_AD_Table_ID, I_AD_Table.class, get_TrxName()); return targetTable; }
protected List<I_AD_Column> getSourceColumns() { final IQueryFilter<I_AD_Column> selectedColumnsFilter = getProcessInfo().getQueryFilterOrElseFalse(); final IQueryBuilder<I_AD_Column> queryBuilder = Services.get(IQueryBL.class).createQueryBuilder(I_AD_Column.class, this) .filter(selectedColumnsFilter); queryBuilder.orderBy() .addColumn(I_AD_Column.COLUMNNAME_AD_Table_ID) .addColumn(I_AD_Column.COLUMNNAME_AD_Column_ID); return queryBuilder .create() .list(I_AD_Column.class); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\process\AD_Column_CopySelectedToTable.java
1
请完成以下Java代码
private static final class OptionHelpFormatter implements HelpFormatter { private final List<OptionHelp> help = new ArrayList<>(); @Override public String format(Map<String, ? extends OptionDescriptor> options) { Comparator<OptionDescriptor> comparator = Comparator .comparing((optionDescriptor) -> optionDescriptor.options().iterator().next()); Set<OptionDescriptor> sorted = new TreeSet<>(comparator); sorted.addAll(options.values()); for (OptionDescriptor descriptor : sorted) { if (!descriptor.representsNonOptions()) { this.help.add(new OptionHelpAdapter(descriptor)); } } return ""; } Collection<OptionHelp> getOptionHelp() { return Collections.unmodifiableList(this.help); } } private static class OptionHelpAdapter implements OptionHelp { private final Set<String> options; private final String description; OptionHelpAdapter(OptionDescriptor descriptor) {
this.options = new LinkedHashSet<>(); for (String option : descriptor.options()) { String prefix = (option.length() != 1) ? "--" : "-"; this.options.add(prefix + option); } if (this.options.contains("--cp")) { this.options.remove("--cp"); this.options.add("-cp"); } this.description = descriptor.description(); } @Override public Set<String> getOptions() { return this.options; } @Override public String getUsageHelp() { return this.description; } } }
repos\spring-boot-4.0.1\cli\spring-boot-cli\src\main\java\org\springframework\boot\cli\command\options\OptionHandler.java
1
请完成以下Java代码
public class MetricsClientMeters { private MeterProvider<Counter> attemptCounter; private MeterProvider<DistributionSummary> sentMessageSizeDistribution; private MeterProvider<DistributionSummary> receivedMessageSizeDistribution; private MeterProvider<Timer> clientAttemptDuration; private MeterProvider<Timer> clientCallDuration; private MetricsClientMeters(Builder builder) { this.attemptCounter = builder.attemptCounter; this.sentMessageSizeDistribution = builder.sentMessageSizeDistribution; this.receivedMessageSizeDistribution = builder.receivedMessageSizeDistribution; this.clientAttemptDuration = builder.clientAttemptDuration; this.clientCallDuration = builder.clientCallDuration; } public MeterProvider<Counter> getAttemptCounter() { return this.attemptCounter; } public MeterProvider<DistributionSummary> getSentMessageSizeDistribution() { return this.sentMessageSizeDistribution; } public MeterProvider<DistributionSummary> getReceivedMessageSizeDistribution() { return this.receivedMessageSizeDistribution; } public MeterProvider<Timer> getClientAttemptDuration() { return this.clientAttemptDuration; } public MeterProvider<Timer> getClientCallDuration() { return this.clientCallDuration; } public static Builder newBuilder() { return new Builder(); } static class Builder { private MeterProvider<Counter> attemptCounter; private MeterProvider<DistributionSummary> sentMessageSizeDistribution; private MeterProvider<DistributionSummary> receivedMessageSizeDistribution; private MeterProvider<Timer> clientAttemptDuration; private MeterProvider<Timer> clientCallDuration; private Builder() {} public Builder setAttemptCounter(MeterProvider<Counter> counter) { this.attemptCounter = counter; return this; }
public Builder setSentMessageSizeDistribution(MeterProvider<DistributionSummary> distribution) { this.sentMessageSizeDistribution = distribution; return this; } public Builder setReceivedMessageSizeDistribution(MeterProvider<DistributionSummary> distribution) { this.receivedMessageSizeDistribution = distribution; return this; } public Builder setClientAttemptDuration(MeterProvider<Timer> timer) { this.clientAttemptDuration = timer; return this; } public Builder setClientCallDuration(MeterProvider<Timer> timer) { this.clientCallDuration = timer; return this; } public MetricsClientMeters build() { return new MetricsClientMeters(this); } } }
repos\grpc-spring-master\grpc-client-spring-boot-starter\src\main\java\net\devh\boot\grpc\client\metrics\MetricsClientMeters.java
1
请完成以下Java代码
public class ActivityCompletedListenerDelegate implements ActivitiEventListener { private List<BPMNElementEventListener<BPMNActivityCompletedEvent>> processRuntimeEventListeners; private ToActivityCompletedConverter converter; public ActivityCompletedListenerDelegate( List<BPMNElementEventListener<BPMNActivityCompletedEvent>> processRuntimeEventListeners, ToActivityCompletedConverter converter ) { this.processRuntimeEventListeners = processRuntimeEventListeners; this.converter = converter; } @Override public void onEvent(ActivitiEvent event) { if (event instanceof ActivitiActivityEvent) {
converter .from((ActivitiActivityEvent) event) .ifPresent(convertedEvent -> { for (BPMNElementEventListener<BPMNActivityCompletedEvent> listener : processRuntimeEventListeners) { listener.onEvent(convertedEvent); } }); } } @Override public boolean isFailOnException() { return false; } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-process-runtime-impl\src\main\java\org\activiti\runtime\api\event\internal\ActivityCompletedListenerDelegate.java
1
请完成以下Java代码
public int getCM_NewsItem_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_CM_NewsItem_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Content HTML. @param ContentHTML Contains the content itself */ public void setContentHTML (String ContentHTML) { set_Value (COLUMNNAME_ContentHTML, ContentHTML); } /** Get Content HTML. @return Contains the content itself */ public String getContentHTML () { return (String)get_Value(COLUMNNAME_ContentHTML); } /** 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 LinkURL. @param LinkURL Contains URL to a target */ public void setLinkURL (String LinkURL) { set_Value (COLUMNNAME_LinkURL, LinkURL); } /** Get LinkURL. @return Contains URL to a target */ public String getLinkURL () { return (String)get_Value(COLUMNNAME_LinkURL);
} /** Set Publication Date. @param PubDate Date on which this article will / should get published */ public void setPubDate (Timestamp PubDate) { set_Value (COLUMNNAME_PubDate, PubDate); } /** Get Publication Date. @return Date on which this article will / should get published */ public Timestamp getPubDate () { return (Timestamp)get_Value(COLUMNNAME_PubDate); } /** Set Title. @param Title Name this entity is referred to as */ public void setTitle (String Title) { set_Value (COLUMNNAME_Title, Title); } /** Get Title. @return Name this entity is referred to as */ public String getTitle () { return (String)get_Value(COLUMNNAME_Title); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_CM_NewsItem.java
1
请完成以下Java代码
public WFActivityType getHandledActivityType() { return HANDLED_ACTIVITY_TYPE; } @Override public UIComponent getUIComponent( final @NonNull WFProcess wfProcess, final @NonNull WFActivity wfActivity, final @NonNull JsonOpts jsonOpts) { return UserConfirmationSupportUtil.createUIComponent( UserConfirmationSupportUtil.UIComponentProps.builderFrom(wfActivity) .question(TranslatableStrings.adMessage(ARE_YOU_SURE).translate(jsonOpts.getAdLanguage())) .build()); } @Override public WFActivityStatus computeActivityState(final WFProcess wfProcess, final WFActivity completeDistributionWFActivity)
{ final DistributionJob job = DistributionMobileApplication.getDistributionJob(wfProcess); return computeActivityState(job); } public static WFActivityStatus computeActivityState(final DistributionJob job) { return job.isClosed() ? WFActivityStatus.COMPLETED : WFActivityStatus.NOT_STARTED; } @Override public WFProcess userConfirmed(final UserConfirmationRequest request) { request.assertActivityType(HANDLED_ACTIVITY_TYPE); return DistributionMobileApplication.mapDocument(request.getWfProcess(), distributionRestService::complete); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.distribution.rest-api\src\main\java\de\metas\distribution\mobileui\workflows_api\activity_handlers\CompleteDistributionWFActivityHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class JsonExternalSystemInfo { @NonNull @JsonProperty("externalSystemConfigId") JsonMetasfreshId externalSystemConfigId; @NonNull @JsonProperty("orgCode") String orgCode; @NonNull @JsonProperty("externalSystemChildConfigValue") String externalSystemChildConfigValue; @NonNull @JsonProperty("externalSystemName") JsonExternalSystemName externalSystemName;
@NonNull @JsonProperty("parameters") Map<String, String> parameters; @Builder public JsonExternalSystemInfo( @JsonProperty("externalSystemConfigId") final @NonNull JsonMetasfreshId externalSystemConfigId, @JsonProperty("externalSystemName") final @NonNull JsonExternalSystemName externalSystemName, @JsonProperty("orgCode") final @NonNull String orgCode, @JsonProperty("externalSystemChildConfigValue") final @NonNull String externalSystemChildConfigValue, @JsonProperty("parameters") final @NonNull Map<String, String> parameters) { this.externalSystemConfigId = externalSystemConfigId; this.externalSystemName = externalSystemName; this.orgCode = orgCode; this.externalSystemChildConfigValue = externalSystemChildConfigValue; this.parameters = parameters; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-externalsystem\src\main\java\de\metas\common\externalsystem\JsonExternalSystemInfo.java
2
请在Spring Boot框架中完成以下Java代码
public List<EntityLinkEntity> findEntityLinksByQuery(InternalEntityLinkQuery<EntityLinkEntity> query) { return getList("selectEntityLinksByQuery", query, (CachedEntityMatcher<EntityLinkEntity>) query, true); } @Override @SuppressWarnings("unchecked") public EntityLinkEntity findEntityLinkByQuery(InternalEntityLinkQuery<EntityLinkEntity> query) { return getEntity("selectEntityLinksByQuery", query, (SingleCachedEntityMatcher<EntityLinkEntity>) query, true); } @Override public void deleteEntityLinksByScopeIdAndScopeType(String scopeId, String scopeType) { Map<String, String> parameters = new HashMap<>(); parameters.put("scopeId", scopeId); parameters.put("scopeType", scopeType); bulkDelete("deleteEntityLinksByScopeIdAndScopeType", entityLinksByScopeIdAndTypeMatcher, parameters); }
@Override public void deleteEntityLinksByRootScopeIdAndType(String scopeId, String scopeType) { Map<String, String> parameters = new HashMap<>(); parameters.put("rootScopeId", scopeId); parameters.put("rootScopeType", scopeType); bulkDelete("deleteEntityLinksByRootScopeIdAndRootScopeType", entityLinksByRootScopeIdAndScopeTypeMatcher, parameters); } @Override protected IdGenerator getIdGenerator() { return entityLinkServiceConfiguration.getIdGenerator(); } }
repos\flowable-engine-main\modules\flowable-entitylink-service\src\main\java\org\flowable\entitylink\service\impl\persistence\entity\data\impl\MybatisEntityLinkDataManager.java
2
请完成以下Java代码
public final class CurrentAttributeValueContextProvider { private static final ThreadLocal<IAttributeValueContext> currentAttributesContextRef = new ThreadLocal<IAttributeValueContext>(); private CurrentAttributeValueContextProvider() { super(); } /** * @return {@link IAttributeValueContext} available or <code>null</code> */ public static IAttributeValueContext getCurrentAttributesContextOrNull() { return currentAttributesContextRef.get(); }
public static IAttributeValueContext setCurrentAttributesContext(final IAttributeValueContext attributesContext) { final IAttributeValueContext attributesContextOld = currentAttributesContextRef.get(); currentAttributesContextRef.set(attributesContext); return attributesContextOld; } /** * Makes sure current attribute context is not set (i.e. null) */ public static void assertNoCurrentContext() { final IAttributeValueContext currentAttributesContext = getCurrentAttributesContextOrNull(); Check.assumeNull(currentAttributesContext, "currentAttributesContext shall be null but it was {}", currentAttributesContext); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\api\CurrentAttributeValueContextProvider.java
1
请在Spring Boot框架中完成以下Java代码
public String prefix() { return "management.newrelic.metrics.export"; } @Override public boolean meterNameEventTypeEnabled() { return obtain(NewRelicProperties::isMeterNameEventTypeEnabled, NewRelicConfig.super::meterNameEventTypeEnabled); } @Override public String eventType() { return obtain(NewRelicProperties::getEventType, NewRelicConfig.super::eventType); } @Override public ClientProviderType clientProviderType() { return obtain(NewRelicProperties::getClientProviderType, NewRelicConfig.super::clientProviderType);
} @Override public @Nullable String apiKey() { return get(NewRelicProperties::getApiKey, NewRelicConfig.super::apiKey); } @Override public @Nullable String accountId() { return get(NewRelicProperties::getAccountId, NewRelicConfig.super::accountId); } @Override public String uri() { return obtain(NewRelicProperties::getUri, NewRelicConfig.super::uri); } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\newrelic\NewRelicPropertiesConfigAdapter.java
2
请在Spring Boot框架中完成以下Java代码
public JAXBElement<String> createVATIdentificationNumber(String value) { return new JAXBElement<String>(_VATIdentificationNumber_QNAME, String.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link UnitType }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link UnitType }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/documents", name = "Weight") public JAXBElement<UnitType> createWeight(UnitType value) { return new JAXBElement<UnitType>(_Weight_QNAME, UnitType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link UnitType }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link UnitType }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/documents", name = "Width")
public JAXBElement<UnitType> createWidth(UnitType value) { return new JAXBElement<UnitType>(_Width_QNAME, UnitType.class, null, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link String }{@code >} * * @param value * Java instance representing xml element's value. * @return * the new instance of {@link JAXBElement }{@code <}{@link String }{@code >} */ @XmlElementDecl(namespace = "http://erpel.at/schemas/1p0/documents", name = "ZIP") public JAXBElement<String> createZIP(String value) { return new JAXBElement<String>(_ZIP_QNAME, String.class, null, value); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\ObjectFactory.java
2
请完成以下Java代码
private JsonReportError extractJsonReportError(final RestClientResponseException ex) { final ObjectMapper jsonObjectMapper = JsonObjectMapperHolder.sharedJsonObjectMapper(); try { return jsonObjectMapper.readValue(ex.getResponseBodyAsString(), JsonReportError.class); } catch (final Exception ex2) { logger.warn("Error while decoding response exception. Will return a generic error", ex2); logger.warn("Original exception was... ", ex); final int httpStatusCode = ex.getRawStatusCode(); if (httpStatusCode == 404) { return JsonReportError.builder() .message("Got 404 when calling Report Servers API. Might be a config issue.") .build(); } else { return JsonReportError.builder() .message("Internal error") .build(); } } } private void writeLog(final String url, final Exception ex) {
Loggables.withLogger(logger, Level.ERROR) .addLog("Caught {} trying to invoke URL {}; message: {}", ex.getClass(), url, ex.getMessage(), ex); } @Override public void cacheReset() { final String mgtUrl = mgtRootUrl + "?" + ReportConstants.MGTSERVLET_PARAM_Action + "=" + ReportConstants.MGTSERVLET_ACTION_CacheReset; logger.debug("Calling URL {}", mgtUrl); final String result = restTemplate.getForObject(mgtUrl, String.class); logger.debug("result: {}", result); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.report\de.metas.report.jasper.client\src\main\java\de\metas\report\jasper\client\RemoteServletInvoker.java
1
请在Spring Boot框架中完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; nameSet = true; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; descriptionSet = true; } public Date getDueDate() { return dueDate; } public void setDueDate(Date dueDate) { this.dueDate = dueDate; duedateSet = true; } public int getPriority() { return priority; } public void setPriority(int priority) { this.priority = priority; prioritySet = true; } public String getParentTaskId() { return parentTaskId; } public void setParentTaskId(String parentTaskId) { this.parentTaskId = parentTaskId; parentTaskIdSet = true; } public void setCategory(String category) { this.category = category; categorySet = true; } public String getCategory() { return category; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; tenantIdSet = true; } public String getFormKey() { return formKey; }
public void setFormKey(String formKey) { this.formKey = formKey; formKeySet = true; } public boolean isOwnerSet() { return ownerSet; } public boolean isAssigneeSet() { return assigneeSet; } public boolean isDelegationStateSet() { return delegationStateSet; } public boolean isNameSet() { return nameSet; } public boolean isDescriptionSet() { return descriptionSet; } public boolean isDuedateSet() { return duedateSet; } public boolean isPrioritySet() { return prioritySet; } public boolean isParentTaskIdSet() { return parentTaskIdSet; } public boolean isCategorySet() { return categorySet; } public boolean isTenantIdSet() { return tenantIdSet; } public boolean isFormKeySet() { return formKeySet; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\runtime\task\TaskRequest.java
2
请在Spring Boot框架中完成以下Java代码
public class DefaultJwtSettingsValidator implements JwtSettingsValidator { @Override public void validate(JwtSettings jwtSettings) { if (StringUtils.isEmpty(jwtSettings.getTokenIssuer())) { throw new DataValidationException("JWT token issuer should be specified!"); } if (Optional.ofNullable(jwtSettings.getRefreshTokenExpTime()).orElse(0) < TimeUnit.MINUTES.toSeconds(15)) { throw new DataValidationException("JWT refresh token expiration time should be at least 15 minutes!"); } if (Optional.ofNullable(jwtSettings.getTokenExpirationTime()).orElse(0) < TimeUnit.MINUTES.toSeconds(1)) { throw new DataValidationException("JWT token expiration time should be at least 1 minute!"); } if (jwtSettings.getTokenExpirationTime() >= jwtSettings.getRefreshTokenExpTime()) { throw new DataValidationException("JWT token expiration time should greater than JWT refresh token expiration time!"); } if (StringUtils.isEmpty(jwtSettings.getTokenSigningKey())) { throw new DataValidationException("JWT token signing key should be specified!"); }
byte[] decodedKey; try { decodedKey = Base64.getDecoder().decode(jwtSettings.getTokenSigningKey()); } catch (Exception e) { throw new DataValidationException("JWT token signing key should be a valid Base64 encoded string! " + e.getMessage()); } if (Arrays.isNullOrEmpty(decodedKey)) { throw new DataValidationException("JWT token signing key should be non-empty after Base64 decoding!"); } if (decodedKey.length * Byte.SIZE < KEY_LENGTH && !isSigningKeyDefault(jwtSettings)) { throw new DataValidationException("JWT token signing key should be a Base64 encoded string representing at least 512 bits of data!"); } System.arraycopy(decodedKey, 0, RandomUtils.secure().randomBytes(decodedKey.length), 0, decodedKey.length); // secure memory } }
repos\thingsboard-master\application\src\main\java\org\thingsboard\server\service\security\auth\jwt\settings\DefaultJwtSettingsValidator.java
2
请在Spring Boot框架中完成以下Java代码
public class DerKurierShipperConfigRepository { private static final CCache<Integer, Optional<DerKurierShipperConfig>> cache = CCache.newCache( I_DerKurier_Shipper_Config.Table_Name + "#by#" + I_DerKurier_Shipper_Config.COLUMNNAME_M_Shipper_ID, 10, CCache.EXPIREMINUTES_Never); public DerKurierShipperConfig retrieveConfigForShipperIdOrNull(final int shipperId) { return cache .getOrLoad(shipperId, () -> retrieveConfigForShipperId0(shipperId)) .orElse(null); } public DerKurierShipperConfig retrieveConfigForShipperId(final int shipperId) { final Optional<DerKurierShipperConfig> config = cache.getOrLoad(shipperId, () -> retrieveConfigForShipperId0(shipperId)); return Check.assumePresent(config, "There has to be a DerKurier_Shipper_Config record for shipperId={}", shipperId); } private Optional<DerKurierShipperConfig> retrieveConfigForShipperId0(final int shipperId) { Check.assumeGreaterThanZero(shipperId, "shipperId"); final I_DerKurier_Shipper_Config shipperConfigRecord = Services.get(IQueryBL.class).createQueryBuilder(I_DerKurier_Shipper_Config.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DerKurier_Shipper_Config.COLUMN_M_Shipper_ID, shipperId)
.create() .firstOnly(I_DerKurier_Shipper_Config.class); if (shipperConfigRecord == null) { return Optional.empty(); } final DerKurierShipperConfig shipperConfig = DerKurierShipperConfig.builder() .restApiBaseUrl(shipperConfigRecord.getAPIServerBaseURL()) .customerNumber(shipperConfigRecord.getDK_CustomerNumber()) .parcelNumberAdSequenceId(shipperConfigRecord.getAD_Sequence_ID()) .deliveryOrderMailBoxId(MailboxId.ofRepoIdOrNull(shipperConfigRecord.getAD_MailBox_ID())) .deliveryOrderRecipientEmailOrNull(EMailAddress.ofNullableString(shipperConfigRecord.getEMail_To())) .collectorCode(shipperConfigRecord.getCollectorCode()) .customerCode(shipperConfigRecord.getCustomerCode()) .desiredTimeFrom(TimeUtil.asLocalTime(shipperConfigRecord.getDK_DesiredDeliveryTime_From())) .desiredTimeTo(TimeUtil.asLocalTime(shipperConfigRecord.getDK_DesiredDeliveryTime_To())) .build(); return Optional.of(shipperConfig); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\misc\DerKurierShipperConfigRepository.java
2
请在Spring Boot框架中完成以下Java代码
public List<ExternalSystemServiceModel> getAllByType(@NonNull @CacheAllowMutable final ExternalSystemType systemType) { return queryBL.createQueryBuilder(I_ExternalSystem_Service.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_ExternalSystem_Service.COLUMN_ExternalSystem_ID, externalSystemRepository.getByType(systemType).getId().getRepoId()) .create() .stream() .map(this::ofServiceRecord) .collect(ImmutableList.toImmutableList()); } @NonNull @Cached(cacheName = I_ExternalSystem_Service.Table_Name + "#by#" + I_ExternalSystem_Service.COLUMNNAME_Value) public Optional<ExternalSystemServiceModel> getByValue(@NonNull final String value) { return queryBL.createQueryBuilder(I_ExternalSystem_Service.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_ExternalSystem_Service.COLUMNNAME_Value, value) .create() .firstOnlyOptional(I_ExternalSystem_Service.class) .map(this::ofServiceRecord);
} @NonNull private ExternalSystemServiceModel ofServiceRecord(@NonNull final I_ExternalSystem_Service record) { return ExternalSystemServiceModel.builder() .id(ExternalSystemServiceId.ofRepoId(record.getExternalSystem_Service_ID())) .name(record.getName()) .description(record.getDescription()) .serviceValue(record.getValue()) .externalSystemType(externalSystemRepository.getById(ExternalSystemId.ofRepoId(record.getExternalSystem_ID())).getType()) .disableCommand(record.getDisableCommand()) .enableCommand(record.getEnableCommand()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java\de\metas\externalsystem\externalservice\model\ExternalSystemServiceRepository.java
2
请完成以下Java代码
public InputStream getInputStream() throws IOException { if (_data == null) { throw new IOException("no data"); } // a new stream must be returned each time. return new ByteArrayInputStream(_data); } /** * Throws exception */ @Override public OutputStream getOutputStream() throws IOException
{ throw new IOException("cannot do this"); } /** * Get Content Type * * @return MIME type e.g. text/html */ @Override public String getContentType() { return _mimeType; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\ByteArrayBackedDataSource.java
1
请完成以下Java代码
public boolean isDefaultForPicking() { return get_ValueAsBoolean(COLUMNNAME_IsDefaultForPicking); } @Override public void setIsDefaultLU (final boolean IsDefaultLU) { set_Value (COLUMNNAME_IsDefaultLU, IsDefaultLU); } @Override public boolean isDefaultLU() { return get_ValueAsBoolean(COLUMNNAME_IsDefaultLU); } @Override public void setM_HU_PI_ID (final int M_HU_PI_ID) { if (M_HU_PI_ID < 1) set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, null); else set_ValueNoCheck (COLUMNNAME_M_HU_PI_ID, M_HU_PI_ID); } @Override
public int getM_HU_PI_ID() { return get_ValueAsInt(COLUMNNAME_M_HU_PI_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); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_PI.java
1
请在Spring Boot框架中完成以下Java代码
public Optional<Todo> getTodoById(long id) { return todoRepository.findById(id); } @Override public void updateTodo(Todo todo) { todoRepository.save(todo); } @Override public void addTodo(String name, String desc, Date targetDate, boolean isDone) { todoRepository.save(new Todo(name, desc, targetDate, isDone)); } @Override public void deleteTodo(long id) { Optional<Todo> todo = todoRepository.findById(id);
if(todo.isPresent()) { todoRepository.delete(todo.get()); } } @Override public void saveTodo(Todo todo) { todoRepository.save(todo); } @Override public Object getTodosByUser(ModelMap name) { return null; } }
repos\SpringBoot-Projects-FullStack-master\Part-8 Spring Boot Real Projects\0.ProjectToDoinDBNoSec\src\main\java\spring\hibernate\service\TodoService.java
2
请完成以下Java代码
public Integer getPort() { return port; } public ClusterAppAssignMap setPort(Integer port) { this.port = port; return this; } public Set<String> getClientSet() { return clientSet; } public ClusterAppAssignMap setClientSet(Set<String> clientSet) { this.clientSet = clientSet; return this; } public Set<String> getNamespaceSet() { return namespaceSet; } public ClusterAppAssignMap setNamespaceSet(Set<String> namespaceSet) { this.namespaceSet = namespaceSet; return this; } public Boolean getBelongToApp() { return belongToApp;
} public ClusterAppAssignMap setBelongToApp(Boolean belongToApp) { this.belongToApp = belongToApp; return this; } public Double getMaxAllowedQps() { return maxAllowedQps; } public ClusterAppAssignMap setMaxAllowedQps(Double maxAllowedQps) { this.maxAllowedQps = maxAllowedQps; return this; } @Override public String toString() { return "ClusterAppAssignMap{" + "machineId='" + machineId + '\'' + ", ip='" + ip + '\'' + ", port=" + port + ", belongToApp=" + belongToApp + ", clientSet=" + clientSet + ", namespaceSet=" + namespaceSet + ", maxAllowedQps=" + maxAllowedQps + '}'; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\cluster\request\ClusterAppAssignMap.java
1
请完成以下Java代码
public de.metas.contracts.model.I_C_Flatrate_RefundConfig getC_Flatrate_RefundConfig() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class); } @Override public void setC_Flatrate_RefundConfig(de.metas.contracts.model.I_C_Flatrate_RefundConfig C_Flatrate_RefundConfig) { set_ValueFromPO(COLUMNNAME_C_Flatrate_RefundConfig_ID, de.metas.contracts.model.I_C_Flatrate_RefundConfig.class, C_Flatrate_RefundConfig); } /** Set C_Flatrate_RefundConfig. @param C_Flatrate_RefundConfig_ID C_Flatrate_RefundConfig */ @Override public void setC_Flatrate_RefundConfig_ID (int C_Flatrate_RefundConfig_ID) { if (C_Flatrate_RefundConfig_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Flatrate_RefundConfig_ID, Integer.valueOf(C_Flatrate_RefundConfig_ID)); } /** Get C_Flatrate_RefundConfig. @return C_Flatrate_RefundConfig */ @Override public int getC_Flatrate_RefundConfig_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Flatrate_RefundConfig_ID); if (ii == null) return 0; return ii.intValue();
} /** Set Vertrag-Rechnungskandidat. @param C_Invoice_Candidate_Term_ID Vertrag-Rechnungskandidat */ @Override public void setC_Invoice_Candidate_Term_ID (int C_Invoice_Candidate_Term_ID) { if (C_Invoice_Candidate_Term_ID < 1) set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, null); else set_ValueNoCheck (COLUMNNAME_C_Invoice_Candidate_Term_ID, Integer.valueOf(C_Invoice_Candidate_Term_ID)); } /** Get Vertrag-Rechnungskandidat. @return Vertrag-Rechnungskandidat */ @Override public int getC_Invoice_Candidate_Term_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_Invoice_Candidate_Term_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java-gen\de\metas\contracts\model\X_C_Invoice_Candidate_Assignment_Aggregate_V.java
1
请在Spring Boot框架中完成以下Java代码
public class BusinessController { private final BusinessService businessService; /** * 购买下单,模拟全局事务提交 * * @return */ @RequestMapping("/purchase/commit") public Boolean purchaseCommit(HttpServletRequest request) { businessService.purchase("1001", "2001", 1); return true; } /**
* 购买下单,模拟全局事务回滚 * * @return */ @RequestMapping("/purchase/rollback") public Boolean purchaseRollback() { try { businessService.purchase("1002", "2001", 1); } catch (Exception e) { e.printStackTrace(); return false; } return true; } }
repos\SpringBootLearning-master (1)\springboot-seata\sbm-business-service\src\main\java\com\gf\controller\BusinessController.java
2
请完成以下Java代码
public ContextVariables newChildContext(@NonNull final DocumentEntityDescriptor entityDescriptor) { return ContextVariables.builder() .name("Entity: " + ContextPath.extractName(entityDescriptor)) .parent(this) .contextVariables(extractFieldNames(entityDescriptor)) .build(); } public ContextVariables newLookupContext(String name) { return ContextVariables.builder() .name(name) .parent(this) .contextVariables(ImmutableSet.of( AccessSqlStringExpression.PARAM_UserRolePermissionsKey.getName(), IValidationContext.PARAMETER_ContextTableName, SqlForFetchingLookups.SQL_PARAM_ShowInactive.getName(), SqlForFetchingLookups.PARAM_Limit.getName(), SqlForFetchingLookups.PARAM_Offset.getName(), LookupDataSourceContext.PARAM_AD_Language.getName(), LookupDataSourceContext.PARAM_UserRolePermissionsKey.getName(), LookupDataSourceContext.PARAM_OrgAccessSql.getName(), LookupDataSourceContext.PARAM_Filter.getName(), LookupDataSourceContext.PARAM_FilterSql.getName(), LookupDataSourceContext.PARAM_FilterSqlWithoutWildcards.getName(), LookupDataSourceContext.PARAM_ViewId.getName(), LookupDataSourceContext.PARAM_ViewSize.getName() )) .build(); } private static ImmutableSet<String> extractFieldNames(final DocumentEntityDescriptor entityDescriptor) { return entityDescriptor.getFields().stream().map(DocumentFieldDescriptor::getFieldName).collect(ImmutableSet.toImmutableSet()); } public Set<String> findSimilar(String contextVariable) { final ImmutableSet.Builder<String> result = ImmutableSet.builder(); contextVariables.stream() .filter(item -> isSimilar(item, contextVariable)) .forEach(result::add); if (parent != null) { result.addAll(parent.findSimilar(contextVariable)); } return result.build(); }
private static boolean isSimilar(@NonNull String contextVariable1, @NonNull String contextVariable2) { return contextVariable1.equalsIgnoreCase(contextVariable2); } public boolean contains(@NonNull final String contextVariable) { if (contextVariables.contains(contextVariable)) { return true; } if (knownMissing.contains(contextVariable)) { return true; } return parent != null && parent.contains(contextVariable); } @Override @Deprecated public String toString() {return toSummaryString();} public String toSummaryString() { StringBuilder sb = new StringBuilder(); sb.append(name).append(":"); sb.append("\n\tContext variables: ").append(String.join(",", contextVariables)); if (!knownMissing.isEmpty()) { sb.append("\n\tKnown missing context variables: ").append(String.join(",", knownMissing)); } if (parent != null) { sb.append("\n--- parent: ----\n"); sb.append(parent.toSummaryString()); } return sb.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\health\ContextVariables.java
1
请完成以下Java代码
public String getClassName() { return variableContainer.getClass().getName(); } @Override public Object get(String s, Scriptable scriptable) { if (KEYWORD_EXECUTION.equals(s) && variableContainer instanceof DelegateExecution) { return variableContainer; } else if (KEYWORD_TASK.equals(s) && variableContainer instanceof DelegateTask) { return variableContainer; } else if (variableContainer.hasVariable(s)) { return variableContainer.getVariable(s); } else if (beans != null && beans.containsKey(s)) { return beans.get(s); } return null; } @Override public Object get(int i, Scriptable scriptable) { return null; } @Override public boolean has(String s, Scriptable scriptable) { return variableContainer.hasVariable(s); } @Override public boolean has(int i, Scriptable scriptable) { return false; } @Override public void put(String s, Scriptable scriptable, Object o) { } @Override public void put(int i, Scriptable scriptable, Object o) { } @Override public void delete(String s) { } @Override public void delete(int i) { } @Override public Scriptable getPrototype() {
return null; } @Override public void setPrototype(Scriptable scriptable) { } @Override public Scriptable getParentScope() { return null; } @Override public void setParentScope(Scriptable scriptable) { } @Override public Object[] getIds() { return null; } @Override public Object getDefaultValue(Class<?> aClass) { return null; } @Override public boolean hasInstance(Scriptable scriptable) { return false; } }
repos\flowable-engine-main\modules\flowable-secure-javascript\src\main\java\org\flowable\scripting\secure\impl\SecureScriptScope.java
1
请在Spring Boot框架中完成以下Java代码
public String chat(){ return "chat"; } //http://localhost:8080/ws @MessageMapping("/welcome")//浏览器发送请求通过@messageMapping 映射/welcome 这个地址。 @SendTo("/topic/getResponse")//服务器端有消息时,会订阅@SendTo 中的路径的浏览器发送消息。 public Response say(Message message) throws Exception { Thread.sleep(1000); return new Response("Welcome, " + message.getName() + "!"); } //http://localhost:8080/Welcome1 @RequestMapping("/Welcome1") @ResponseBody public String say2()throws Exception { ws.sendMessage(); return "is ok"; } @MessageMapping("/chat") //在springmvc 中可以直接获得principal,principal 中包含当前用户的信息 public void handleChat(Principal principal, Message message) { /** * 此处是一段硬编码。如果发送人是wyf 则发送给 wisely 如果发送人是wisely 就发送给 wyf。 * 通过当前用户,然后查找消息,如果查找到未读消息,则发送给当前用户。 */ if (principal.getName().equals("admin")) { //通过convertAndSendToUser 向用户发送信息,
// 第一个参数是接收消息的用户,第二个参数是浏览器订阅的地址,第三个参数是消息本身 messagingTemplate.convertAndSendToUser("abel", "/queue/notifications", principal.getName() + "-send:" + message.getName()); /** * 72 行操作相等于 * messagingTemplate.convertAndSend("/user/abel/queue/notifications",principal.getName() + "-send:" + message.getName()); */ } else { messagingTemplate.convertAndSendToUser("admin", "/queue/notifications", principal.getName() + "-send:" + message.getName()); } } }
repos\springBoot-master\springWebSocket\src\main\java\com\us\example\controller\WebSocketController.java
2
请完成以下Java代码
public class AD_ImpFormat_Row_Create_Based_OnTable extends JavaProcess { private static transient IADTableDAO tableDAO = Services.get(IADTableDAO.class); @Override protected String doIt() { final I_AD_ImpFormat impFormat = getRecord(I_AD_ImpFormat.class); final I_AD_Table table = tableDAO.retrieveTable(AdTableId.ofRepoId(impFormat.getAD_Table_ID())); final List<I_AD_Column> columns = tableDAO.retrieveColumnsForTable(table); final AtomicInteger index = new AtomicInteger(1); columns.stream().filter(column -> !DisplayType.isLookup(column.getAD_Reference_ID())) .forEach(column -> { final I_AD_ImpFormat_Row impRow = createImpFormatRow(impFormat, column, index); index.incrementAndGet(); addLog("@Created@ @AD_ImpFormat_Row_ID@: {}", impRow); }); return MSG_OK; } private I_AD_ImpFormat_Row createImpFormatRow(@NonNull final I_AD_ImpFormat impFormat, @NonNull final I_AD_Column column, final AtomicInteger index) { final I_AD_ImpFormat_Row impRow = newInstance(I_AD_ImpFormat_Row.class); impRow.setAD_Column_ID(column.getAD_Column_ID()); impRow.setAD_ImpFormat_ID(impFormat.getAD_ImpFormat_ID()); impRow.setName(column.getName()); final int adRefId = column.getAD_Reference_ID(); impRow.setDataType(extractDisplayType(adRefId)); impRow.setSeqNo(index.get()); impRow.setStartNo(index.get()); save(impRow); return impRow; }
private String extractDisplayType(final int adRefId) { if (DisplayType.isText(adRefId)) { return X_AD_ImpFormat_Row.DATATYPE_String; } else if (DisplayType.isNumeric(adRefId)) { return X_AD_ImpFormat_Row.DATATYPE_Number; } else if (DisplayType.isDate(adRefId)) { return X_AD_ImpFormat_Row.DATATYPE_Date; } else { return X_AD_ImpFormat_Row.DATATYPE_Constant; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\table\process\AD_ImpFormat_Row_Create_Based_OnTable.java
1
请完成以下Java代码
public OptimizeRestService getOptimizeRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); OptimizeRestService subResource = new OptimizeRestService(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; } public VersionRestService getVersionRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); VersionRestService subResource = new VersionRestService(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; } public SchemaLogRestService getSchemaLogRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); SchemaLogRestServiceImpl subResource = new SchemaLogRestServiceImpl(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; } public EventSubscriptionRestService getEventSubscriptionRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); EventSubscriptionRestServiceImpl subResource = new EventSubscriptionRestServiceImpl(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; }
public TelemetryRestService getTelemetryRestService(String engineName) { String rootResourcePath = getRelativeEngineUri(engineName).toASCIIString(); TelemetryRestServiceImpl subResource = new TelemetryRestServiceImpl(engineName, getObjectMapper()); subResource.setRelativeRootResourceUri(rootResourcePath); return subResource; } protected abstract URI getRelativeEngineUri(String engineName); protected ObjectMapper getObjectMapper() { return ProvidersUtil .resolveFromContext(providers, ObjectMapper.class, MediaType.APPLICATION_JSON_TYPE, this.getClass()); } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\AbstractProcessEngineRestServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class Routing { LocalDate sendDate; LocalDate deliveryDate; Participant sender; Participant consignee; List<String> viaHubs; String labelContent; String message; @Builder @JsonCreator public Routing( @JsonProperty("sendDate") @JsonFormat(shape = Shape.STRING, pattern = DATE_FORMAT) final LocalDate sendDate, @JsonProperty("deliveryDate") @JsonFormat(shape = Shape.STRING, pattern = DATE_FORMAT) final LocalDate deliveryDate, @JsonProperty("sender") final Participant sender,
@JsonProperty("consignee") final Participant consignee, @JsonProperty("viaHubs") final List<String> viaHubs, @JsonProperty("labelContent") final String labelContent, @JsonProperty("message") final String message) { this.sendDate = Check.assumeNotNull(sendDate, "Parameter sendDate may not be null"); this.deliveryDate = deliveryDate; this.sender = sender; this.consignee = consignee; this.viaHubs = Check.assumeNotNull(viaHubs, "Parameter viaHubs may not be null"); // note: may be empty this.labelContent = Check.assumeNotNull(labelContent, "Parameter labelContent may not be empty"); // note: may be empty this.message = Check.assumeNotEmpty(message, "Parameter message may not be empty"); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.derkurier\src\main\java\de\metas\shipper\gateway\derkurier\restapi\models\Routing.java
2
请完成以下Java代码
public HUAttributeChange mergeWithNextChange(final HUAttributeChange nextChange) { Check.assumeEquals(huId, nextChange.huId, "Invalid huId for {}. Expected: {}", nextChange, huId); Check.assumeEquals(attributeId, nextChange.attributeId, "Invalid attributeId for {}. Expected: {}", nextChange, attributeId); Check.assumeEquals(attributeValueType, nextChange.attributeValueType, "Invalid attributeValueType for {}. Expected: {}", nextChange, attributeValueType); return toBuilder() .valueNew(nextChange.getValueNew()) .date(nextChange.getDate()) .build(); } public AttributesKeyPart getNewAttributeKeyPartOrNull() { return toAttributeKeyPartOrNull(valueNew); } public AttributesKeyPart getOldAttributeKeyPartOrNull() { return toAttributeKeyPartOrNull(valueOld); } private AttributesKeyPart toAttributeKeyPartOrNull(final Object value) { if (AttributeValueType.STRING.equals(attributeValueType)) { final String valueStr = value != null ? value.toString() : null; return AttributesKeyPart.ofStringAttribute(attributeId, valueStr); } else if (AttributeValueType.NUMBER.equals(attributeValueType))
{ final BigDecimal valueBD = NumberUtils.asBigDecimal(value); return BigDecimal.ZERO.equals(valueBD) ? null : AttributesKeyPart.ofNumberAttribute(attributeId, valueBD); } else if (AttributeValueType.DATE.equals(attributeValueType)) { final LocalDate valueDate = TimeUtil.asLocalDate(value); return AttributesKeyPart.ofDateAttribute(attributeId, valueDate); } else if (AttributeValueType.LIST.equals(attributeValueType)) { final AttributeValueId attributeValueId = (AttributeValueId)value; return attributeValueId != null ? AttributesKeyPart.ofAttributeValueId(attributeValueId) : null; } else { throw new AdempiereException("Unknown attribute value type: " + attributeValueType); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\material\interceptor\HUAttributeChange.java
1
请完成以下Java代码
public Boolean validateToken(String token, UserDetails userDetails) { User user = (User) userDetails; String username = getUsernameFromToken( token ); return (username.equals( user.getUsername() ) && !isTokenExpired( token )); } /** * 获取token是否过期 */ public Boolean isTokenExpired(String token) { Date expiration = getExpirationDateFromToken( token ); return expiration.before( new Date() ); } /** * 根据token获取username */ public String getUsernameFromToken(String token) { String username = getClaimsFromToken( token ).getSubject(); return username; } /** * 获取token的过期时间 */ public Date getExpirationDateFromToken(String token) {
Date expiration = getClaimsFromToken( token ).getExpiration(); return expiration; } /** * 解析JWT */ private Claims getClaimsFromToken(String token) { Claims claims = Jwts.parser() .setSigningKey( SECRET ) .parseClaimsJws( token ) .getBody(); return claims; } }
repos\SpringBootLearning-master (1)\springboot-jwt\src\main\java\com\gf\utils\JwtTokenUtil.java
1
请完成以下Java代码
private static void startThread() { LOG.info("startThread"); cacheThreadPool.execute(new Runnable() { public void run() { try { while (true) { Thread.sleep(50);//50毫秒执行一次 // 如果当前活动线程等于最大线程,那么不执行 if (cacheThreadPool.getActiveCount() < cacheThreadPool.getMaxPoolSize()) { final NotifyTask task = tasks.poll(); if (task != null) { cacheThreadPool.execute(new Runnable() { public void run() { LOG.info(cacheThreadPool.getActiveCount() + "---------"); tasks.remove(task); task.run(); } }); } } } } catch (Exception e) { LOG.error("系统异常", e); e.printStackTrace(); } } }); } /** * 从数据库中取一次数据用来当系统启动时初始化 */ @SuppressWarnings("unchecked") private static void startInitFromDB() { LOG.info("get data from database"); int pageNum = 1;
int numPerPage = 500; PageParam pageParam = new PageParam(pageNum, numPerPage); // 查询状态和通知次数符合以下条件的数据进行通知 String[] status = new String[]{"101", "102", "200", "201"}; Integer[] notifyTime = new Integer[]{0, 1, 2, 3, 4}; // 组装查询条件 Map<String, Object> paramMap = new HashMap<String, Object>(); paramMap.put("statusList", status); paramMap.put("notifyTimeList", notifyTime); PageBean<RpNotifyRecord> pager = cacheRpNotifyService.queryNotifyRecordListPage(pageParam, paramMap); int totalSize = (pager.getNumPerPage() - 1) / numPerPage + 1;//总页数 while (pageNum <= totalSize) { List<RpNotifyRecord> list = pager.getRecordList(); for (int i = 0; i < list.size(); i++) { RpNotifyRecord notifyRecord = list.get(i); notifyRecord.setLastNotifyTime(new Date()); cacheNotifyQueue.addElementToList(notifyRecord); } pageNum++; LOG.info(String.format("调用通知服务.rpNotifyService.queryNotifyRecordListPage(%s, %s, %s)", pageNum, numPerPage, paramMap)); pageParam = new PageParam(pageNum, numPerPage); pager = cacheRpNotifyService.queryNotifyRecordListPage(pageParam, paramMap); } } }
repos\roncoo-pay-master\roncoo-pay-app-notify\src\main\java\com\roncoo\pay\AppNotifyApplication.java
1
请完成以下Java代码
public SpinXmlElement replace(SpinXmlElement newElement) { ensureNotNull("newElement", newElement); DomXmlElement element = ensureParamInstanceOf("newElement", newElement, DomXmlElement.class); adoptElement(element); Node parentNode = domElement.getParentNode(); if (parentNode == null) { throw LOG.elementHasNoParent(this); } try { parentNode.replaceChild(element.domElement, domElement); } catch (DOMException e) { throw LOG.unableToReplaceElementInImplementation(this, newElement, e); } return element; } public SpinXmlElement replaceChild(SpinXmlElement existingChildElement, SpinXmlElement newChildElement) { ensureNotNull("existingChildElement", existingChildElement); ensureNotNull("newChildElement", newChildElement); ensureChildElement(this, (DomXmlElement) existingChildElement); DomXmlElement existingChild = ensureParamInstanceOf("existingChildElement", existingChildElement, DomXmlElement.class); DomXmlElement newChild = ensureParamInstanceOf("newChildElement", newChildElement, DomXmlElement.class); adoptElement(newChild); try { domElement.replaceChild(newChild.domElement, existingChild.domElement); } catch (DOMException e) { throw LOG.unableToReplaceElementInImplementation(existingChild, newChildElement, e); } return this; } public SpinXPathQuery xPath(String expression) { XPath query = getXPathFactory().newXPath(); return new DomXPathQuery(this, query, expression, dataFormat); } /** * Adopts an xml dom element to the owner document of this element if necessary. * * @param elementToAdopt the element to adopt */ protected void adoptElement(DomXmlElement elementToAdopt) { Document document = this.domElement.getOwnerDocument(); Element element = elementToAdopt.domElement; if (!document.equals(element.getOwnerDocument())) { Node node = document.adoptNode(element); if (node == null) { throw LOG.unableToAdoptElement(elementToAdopt); } }
} public String toString() { StringWriter writer = new StringWriter(); writeToWriter(writer); return writer.toString(); } public void writeToWriter(Writer writer) { dataFormat.getWriter().writeToWriter(writer, this.domElement); } /** * Returns a XPath Factory * * @return the XPath factory */ protected XPathFactory getXPathFactory() { if (cachedXPathFactory == null) { cachedXPathFactory = XPathFactory.newInstance(); } return cachedXPathFactory; } public <C> C mapTo(Class<C> javaClass) { DataFormatMapper mapper = dataFormat.getMapper(); return mapper.mapInternalToJava(this.domElement, javaClass); } public <C> C mapTo(String javaClass) { DataFormatMapper mapper = dataFormat.getMapper(); return mapper.mapInternalToJava(this.domElement, javaClass); } }
repos\camunda-bpm-platform-master\spin\dataformat-xml-dom\src\main\java\org\camunda\spin\impl\xml\dom\DomXmlElement.java
1
请完成以下Java代码
public boolean enableLookupAutocomplete() { if (lookupAutoCompleter != null) { return true; // auto-complete already initialized } final Lookup lookup = getLookup(); if (lookup instanceof MLookup && lookup.getDisplayType() == DisplayType.Search) { final MLookup mlookup = (MLookup)lookup; final MLookupInfo lookupInfo = mlookup.getLookupInfo(); // FIXME: check what happens when lookup changes lookupAutoCompleter = new VLookupAutoCompleter(this.m_text, this, lookupInfo); return true; } return false; } // metas-2009_0021_AP1_CR054: end // metas @Override public boolean isAutoCommit() { return true; } // metas @Override public void addMouseListener(MouseListener l) { m_text.addMouseListener(l); m_button.addMouseListener(l); m_combo.getEditor().getEditorComponent().addMouseListener(l); // popup } private boolean isRowLoading() { if (m_mField == null) { return false; } final String rowLoadingStr = Env.getContext(Env.getCtx(), m_mField.getWindowNo(), m_mField.getVO().TabNo, GridTab.CTX_RowLoading); return "Y".equals(rowLoadingStr); } /* package */IValidationContext getValidationContext() { final GridField gridField = m_mField; // In case there is no GridField set (e.g. VLookup was created from a custom swing form)
if (gridField == null) { return IValidationContext.DISABLED; } final IValidationContext evalCtx = Services.get(IValidationRuleFactory.class).createValidationContext(gridField); // In case grid field validation context could not be created, disable validation // NOTE: in most of the cases when we reach this point is when we are in a custom form which used GridFields to create the lookups // but those custom fields does not have a GridTab // e.g. de.metas.paymentallocation.form.PaymentAllocationForm if (evalCtx == null) { return IValidationContext.DISABLED; } return evalCtx; } @Override public void addFocusListener(final FocusListener l) { getEditorComponent().addFocusListener(l); } @Override public void removeFocusListener(FocusListener l) { getEditorComponent().removeFocusListener(l); } public void setInfoWindowEnabled(final boolean enabled) { this.infoWindowEnabled = enabled; if (m_button != null) { m_button.setVisible(enabled); } } @Override public ICopyPasteSupportEditor getCopyPasteSupport() { return copyPasteSupport; } } // VLookup
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\grid\ed\VLookup.java
1
请完成以下Java代码
public void insert(DeadLetterJobEntity jobEntity) { insert(jobEntity, true); } @Override public void delete(DeadLetterJobEntity jobEntity) { super.delete(jobEntity); deleteExceptionByteArrayRef(jobEntity); if (jobEntity.getExecutionId() != null && isExecutionRelatedEntityCountEnabledGlobally()) { CountingExecutionEntity executionEntity = (CountingExecutionEntity) getExecutionEntityManager().findById( jobEntity.getExecutionId() ); if (isExecutionRelatedEntityCountEnabled(executionEntity)) { executionEntity.setDeadLetterJobCount(executionEntity.getDeadLetterJobCount() - 1); } } // Send event if (getEventDispatcher().isEnabled()) { getEventDispatcher().dispatchEvent( ActivitiEventBuilder.createEntityEvent(ActivitiEventType.ENTITY_DELETED, this) ); } } /** * Deletes a the byte array used to store the exception information. Subclasses may override * to provide custom implementations. */ protected void deleteExceptionByteArrayRef(DeadLetterJobEntity jobEntity) { ByteArrayRef exceptionByteArrayRef = jobEntity.getExceptionByteArrayRef(); if (exceptionByteArrayRef != null) {
exceptionByteArrayRef.delete(); } } protected DeadLetterJobEntity createDeadLetterJob(AbstractJobEntity job) { DeadLetterJobEntity newJobEntity = create(); newJobEntity.setJobHandlerConfiguration(job.getJobHandlerConfiguration()); newJobEntity.setJobHandlerType(job.getJobHandlerType()); newJobEntity.setExclusive(job.isExclusive()); newJobEntity.setRepeat(job.getRepeat()); newJobEntity.setRetries(job.getRetries()); newJobEntity.setEndDate(job.getEndDate()); newJobEntity.setExecutionId(job.getExecutionId()); newJobEntity.setProcessInstanceId(job.getProcessInstanceId()); newJobEntity.setProcessDefinitionId(job.getProcessDefinitionId()); // Inherit tenant newJobEntity.setTenantId(job.getTenantId()); newJobEntity.setJobType(job.getJobType()); return newJobEntity; } protected DeadLetterJobDataManager getDataManager() { return jobDataManager; } public void setJobDataManager(DeadLetterJobDataManager jobDataManager) { this.jobDataManager = jobDataManager; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\persistence\entity\DeadLetterJobEntityManagerImpl.java
1
请完成以下Java代码
public void addCaseDefinitionCacheEntry(String caseDefinitionId, CaseDefinitionCacheEntry caseDefinitionCacheEntry) { caseDefinitionCache.put(caseDefinitionId, caseDefinitionCacheEntry); } @Override public CaseDefinitionCacheEntry getCaseDefinitionCacheEntry(String caseDefinitionId) { return caseDefinitionCache.get(caseDefinitionId); } // getters and setters //////////////////////////////////////////////////////// @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getCategory() { return category; } @Override public void setCategory(String category) { this.category = category; } @Override public String getKey() { return key; } @Override public void setKey(String key) { this.key = key; } @Override public String getTenantId() { return tenantId; } @Override public void setTenantId(String tenantId) { this.tenantId = tenantId; } @Override public String getParentDeploymentId() { return parentDeploymentId; } @Override
public void setParentDeploymentId(String parentDeploymentId) { this.parentDeploymentId = parentDeploymentId; } @Override public void setResources(Map<String, EngineResource> resources) { this.resources = resources; } @Override public Date getDeploymentTime() { return deploymentTime; } @Override public void setDeploymentTime(Date deploymentTime) { this.deploymentTime = deploymentTime; } @Override public boolean isNew() { return isNew; } @Override public void setNew(boolean isNew) { this.isNew = isNew; } @Override public String getDerivedFrom() { return null; } @Override public String getDerivedFromRoot() { return null; } @Override public String getEngineVersion() { return null; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { return "CmmnDeploymentEntity[id=" + id + ", name=" + name + "]"; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\persistence\entity\CmmnDeploymentEntityImpl.java
1
请完成以下Java代码
Supplier<Integer> incrementer() { return () -> start++; } public void localVariableMultithreading() { boolean run = true; executor.execute(() -> { while (run) { // do operation } }); // commented because it doesn't compile, it's just an example of non-final local variables in lambdas // run = false; } public void instanceVariableMultithreading() { executor.execute(() -> { while (run) { // do operation } }); run = false; } /** * WARNING: always avoid this workaround!! */ public void workaroundSingleThread() { int[] holder = new int[] { 2 }; IntStream sums = IntStream .of(1, 2, 3) .map(val -> val + holder[0]); holder[0] = 0;
System.out.println(sums.sum()); } /** * WARNING: always avoid this workaround!! */ public void workaroundMultithreading() { int[] holder = new int[] { 2 }; Runnable runnable = () -> System.out.println(IntStream .of(1, 2, 3) .map(val -> val + holder[0]) .sum()); new Thread(runnable).start(); // simulating some processing try { Thread.sleep(new Random().nextInt(3) * 1000L); } catch (InterruptedException e) { throw new RuntimeException(e); } holder[0] = 0; } }
repos\tutorials-master\core-java-modules\core-java-lambdas-2\src\main\java\com\baeldung\lambdas\LambdaVariables.java
1
请完成以下Java代码
public Builder scope(String scope) { try { this.scope = AttributeScope.valueOf(scope); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Invalid attribute scope '" + scope + "'"); } return this; } public Builder keys(List<String> keys) { this.keys = keys; return this; } public Builder notifyDevice(boolean notifyDevice) { this.notifyDevice = notifyDevice; return this; } public Builder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) { this.previousCalculatedFieldIds = previousCalculatedFieldIds; return this; } public Builder tbMsgId(UUID tbMsgId) { this.tbMsgId = tbMsgId; return this; } public Builder tbMsgType(TbMsgType tbMsgType) { this.tbMsgType = tbMsgType; return this; } public Builder callback(FutureCallback<Void> callback) { this.callback = callback;
return this; } public Builder future(SettableFuture<Void> future) { return callback(new FutureCallback<>() { @Override public void onSuccess(Void result) { future.set(result); } @Override public void onFailure(Throwable t) { future.setException(t); } }); } public AttributesDeleteRequest build() { return new AttributesDeleteRequest( tenantId, entityId, scope, keys, notifyDevice, previousCalculatedFieldIds, tbMsgId, tbMsgType, requireNonNullElse(callback, NoOpFutureCallback.instance()) ); } } }
repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\AttributesDeleteRequest.java
1
请在Spring Boot框架中完成以下Java代码
public class DocumentReportRequest { @Nullable AdProcessId reportProcessId; @Nullable PrintFormatId printFormatIdToUse; @NonNull @Builder.Default DocumentReportFlavor flavor = DocumentReportFlavor.PRINT; @NonNull TableRecordReference documentRef; @NonNull ClientId clientId; @NonNull OrgId orgId; @NonNull UserId userId; @NonNull RoleId roleId; @Builder.Default int windowNo = Env.WINDOW_MAIN; @Builder.Default int tabNo = 0; boolean printPreview; @NonNull @Builder.Default PrintCopies printCopies = PrintCopies.ONE; @Nullable Language reportLanguage; @Nullable Integer asyncBatchId; @NonNull @Builder.Default DocumentPrintOptions printOptions = DocumentPrintOptions.NONE;
public DocumentReportRequest withPrintOptionsFallback(@NonNull final DocumentPrintOptions printOptionsFallback) { final DocumentPrintOptions newPrintOptions = this.printOptions.mergeWithFallback(printOptionsFallback); return !Objects.equals(this.printOptions, newPrintOptions) ? toBuilder().printOptions(newPrintOptions).build() : this; } public DocumentReportRequest withReportProcessId(final AdProcessId reportProcessId) { return !AdProcessId.equals(this.reportProcessId, reportProcessId) ? toBuilder().reportProcessId(reportProcessId).build() : this; } public DocumentReportRequest withReportLanguage(final Language reportLanguage) { return !Objects.equals(this.reportLanguage, reportLanguage) ? toBuilder().reportLanguage(reportLanguage).build() : this; } public DocumentReportRequest withPrintCopies(final PrintCopies printCopies) { return !Objects.equals(this.printCopies, printCopies) ? toBuilder().printCopies(printCopies).build() : this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\report\DocumentReportRequest.java
2
请完成以下Java代码
private IQueryBuilder<I_AD_Private_Access> queryPrivateAccess( @NonNull final Principal principal, @NonNull final TableRecordReference recordRef) { return queryBL .createQueryBuilder(I_AD_Private_Access.class) .addEqualsFilter(I_AD_Private_Access.COLUMNNAME_AD_User_ID, principal.getUserId()) .addEqualsFilter(I_AD_Private_Access.COLUMNNAME_AD_UserGroup_ID, principal.getUserGroupId()) .addEqualsFilter(I_AD_Private_Access.COLUMNNAME_AD_Table_ID, recordRef.getAD_Table_ID()) .addEqualsFilter(I_AD_Private_Access.COLUMNNAME_Record_ID, recordRef.getRecord_ID()); } @Override public void createMobileApplicationAccess(@NonNull final CreateMobileApplicationAccessRequest request) { mobileApplicationPermissionsRepository.createMobileApplicationAccess(request); resetCacheAfterTrxCommit(); } @Override public void deleteMobileApplicationAccess(@NonNull final MobileApplicationRepoId applicationId) { mobileApplicationPermissionsRepository.deleteMobileApplicationAccess(applicationId); } @Override public void deleteUserOrgAccessByUserId(final UserId userId) { queryBL.createQueryBuilder(I_AD_User_OrgAccess.class) .addEqualsFilter(I_AD_User_OrgAccess.COLUMNNAME_AD_User_ID, userId) .create() .delete(); } @Override public void deleteUserOrgAssignmentByUserId(final UserId userId) {
queryBL.createQueryBuilder(I_C_OrgAssignment.class) .addEqualsFilter(I_C_OrgAssignment.COLUMNNAME_AD_User_ID, userId) .create() .delete(); } @Value(staticConstructor = "of") private static class RoleOrgPermissionsCacheKey { RoleId roleId; AdTreeId adTreeOrgId; } @Value(staticConstructor = "of") private static class UserOrgPermissionsCacheKey { UserId userId; AdTreeId adTreeOrgId; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\security\impl\UserRolePermissionsDAO.java
1
请完成以下Java代码
public String getElementText() { return elementText; } public void setElementText(String elementText) { this.elementText = elementText; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getNamespacePrefix() { return namespacePrefix; } public void setNamespacePrefix(String namespacePrefix) { this.namespacePrefix = namespacePrefix; } public String getNamespace() { return namespace; } public void setNamespace(String namespace) { this.namespace = namespace; } public Map<String, List<ExtensionElement>> getChildElements() { return childElements; } public void addChildElement(ExtensionElement childElement) { if (childElement != null && StringUtils.isNotEmpty(childElement.getName())) { List<ExtensionElement> elementList = null; if (!this.childElements.containsKey(childElement.getName())) { elementList = new ArrayList<ExtensionElement>(); this.childElements.put(childElement.getName(), elementList); } this.childElements.get(childElement.getName()).add(childElement); }
} public void setChildElements(Map<String, List<ExtensionElement>> childElements) { this.childElements = childElements; } public ExtensionElement clone() { ExtensionElement clone = new ExtensionElement(); clone.setValues(this); return clone; } public void setValues(ExtensionElement otherElement) { setName(otherElement.getName()); setNamespacePrefix(otherElement.getNamespacePrefix()); setNamespace(otherElement.getNamespace()); setElementText(otherElement.getElementText()); setAttributes(otherElement.getAttributes()); childElements = new LinkedHashMap<String, List<ExtensionElement>>(); if (otherElement.getChildElements() != null && !otherElement.getChildElements().isEmpty()) { for (String key : otherElement.getChildElements().keySet()) { List<ExtensionElement> otherElementList = otherElement.getChildElements().get(key); if (otherElementList != null && !otherElementList.isEmpty()) { List<ExtensionElement> elementList = new ArrayList<ExtensionElement>(); for (ExtensionElement extensionElement : otherElementList) { elementList.add(extensionElement.clone()); } childElements.put(key, elementList); } } } } }
repos\Activiti-develop\activiti-core\activiti-bpmn-model\src\main\java\org\activiti\bpmn\model\ExtensionElement.java
1
请完成以下Java代码
protected Properties getParentCtx() { return getParentPO().getCtx(); } @Override protected String getParentTrxName() { return getParentPO().get_TrxName(); } @Override protected int getId() { final PO parentPO = getParentPO(); final String parentColumnName = getParentColumnName(); return parentPO.get_ValueAsInt(parentColumnName); } @Override protected boolean setId(final int id) { final PO parentPO = getParentPO(); final Integer value = id < 0 ? null : id;
final String parentColumnName = getParentColumnName(); final boolean ok = parentPO.set_ValueOfColumn(parentColumnName, value); if (!ok) { logger.warn("Cannot set " + parentColumnName + "=" + id + " to " + parentPO); } return ok; } public POCacheLocal copy(@NonNull final PO parentPO) { final POCacheLocal poCacheLocalNew = newInstance(parentPO, getParentColumnName(), getTableName()); poCacheLocalNew.poRef = this.poRef; return poCacheLocalNew; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\compiere\model\POCacheLocal.java
1
请完成以下Java代码
public static Password cast(final Object value) { return (Password)value; } public static final String OBFUSCATE_STRING = "********"; private final String password; private Password(@NonNull final String password) { this.password = password; } @Override public String toString() { return MoreObjects.toStringHelper(this)
.add("password", "********") .toString(); } @JsonValue public String toJson() { return OBFUSCATE_STRING; } public String getAsString() { return password; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\datatypes\Password.java
1
请完成以下Java代码
public class TreeModel implements Serializable { private static final long serialVersionUID = 4013193970046502756L; private String key; private String title; private String slotTitle; private Boolean isLeaf; private String icon; private Integer ruleFlag; private Map<String,String> scopedSlots; public Map<String, String> getScopedSlots() { return scopedSlots; } public void setScopedSlots(Map<String, String> scopedSlots) { this.scopedSlots = scopedSlots; } public String getKey() { return key; } public void setKey(String key) { this.key = key; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public Boolean getIsLeaf() { return isLeaf; } public void setIsLeaf(Boolean isLeaf) { this.isLeaf = isLeaf; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } private List<TreeModel> children; public List<TreeModel> getChildren() { return children; } public void setChildren(List<TreeModel> children) { this.children = children; } public TreeModel() { } public TreeModel(SysPermission permission) { this.key = permission.getId(); this.icon = permission.getIcon(); this.parentId = permission.getParentId(); this.title = permission.getName(); this.slotTitle = permission.getName(); this.value = permission.getId(); this.isLeaf = permission.isLeaf(); this.label = permission.getName(); if(!permission.isLeaf()) { this.children = new ArrayList<TreeModel>(); } } public TreeModel(String key,String parentId,String slotTitle,Integer ruleFlag,boolean isLeaf) { this.key = key;
this.parentId = parentId; this.ruleFlag=ruleFlag; this.slotTitle = slotTitle; Map<String,String> map = new HashMap(5); map.put("title", "hasDatarule"); this.scopedSlots = map; this.isLeaf = isLeaf; this.value = key; if(!isLeaf) { this.children = new ArrayList<TreeModel>(); } } private String parentId; private String label; private String value; public String getParentId() { return parentId; } public void setParentId(String parentId) { this.parentId = parentId; } /** * @return the label */ public String getLabel() { return label; } /** * @param label the label to set */ public void setLabel(String label) { this.label = label; } /** * @return the value */ public String getValue() { return value; } /** * @param value the value to set */ public void setValue(String value) { this.value = value; } public String getSlotTitle() { return slotTitle; } public void setSlotTitle(String slotTitle) { this.slotTitle = slotTitle; } public Integer getRuleFlag() { return ruleFlag; } public void setRuleFlag(Integer ruleFlag) { this.ruleFlag = ruleFlag; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\model\TreeModel.java
1
请完成以下Java代码
protected MigratingProcessElementInstance createMigratingEventScopeInstance(MigratingInstanceParseContext parseContext, EventSubscriptionEntity element) { ActivityImpl compensatingActivity = parseContext.getSourceProcessDefinition().findActivity(element.getActivityId()); MigrationInstruction migrationInstruction = getMigrationInstruction(parseContext, compensatingActivity); ActivityImpl eventSubscriptionTargetScope = null; if (migrationInstruction != null) { if (compensatingActivity.isCompensationHandler()) { ActivityImpl targetEventScope = (ActivityImpl) parseContext.getTargetActivity(migrationInstruction).getEventScope(); eventSubscriptionTargetScope = targetEventScope.findCompensationHandler(); } else { eventSubscriptionTargetScope = parseContext.getTargetActivity(migrationInstruction); } } ExecutionEntity eventScopeExecution = CompensationUtil.getCompensatingExecution(element); MigrationInstruction eventScopeInstruction = parseContext.findSingleMigrationInstruction(eventScopeExecution.getActivityId()); ActivityImpl targetScope = parseContext.getTargetActivity(eventScopeInstruction); MigratingEventScopeInstance migratingCompensationInstance = parseContext.getMigratingProcessInstance().addEventScopeInstance( eventScopeInstruction, eventScopeExecution, eventScopeExecution.getActivity(), targetScope, migrationInstruction, element, compensatingActivity, eventSubscriptionTargetScope); parseContext.consume(element); parseContext.submit(migratingCompensationInstance); parseDependentEntities(parseContext, migratingCompensationInstance); return migratingCompensationInstance; } protected MigrationInstruction getMigrationInstruction(MigratingInstanceParseContext parseContext, ActivityImpl activity) { if (activity.isCompensationHandler()) { Properties compensationHandlerProperties = activity.getProperties();
ActivityImpl eventTrigger = compensationHandlerProperties.get(BpmnProperties.COMPENSATION_BOUNDARY_EVENT); if (eventTrigger == null) { eventTrigger = compensationHandlerProperties.get(BpmnProperties.INITIAL_ACTIVITY); } return parseContext.findSingleMigrationInstruction(eventTrigger.getActivityId()); } else { return parseContext.findSingleMigrationInstruction(activity.getActivityId()); } } protected void parseDependentEntities(MigratingInstanceParseContext parseContext, MigratingEventScopeInstance migratingInstance) { ExecutionEntity representativeExecution = migratingInstance.resolveRepresentativeExecution(); List<VariableInstanceEntity> variables = new ArrayList<VariableInstanceEntity>( representativeExecution.getVariablesInternal()); parseContext.handleDependentVariables(migratingInstance, variables); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\migration\instance\parser\CompensationInstanceHandler.java
1
请完成以下Java代码
public java.lang.String getProductValue () { return (java.lang.String)get_Value(COLUMNNAME_ProductValue); } /** Set Reihenfolge. @param SeqNo Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Reihenfolge. @return Zur Bestimmung der Reihenfolge der Einträge; die kleinste Zahl kommt zuerst */ @Override public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } /** Set Gültig ab. @param ValidFrom Gültig ab inklusiv (erster Tag) */ @Override public void setValidFrom (java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } /** Get Gültig ab. @return Gültig ab inklusiv (erster Tag) */ @Override public java.sql.Timestamp getValidFrom ()
{ return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidFrom); } /** Set Gültig bis. @param ValidTo Gültig bis inklusiv (letzter Tag) */ @Override public void setValidTo (java.sql.Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Gültig bis. @return Gültig bis inklusiv (letzter Tag) */ @Override public java.sql.Timestamp getValidTo () { return (java.sql.Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.procurement.base\src\main\java-gen\de\metas\procurement\base\model\X_PMM_Product.java
1
请完成以下Java代码
public int getEmployeeUsingBeanPropertySqlParameterSource() { final Employee employee = new Employee(); employee.setFirstName("James"); final String SELECT_BY_ID = "SELECT COUNT(*) FROM EMPLOYEE WHERE FIRST_NAME = :firstName"; final SqlParameterSource namedParameters = new BeanPropertySqlParameterSource(employee); return namedParameterJdbcTemplate.queryForObject(SELECT_BY_ID, namedParameters, Integer.class); } public int[] batchUpdateUsingJDBCTemplate(final List<Employee> employees) { return jdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (?, ?, ?, ?)", new BatchPreparedStatementSetter() { @Override public void setValues(final PreparedStatement ps, final int i) throws SQLException { ps.setInt(1, employees.get(i).getId()); ps.setString(2, employees.get(i).getFirstName()); ps.setString(3, employees.get(i).getLastName()); ps.setString(4, employees.get(i).getAddress()); } @Override public int getBatchSize() { return 3; } }); }
public int[] batchUpdateUsingNamedParameterJDBCTemplate(final List<Employee> employees) { final SqlParameterSource[] batch = SqlParameterSourceUtils.createBatch(employees.toArray()); final int[] updateCounts = namedParameterJdbcTemplate.batchUpdate("INSERT INTO EMPLOYEE VALUES (:id, :firstName, :lastName, :address)", batch); return updateCounts; } public Employee getEmployeeUsingSimpleJdbcCall(int id) { SqlParameterSource in = new MapSqlParameterSource().addValue("in_id", id); Map<String, Object> out = simpleJdbcCall.execute(in); Employee emp = new Employee(); emp.setFirstName((String) out.get("FIRST_NAME")); emp.setLastName((String) out.get("LAST_NAME")); return emp; } }
repos\tutorials-master\persistence-modules\spring-persistence-simple\src\main\java\com\baeldung\spring\jdbc\template\guide\EmployeeDAO.java
1
请完成以下Java代码
public boolean isSkipIoMappings() { return skipIoMappings; } public boolean isExternallyTerminated() { return externallyTerminated; } public void setSkipCustomListeners(boolean skipCustomListeners) { this.skipCustomListeners = skipCustomListeners; } public void setSkipIoMappings(boolean skipIoMappings) { this.skipIoMappings = skipIoMappings; } public VariableMap getProcessVariables() { return processVariables; } public String getModificationReason() {
return modificationReason; } public void setModificationReason(String modificationReason) { this.modificationReason = modificationReason; } public String getAnnotation() { return annotation; } public void setAnnotationInternal(String annotation) { this.annotation = annotation; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\ProcessInstanceModificationBuilderImpl.java
1
请完成以下Java代码
private void assertVariableDoesNotExist(CreateTaskVariablePayload createTaskVariablePayload) { Map<String, VariableInstance> variables = taskService.getVariableInstancesLocal( createTaskVariablePayload.getTaskId() ); if (variables != null && variables.containsKey(createTaskVariablePayload.getName())) { throw new IllegalStateException("Variable already exists"); } } public void updateVariable(boolean isAdmin, UpdateTaskVariablePayload updateTaskVariablePayload) { if (!isAdmin) { assertCanModifyTask(getInternalTask(updateTaskVariablePayload.getTaskId())); } taskVariablesValidator.handleUpdateTaskVariablePayload(updateTaskVariablePayload); assertVariableExists(updateTaskVariablePayload); taskService.setVariableLocal( updateTaskVariablePayload.getTaskId(), updateTaskVariablePayload.getName(), updateTaskVariablePayload.getValue() ); } private void assertVariableExists(UpdateTaskVariablePayload updateTaskVariablePayload) { Map<String, VariableInstance> variables = taskService.getVariableInstancesLocal( updateTaskVariablePayload.getTaskId() ); if (variables == null) {
throw new IllegalStateException("Variable does not exist"); } if (!variables.containsKey(updateTaskVariablePayload.getName())) { throw new IllegalStateException("Variable does not exist"); } } public void handleCompleteTaskPayload(CompleteTaskPayload completeTaskPayload) { completeTaskPayload.setVariables( taskVariablesValidator.handlePayloadVariables(completeTaskPayload.getVariables()) ); } public void handleSaveTaskPayload(SaveTaskPayload saveTaskPayload) { saveTaskPayload.setVariables(taskVariablesValidator.handlePayloadVariables(saveTaskPayload.getVariables())); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-task-runtime-impl\src\main\java\org\activiti\runtime\api\impl\TaskRuntimeHelper.java
1
请完成以下Java代码
public void close() { } public float[] weightVector() { return null; } public boolean add(String str) { return true; } public int size() { return 0; } public int xsize() { return 0; } public int dsize() { return 0; } public int result(int i) { return 0; } public int answer(int i) { return 0; } public int y(int i) { return result(i); } public String y2(int i) { return ""; } public String yname(int i) { return ""; } public String x(int i, int j) { return ""; } public int ysize() { return 0; } public double prob(int i, int j) { return 0.0; } public double prob(int i) { return 0.0; } public double prob() { return 0.0; } public double alpha(int i, int j) { return 0.0; } public double beta(int i, int j) { return 0.0; } public double emissionCost(int i, int j) { return 0.0; } public double nextTransitionCost(int i, int j, int k) { return 0.0; } public double prevTransitionCost(int i, int j, int k) { return 0.0; } public double bestCost(int i, int j) { return 0.0; } public List<Integer> emissionVector(int i, int j) { return null; } public List<Integer> nextTransitionVector(int i, int j, int k) { return null; } public List<Integer> prevTransitionVector(int i, int j, int k) { return null; } public double Z() { return 0.0; } public boolean parse()
{ return true; } public boolean empty() { return true; } public boolean clear() { return true; } public boolean next() { return true; } public String parse(String str) { return ""; } public String toString() { return ""; } public String toString(String result, int size) { return ""; } public String parse(String str, int size) { return ""; } public String parse(String str, int size1, String result, int size2) { return ""; } // set token-level penalty. It would be useful for implementing // Dual decompositon decoding. // e.g. // "Dual Decomposition for Parsing with Non-Projective Head Automata" // Terry Koo Alexander M. Rush Michael Collins Tommi Jaakkola David Sontag public void setPenalty(int i, int j, double penalty) { } public double penalty(int i, int j) { return 0.0; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\crf\crfpp\Tagger.java
1
请完成以下Java代码
public void onKeyUp(KeyUpEvent event) { if (event.getNativeKeyCode() == KeyCodes.KEY_ENTER) { sendMessageToServer(); } } private void sendMessageToServer() { warningLabel.setText(""); String textToServer = nameField.getText(); if (textToServer == null || textToServer.isEmpty()) { warningLabel.setText("Please enter the message"); return; } sendButton.setEnabled(false); textToServerLabel.setText(textToServer); serverResponseLabel.setText(""); messageServiceAsync.sendMessage(textToServer, new AsyncCallback<String>() { public void onFailure(Throwable caught) {
serverResponseLabel.addStyleName("serverResponseLabelError"); serverResponseLabel.setHTML("server error occurred"); closeButton.setFocus(true); } public void onSuccess(String result) { serverResponseLabel.removeStyleName("serverResponseLabelError"); serverResponseLabel.setHTML(result); closeButton.setFocus(true); vPanel.setVisible(true); } }); } } // Add a handler to send the name to the server MyHandler handler = new MyHandler(); sendButton.addClickHandler(handler); nameField.addKeyUpHandler(handler); } }
repos\tutorials-master\web-modules\google-web-toolkit\src\main\java\com\baeldung\client\Google_web_toolkit.java
1
请在Spring Boot框架中完成以下Java代码
public String getCreatedBy() { return createdBy; } public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } public Instant getCreatedDate() { return createdDate; } public void setCreatedDate(Instant createdDate) { this.createdDate = createdDate; } public String getLastModifiedBy() {
return lastModifiedBy; } public void setLastModifiedBy(String lastModifiedBy) { this.lastModifiedBy = lastModifiedBy; } public Instant getLastModifiedDate() { return lastModifiedDate; } public void setLastModifiedDate(Instant lastModifiedDate) { this.lastModifiedDate = lastModifiedDate; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\AbstractAuditingEntity.java
2
请在Spring Boot框架中完成以下Java代码
private final void destroyExecutor(final ScheduledThreadPoolExecutor threadPoolExecutor) { threadPoolExecutor.shutdown(); logger.debug("Shutdown {}", threadPoolExecutor); } @Override public void destroy() { _threadNamePrefix2ThreadPoolExecutor.invalidateAll(); _threadNamePrefix2ThreadPoolExecutor.cleanUp(); } @Override public <T> Future<T> submit(final Callable<T> task, final String theadNamePrefix) { final ScheduledThreadPoolExecutor threadPoolExecutor = getCreateExecutor(theadNamePrefix); return threadPoolExecutor.submit(task); } @Override public <T> ScheduledFuture<T> schedule(final Callable<T> task,
final int time, final TimeUnit timeUnit, final String theadNamePrefix) { final ScheduledThreadPoolExecutor threadPoolExecutor = getCreateExecutor(theadNamePrefix); return threadPoolExecutor.schedule(task, time, timeUnit); } @Override public Future<?> submit(final Runnable task, final String theadNamePrefix) { final ScheduledThreadPoolExecutor threadPoolExecutor = getCreateExecutor(theadNamePrefix); return threadPoolExecutor.submit(task); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\service\impl\TaskExecutorService.java
2
请在Spring Boot框架中完成以下Java代码
public class LookupTemplate<KT extends Object> implements ILookupTemplate<KT> { private final Class<KT> keyType; private final String methodName; /** * Create an {@link ILookupTemplate} instance.<br> * <br> * Call {@link #createMandatoryValueLookup(Object)} or {@link #createNonMandatoryValueLookup(Object)} in order to instantiate an {@link ILookupValue} * * @param keyType * @param methodName */ public LookupTemplate(final Class<KT> keyType, final String methodName) { this.keyType = keyType; this.methodName = methodName; } @Override public Class<KT> getKeyType() { return keyType; }
@Override public String getMethodName() { return methodName; } @Override public ILookupValue<KT> createMandatoryValueLookup(final KT value) { return new LookupValue<KT>(this, value, true); // mandatoryLookup=true } @Override public ILookupValue<KT> createNonMandatoryValueLookup(final KT value) { return new LookupValue<KT>(this, value, false); // mandatoryLookup=false } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java\de\metas\edi\esb\commons\api\impl\LookupTemplate.java
2
请完成以下Java代码
public Sentence mergeCompoundWords() { ListIterator<IWord> listIterator = wordList.listIterator(); while (listIterator.hasNext()) { IWord word = listIterator.next(); if (word instanceof CompoundWord) { listIterator.set(new Word(word.getValue(), word.getLabel())); } } return this; } @Override
public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Sentence sentence = (Sentence) o; return toString().equals(sentence.toString()); } @Override public int hashCode() { return toString().hashCode(); } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\corpus\document\sentence\Sentence.java
1
请完成以下Java代码
private static LocalDate fromObjectToLocalDate(final Object valueObj, final ZoneId zoneId) { return fromObjectTo(valueObj, LocalDate.class, DateTimeConverters::fromJsonToLocalDate, (object) -> TimeUtil.asLocalDate(object, zoneId)); } @Nullable private static LocalTime fromObjectToLocalTime(final Object valueObj, final ZoneId zoneId) { return fromObjectTo(valueObj, LocalTime.class, DateTimeConverters::fromJsonToLocalTime, (object) -> TimeUtil.asLocalTime(object, zoneId)); } @Nullable private static ZonedDateTime fromObjectToZonedDateTime(final Object valueObj, final ZoneId zoneId) { return fromObjectTo(valueObj, ZonedDateTime.class, DateTimeConverters::fromJsonToZonedDateTime, (object) -> TimeUtil.asZonedDateTime(object, zoneId)); } @Nullable private static Instant fromObjectToInstant(final Object valueObj, final ZoneId zoneId) { return fromObjectTo(valueObj, Instant.class, DateTimeConverters::fromJsonToInstant, (object) -> TimeUtil.asInstant(object, zoneId)); } @Nullable private static <T> T fromObjectTo(
@NonNull final Object valueObj, @NonNull final Class<T> type, @NonNull final Function<String, T> fromJsonConverter, @NonNull final Function<Object, T> fromObjectConverter) { if (type.isInstance(valueObj)) { return type.cast(valueObj); } else if (valueObj instanceof CharSequence) { final String json = valueObj.toString().trim(); if (json.isEmpty()) { return null; } if (json.length() == 21 && json.charAt(10) == ' ') // json string - possible in JDBC format (`2016-06-11 00:00:00.0`) { final Timestamp timestamp = Timestamp.valueOf(json); return fromObjectConverter.apply(timestamp); } else { return fromJsonConverter.apply(json); } } else { return fromObjectConverter.apply(valueObj); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\converter\DateTimeConverters.java
1
请完成以下Java代码
public org.compiere.model.I_M_Nutrition_Fact getM_Nutrition_Fact() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Nutrition_Fact_ID, org.compiere.model.I_M_Nutrition_Fact.class); } @Override public void setM_Nutrition_Fact(org.compiere.model.I_M_Nutrition_Fact M_Nutrition_Fact) { set_ValueFromPO(COLUMNNAME_M_Nutrition_Fact_ID, org.compiere.model.I_M_Nutrition_Fact.class, M_Nutrition_Fact); } /** Set Nutrition Fact. @param M_Nutrition_Fact_ID Nutrition Fact */ @Override public void setM_Nutrition_Fact_ID (int M_Nutrition_Fact_ID) { if (M_Nutrition_Fact_ID < 1) set_Value (COLUMNNAME_M_Nutrition_Fact_ID, null); else set_Value (COLUMNNAME_M_Nutrition_Fact_ID, Integer.valueOf(M_Nutrition_Fact_ID)); } /** Get Nutrition Fact. @return Nutrition Fact */ @Override public int getM_Nutrition_Fact_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Nutrition_Fact_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(); } /** Set Product Nutrition. @param M_Product_Nutrition_ID Product Nutrition */ @Override public void setM_Product_Nutrition_ID (int M_Product_Nutrition_ID) { if (M_Product_Nutrition_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_Nutrition_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_Nutrition_ID, Integer.valueOf(M_Product_Nutrition_ID)); } /** Get Product Nutrition. @return Product Nutrition */ @Override public int getM_Product_Nutrition_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Nutrition_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Nutrition Quanitity. @param NutritionQty Nutrition Quanitity */ @Override public void setNutritionQty (java.lang.String NutritionQty) { set_Value (COLUMNNAME_NutritionQty, NutritionQty); } /** Get Nutrition Quanitity. @return Nutrition Quanitity */ @Override public java.lang.String getNutritionQty () { return (java.lang.String)get_Value(COLUMNNAME_NutritionQty); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Product_Nutrition.java
1
请在Spring Boot框架中完成以下Java代码
public Map<String, String> getSecrets() { return secrets; } public void setSecrets(Map<String, String> secrets) { Assert.notNull(secrets); Assert.hasText(secrets.get(SignatureAlgorithm.HS256.getJcaName())); Assert.hasText(secrets.get(SignatureAlgorithm.HS384.getJcaName())); Assert.hasText(secrets.get(SignatureAlgorithm.HS512.getJcaName())); this.secrets = secrets; } public byte[] getHS256SecretBytes() { return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS256.getJcaName())); } public byte[] getHS384SecretBytes() { return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS384.getJcaName())); } public byte[] getHS512SecretBytes() {
return TextCodec.BASE64.decode(secrets.get(SignatureAlgorithm.HS512.getJcaName())); } public Map<String, String> refreshSecrets() throws NoSuchAlgorithmException { SecretKey key = KeyGenerator.getInstance(SignatureAlgorithm.HS256.getJcaName()).generateKey(); secrets.put(SignatureAlgorithm.HS256.getJcaName(), TextCodec.BASE64.encode(key.getEncoded())); key = KeyGenerator.getInstance(SignatureAlgorithm.HS384.getJcaName()).generateKey(); secrets.put(SignatureAlgorithm.HS384.getJcaName(), TextCodec.BASE64.encode(key.getEncoded())); key = KeyGenerator.getInstance(SignatureAlgorithm.HS512.getJcaName()).generateKey(); secrets.put(SignatureAlgorithm.HS512.getJcaName(), TextCodec.BASE64.encode(key.getEncoded())); return secrets; } }
repos\tutorials-master\security-modules\jjwt\src\main\java\io\jsonwebtoken\jjwtfun\service\SecretService.java
2
请完成以下Java代码
public void setRecord_ID (final int Record_ID) { if (Record_ID < 0) set_Value (COLUMNNAME_Record_ID, null); else set_Value (COLUMNNAME_Record_ID, Record_ID); } @Override public int getRecord_ID() { return get_ValueAsInt(COLUMNNAME_Record_ID); } @Override public de.metas.handlingunits.model.I_M_HU getVHU() { return get_ValueAsPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class); } @Override
public void setVHU(final de.metas.handlingunits.model.I_M_HU VHU) { set_ValueFromPO(COLUMNNAME_VHU_ID, de.metas.handlingunits.model.I_M_HU.class, VHU); } @Override public void setVHU_ID (final int VHU_ID) { if (VHU_ID < 1) set_Value (COLUMNNAME_VHU_ID, null); else set_Value (COLUMNNAME_VHU_ID, VHU_ID); } @Override public int getVHU_ID() { return get_ValueAsInt(COLUMNNAME_VHU_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java-gen\de\metas\handlingunits\model\X_M_HU_Assignment.java
1
请完成以下Java代码
private static Color extractPrimaryAWTColor(@NonNull final I_AD_Color colorRecord) { return new Color(colorRecord.getRed(), colorRecord.getGreen(), colorRecord.getBlue()); } private static Color extractSecondaryAWTColor(@NonNull final I_AD_Color colorRecord) { return new Color(colorRecord.getRed(), colorRecord.getGreen(), colorRecord.getBlue()); } @Override public ColorId saveFlatColorAndReturnId(@NonNull String flatColorHexString) { final Color flatColor = MFColor.ofFlatColorHexString(flatColorHexString).getFlatColor(); final I_AD_Color existingColorRecord = Services.get(IQueryBL.class) .createQueryBuilderOutOfTrx(I_AD_Color.class) .addOnlyActiveRecordsFilter() .addOnlyContextClientOrSystem() .addEqualsFilter(I_AD_Color.COLUMNNAME_ColorType, X_AD_Color.COLORTYPE_NormalFlat) .addEqualsFilter(I_AD_Color.COLUMNNAME_Red, flatColor.getRed()) .addEqualsFilter(I_AD_Color.COLUMNNAME_Green, flatColor.getGreen()) .addEqualsFilter(I_AD_Color.COLUMNNAME_Blue, flatColor.getBlue()) .orderByDescending(I_AD_Color.COLUMNNAME_AD_Client_ID) .orderBy(I_AD_Color.COLUMNNAME_AD_Color_ID) .create() .first(); if (existingColorRecord != null) { return ColorId.ofRepoId(existingColorRecord.getAD_Color_ID()); } final I_AD_Color newColorRecord = InterfaceWrapperHelper.newInstanceOutOfTrx(I_AD_Color.class); newColorRecord.setAD_Org_ID(Env.CTXVALUE_AD_Org_ID_Any); newColorRecord.setName(flatColorHexString.toLowerCase()); newColorRecord.setColorType(X_AD_Color.COLORTYPE_NormalFlat); newColorRecord.setRed(flatColor.getRed()); newColorRecord.setGreen(flatColor.getGreen()); newColorRecord.setBlue(flatColor.getBlue()); // newColorRecord.setAlpha(0); newColorRecord.setImageAlpha(BigDecimal.ZERO); // InterfaceWrapperHelper.save(newColorRecord);
return ColorId.ofRepoId(newColorRecord.getAD_Color_ID()); } @Override public ColorId getColorIdByName(final String colorName) { return colorIdByName.getOrLoad(colorName, () -> retrieveColorIdByName(colorName)); } private ColorId retrieveColorIdByName(final String colorName) { final int colorRepoId = Services.get(IQueryBL.class) .createQueryBuilder(I_AD_Color.class) .addOnlyActiveRecordsFilter() .addOnlyContextClientOrSystem() .addEqualsFilter(I_AD_Color.COLUMNNAME_Name, colorName) .create() .firstIdOnly(); return ColorId.ofRepoIdOrNull(colorRepoId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\util\impl\ColorRepository.java
1
请在Spring Boot框架中完成以下Java代码
private int resolvePartitionIndexForEntity(UUID entityId) { return partitionService.resolvePartitionIndex(entityId, snmpTransportsCount); } private void recalculatePartitions(List<ServiceInfo> otherServices, ServiceInfo currentService) { log.info("Recalculating partitions for SNMP transports"); List<ServiceInfo> snmpTransports = Stream.concat(otherServices.stream(), Stream.of(currentService)) .filter(service -> service.getTransportsList().contains(snmpTransportService.getName())) .sorted(Comparator.comparing(ServiceInfo::getServiceId)) .collect(Collectors.toList()); log.trace("Found SNMP transports: {}", snmpTransports); int previousCurrentTransportPartitionIndex = currentTransportPartitionIndex; int previousSnmpTransportsCount = snmpTransportsCount; if (!snmpTransports.isEmpty()) { for (int i = 0; i < snmpTransports.size(); i++) { if (snmpTransports.get(i).equals(currentService)) {
currentTransportPartitionIndex = i; break; } } snmpTransportsCount = snmpTransports.size(); } if (snmpTransportsCount != previousSnmpTransportsCount || currentTransportPartitionIndex != previousCurrentTransportPartitionIndex) { log.info("SNMP transports partitions have changed: transports count = {}, current transport partition index = {}", snmpTransportsCount, currentTransportPartitionIndex); eventPublisher.publishEvent(new SnmpTransportListChangedEvent()); } else { log.info("SNMP transports partitions have not changed"); } } }
repos\thingsboard-master\common\transport\snmp\src\main\java\org\thingsboard\server\transport\snmp\service\SnmpTransportBalancingService.java
2
请在Spring Boot框架中完成以下Java代码
private static Map<String, String> uriVariables(HttpServletRequest request) { String baseUrl = getApplicationUri(request); Map<String, String> uriVariables = new HashMap<>(); UriComponents uriComponents = UriComponentsBuilder.fromUriString(baseUrl) .replaceQuery(null) .fragment(null) .build(); String scheme = uriComponents.getScheme(); uriVariables.put("baseScheme", (scheme != null) ? scheme : ""); String host = uriComponents.getHost(); uriVariables.put("baseHost", (host != null) ? host : ""); // following logic is based on HierarchicalUriComponents#toUriString() int port = uriComponents.getPort(); uriVariables.put("basePort", (port == -1) ? "" : ":" + port); String path = uriComponents.getPath(); if (StringUtils.hasLength(path) && path.charAt(0) != PATH_DELIMITER) { path = PATH_DELIMITER + path; } uriVariables.put("basePath", (path != null) ? path : ""); uriVariables.put("baseUrl", uriComponents.toUriString()); return uriVariables; } private static String getApplicationUri(HttpServletRequest request) { UriComponents uriComponents = UriComponentsBuilder.fromUriString(UrlUtils.buildFullRequestUrl(request)) .replacePath(request.getContextPath())
.replaceQuery(null) .fragment(null) .build(); return uriComponents.toUriString(); } /** * A class for resolving {@link RelyingPartyRegistration} URIs */ public static final class UriResolver { private final Map<String, String> uriVariables; private UriResolver(Map<String, String> uriVariables) { this.uriVariables = uriVariables; } public String resolve(String uri) { if (uri == null) { return null; } return UriComponentsBuilder.fromUriString(uri).buildAndExpand(this.uriVariables).toUriString(); } } }
repos\spring-security-main\saml2\saml2-service-provider\src\main\java\org\springframework\security\saml2\provider\service\web\RelyingPartyRegistrationPlaceholderResolvers.java
2
请完成以下Java代码
public String getCallbackType() { return callbackType; } @Override public void setCallbackType(String callbackType) { this.callbackType = callbackType; } @Override public String getReferenceId() { return referenceId; } @Override public void setReferenceId(String referenceId) { this.referenceId = referenceId; } @Override public String getReferenceType() { return referenceType; } @Override public void setReferenceType(String referenceType) { this.referenceType = referenceType; } @Override public String getPropagatedStageInstanceId() { return propagatedStageInstanceId; } @Override public void setPropagatedStageInstanceId(String propagatedStageInstanceId) { this.propagatedStageInstanceId = propagatedStageInstanceId; } @Override public Map<String, Object> getProcessVariables() { Map<String, Object> variables = new HashMap<>(); if (queryVariables != null) { for (HistoricVariableInstanceEntity variableInstance : queryVariables) { if (variableInstance.getId() != null && variableInstance.getTaskId() == null) { variables.put(variableInstance.getName(), variableInstance.getValue()); } }
} return variables; } @Override public List<HistoricVariableInstanceEntity> getQueryVariables() { if (queryVariables == null && Context.getCommandContext() != null) { queryVariables = new HistoricVariableInitializingList(); } return queryVariables; } @Override public void setQueryVariables(List<HistoricVariableInstanceEntity> queryVariables) { this.queryVariables = queryVariables; } // common methods ////////////////////////////////////////////////////////// @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("HistoricProcessInstanceEntity[id=").append(getId()) .append(", definition=").append(getProcessDefinitionId()); if (superProcessInstanceId != null) { sb.append(", superProcessInstanceId=").append(superProcessInstanceId); } if (referenceId != null) { sb.append(", referenceId=").append(referenceId) .append(", referenceType=").append(referenceType); } if (StringUtils.isNotEmpty(tenantId)) { sb.append(", tenantId=").append(tenantId); } sb.append("]"); return sb.toString(); } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\persistence\entity\HistoricProcessInstanceEntityImpl.java
1
请完成以下Java代码
private void setHyperlinkListener() { if (hyperlinkListenerClass == null) { return; } try { final HyperlinkListener listener = (HyperlinkListener)hyperlinkListenerClass.newInstance(); m_textPane.addHyperlinkListener(listener); } catch (Exception e) { log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClass, e); } } private static Class<?> hyperlinkListenerClass; static {
final String hyperlinkListenerClassname = "de.metas.adempiere.gui.ADHyperlinkHandler"; try { hyperlinkListenerClass = Thread.currentThread().getContextClassLoader().loadClass(hyperlinkListenerClassname); } catch (Exception e) { log.warn("Cannot instantiate hyperlink listener - " + hyperlinkListenerClassname, e); } } @Override public final ICopyPasteSupportEditor getCopyPasteSupport() { return copyPasteSupport; } // metas: end } // CTextPane
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\swing\CTextPane.java
1
请完成以下Java代码
public int getM_Inventory_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Inventory_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Move Confirm. @param M_MovementConfirm_ID Inventory Move Confirmation */ public void setM_MovementConfirm_ID (int M_MovementConfirm_ID) { if (M_MovementConfirm_ID < 1) set_ValueNoCheck (COLUMNNAME_M_MovementConfirm_ID, null); else set_ValueNoCheck (COLUMNNAME_M_MovementConfirm_ID, Integer.valueOf(M_MovementConfirm_ID)); } /** Get Move Confirm. @return Inventory Move Confirmation */ public int getM_MovementConfirm_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_MovementConfirm_ID); if (ii == null) return 0; return ii.intValue(); } public I_M_Movement getM_Movement() throws RuntimeException { return (I_M_Movement)MTable.get(getCtx(), I_M_Movement.Table_Name) .getPO(getM_Movement_ID(), get_TrxName()); } /** Set Inventory Move. @param M_Movement_ID Movement of Inventory */ public void setM_Movement_ID (int M_Movement_ID) { if (M_Movement_ID < 1) set_Value (COLUMNNAME_M_Movement_ID, null); else set_Value (COLUMNNAME_M_Movement_ID, Integer.valueOf(M_Movement_ID)); } /** Get Inventory Move. @return Movement of Inventory */ public int getM_Movement_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Movement_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 Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_MovementConfirm.java
1
请完成以下Java代码
public void setPassword(char[] password) { this.password = password; } @Override public Object getPrincipal() { return this.getUsername(); } @Override public Object getCredentials() { return this.getPassword(); } @Override public String getHost() { return this.host; } @Override public void setHost(String host) { this.host = host; } @Override public boolean isRememberMe() { return this.rememberMe;
} @Override public void setRememberMe(boolean rememberMe) { this.rememberMe = rememberMe; } public String getAccessToken() { return accessToken; } public void setAccessToken(String accessToken) { this.accessToken = accessToken; } @Override public void clear() { super.clear(); this.accessToken = null; } }
repos\springBoot-master\springboot-shiro2\src\main\java\cn\abel\rest\shiro\credentials\ThirdPartySupportedToken.java
1
请完成以下Java代码
public class ProgrammerAnnotated { private String name; private String favouriteLanguage; @JsonMerge private Keyboard keyboard; public ProgrammerAnnotated(String name, String favouriteLanguage, Keyboard keyboard) { this.name = name; this.favouriteLanguage = favouriteLanguage; this.keyboard = keyboard; } public String getName() { return name; } public void setName(String name) {
this.name = name; } public String getFavouriteLanguage() { return favouriteLanguage; } public Keyboard getKeyboard() { return keyboard; } @Override public String toString() { return "Programmer{" + "name='" + name + '\'' + ", favouriteLanguage='" + favouriteLanguage + '\'' + ", keyboard=" + keyboard + '}'; } }
repos\tutorials-master\jackson-modules\jackson-annotations\src\main\java\com\baeldung\jackson\jsonmerge\ProgrammerAnnotated.java
1
请完成以下Java代码
public <T> T readValue(String value, String typeIdentifier) { try { Class<?> cls = Class.forName(typeIdentifier); return (T) readValue(value, cls); } catch (ClassNotFoundException e) { JavaType javaType = constructJavaTypeFromCanonicalString(typeIdentifier); return readValue(value, javaType); } } public <T> T readValue(String value, Class<T> cls) { try { return objectMapper.readValue(value, cls); } catch (JsonParseException e) { throw LOG.unableToReadValue(value, e); } catch (JsonMappingException e) { throw LOG.unableToReadValue(value, e); } catch (IOException e) { throw LOG.unableToReadValue(value, e); } } protected <C> C readValue(String value, JavaType type) { try { return objectMapper.readValue(value, type); } catch (JsonParseException e) { throw LOG.unableToReadValue(value, e); } catch (JsonMappingException e) { throw LOG.unableToReadValue(value, e); } catch (IOException e) {
throw LOG.unableToReadValue(value, e); } } public JavaType constructJavaTypeFromCanonicalString(String canonicalString) { try { return TypeFactory.defaultInstance().constructFromCanonical(canonicalString); } catch (IllegalArgumentException e) { throw LOG.unableToConstructJavaType(canonicalString, e); } } public String getCanonicalTypeName(Object value) { ensureNotNull("value", value); for (TypeDetector typeDetector : typeDetectors) { if (typeDetector.canHandle(value)) { return typeDetector.detectType(value); } } throw LOG.unableToDetectCanonicalType(value); } }
repos\camunda-bpm-platform-master\clients\java\client\src\main\java\org\camunda\bpm\client\variable\impl\format\json\JacksonJsonDataFormat.java
1
请完成以下Java代码
public Store setSessionStoreProperties(String userName, String password, Properties properties) throws MessagingException { Session session = Session.getDefaultInstance(properties); Store store = session.getStore("pop3"); store.connect(userName, password); return store; } public Properties setMailServerProperties(String host, String port) { Properties properties = new Properties(); properties.put("mail.pop3.host", host); properties.put("mail.pop3.port", port); properties.setProperty("mail.pop3.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); properties.setProperty("mail.pop3.socketFactory.fallback", "false"); properties.setProperty("mail.pop3.socketFactory.port", String.valueOf(port)); return properties; } public static void main(String[] args) { String host = "pop.gmail.com"; String port = "995"; String userName = "your_email"; String password = "your_password"; String saveDirectory = "valid_folder_path";
DownloadEmailAttachments receiver = new DownloadEmailAttachments(); receiver.setSaveDirectory(saveDirectory); try { receiver.downloadEmailAttachments(host, port, userName, password); } catch (NoSuchProviderException ex) { System.out.println("No provider for pop3."); ex.printStackTrace(); } catch (MessagingException ex) { System.out.println("Could not connect to the message store"); ex.printStackTrace(); } catch (IOException ex) { ex.printStackTrace(); } } }
repos\tutorials-master\core-java-modules\core-java-networking-3\src\main\java\com\baeldung\downloadattachments\DownloadEmailAttachments.java
1
请完成以下Java代码
public final class NullAllocationResult implements IAllocationResult { public static final NullAllocationResult instance = new NullAllocationResult(); private NullAllocationResult() { super(); } @Override public BigDecimal getQtyToAllocate() { return BigDecimal.ZERO; } @Override public BigDecimal getQtyAllocated() { return BigDecimal.ZERO; } @Override public boolean isZeroAllocated() { return true; } /** * @return true always */ @Override
public boolean isCompleted() { return true; } @Override public List<IHUTransactionCandidate> getTransactions() { return Collections.emptyList(); } @Override public List<IHUTransactionAttribute> getAttributeTransactions() { return Collections.emptyList(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\allocation\impl\NullAllocationResult.java
1
请完成以下Java代码
public class CalendarNonBusinessDays implements IBusinessDayMatcher { private final ImmutableList<NonBusinessDay> nonBusinessDays; @Builder private CalendarNonBusinessDays( @NonNull @Singular final ImmutableList<NonBusinessDay> nonBusinessDays) { this.nonBusinessDays = nonBusinessDays; } @Override public String toString() { return MoreObjects.toStringHelper(this) .add("nonBusinessDays.count", nonBusinessDays.size()) .toString();
} @Override public boolean isBusinessDay(@NonNull final LocalDate date) { return !isNonBusinessDay(date); } public boolean isNonBusinessDay(@NonNull final LocalDate date) { return nonBusinessDays .stream() .anyMatch(nonBusinessDay -> nonBusinessDay.isMatching(date)); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\calendar\CalendarNonBusinessDays.java
1
请完成以下Java代码
public void setConnection_timeout (final int Connection_timeout) { set_Value (COLUMNNAME_Connection_timeout, Connection_timeout); } @Override public int getConnection_timeout() { return get_ValueAsInt(COLUMNNAME_Connection_timeout); } @Override public void setPostgREST_ResultDirectory (final String PostgREST_ResultDirectory) { set_Value (COLUMNNAME_PostgREST_ResultDirectory, PostgREST_ResultDirectory); } @Override public String getPostgREST_ResultDirectory() { return get_ValueAsString(COLUMNNAME_PostgREST_ResultDirectory); } @Override public void setRead_timeout (final int Read_timeout) { set_Value (COLUMNNAME_Read_timeout, Read_timeout); }
@Override public int getRead_timeout() { return get_ValueAsInt(COLUMNNAME_Read_timeout); } @Override public void setS_PostgREST_Config_ID (final int S_PostgREST_Config_ID) { if (S_PostgREST_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_S_PostgREST_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_S_PostgREST_Config_ID, S_PostgREST_Config_ID); } @Override public int getS_PostgREST_Config_ID() { return get_ValueAsInt(COLUMNNAME_S_PostgREST_Config_ID); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_PostgREST_Config.java
1
请在Spring Boot框架中完成以下Java代码
public static void logResult(String sWord) { FileWriter writer = null; try { writer = new FileWriter(LOG_PATH + "alipay_log_" + System.currentTimeMillis()+".txt"); writer.write(sWord); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * 生成文件摘要 * @param strFilePath 文件路径 * @param file_digest_type 摘要算法
* @return 文件摘要结果 */ public static String getAbstract(String strFilePath, String file_digest_type) throws IOException { PartSource file = new FilePartSource(new File(strFilePath)); if(file_digest_type.equals("MD5")){ return DigestUtils.md5Hex(file.createInputStream()); } else if(file_digest_type.equals("SHA")) { return DigestUtils.sha256Hex(file.createInputStream()); } else { return ""; } } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\reconciliation\utils\alipay\AlipayCore.java
2
请完成以下Java代码
public Iterator<I_C_Flatrate_Term> retrieveTermsWithMissingCandidates(@Nullable final QueryLimit limit_IGNORED) { return ImmutableList .<I_C_Flatrate_Term> of() .iterator(); } @NonNull @Override public CandidatesAutoCreateMode isMissingInvoiceCandidate(@Nullable final I_C_Flatrate_Term flatrateTerm) { return CandidatesAutoCreateMode.DONT; } /** * Does nothing */ @Override public void setSpecificInvoiceCandidateValues( @NonNull final I_C_Invoice_Candidate ic, @NonNull final I_C_Flatrate_Term term) { // nothing to do } /** * @return always one, in the respective term's UOM */ @Override public Quantity calculateQtyEntered(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord) { final UomId uomId = HandlerTools.retrieveUomId(invoiceCandidateRecord); final I_C_UOM uomRecord = loadOutOfTrx(uomId, I_C_UOM.class); return Quantity.of(ONE, uomRecord);
} /** * @return {@link PriceAndTax#NONE} because the tax remains unchanged and the price is updated in {@link CandidateAssignmentService}. */ @Override public PriceAndTax calculatePriceAndTax(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord) { return PriceAndTax.NONE; // no changes to be made } @Override public Consumer<I_C_Invoice_Candidate> getInvoiceScheduleSetterFunction( @Nullable final Consumer<I_C_Invoice_Candidate> IGNORED_defaultImplementation) { return ic -> { final FlatrateTermId flatrateTermId = FlatrateTermId.ofRepoId(ic.getRecord_ID()); final RefundContractRepository refundContractRepository = SpringContextHolder.instance.getBean(RefundContractRepository.class); final RefundContract refundContract = refundContractRepository.getById(flatrateTermId); final NextInvoiceDate nextInvoiceDate = refundContract.computeNextInvoiceDate(asLocalDate(ic.getDeliveryDate())); ic.setC_InvoiceSchedule_ID(nextInvoiceDate.getInvoiceSchedule().getId().getRepoId()); ic.setDateToInvoice(asTimestamp(nextInvoiceDate.getDateToInvoice())); }; } /** Just return the record's current date */ @Override public Timestamp calculateDateOrdered(@NonNull final I_C_Invoice_Candidate invoiceCandidateRecord) { return invoiceCandidateRecord.getDateOrdered(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.contracts\src\main\java\de\metas\contracts\refund\invoicecandidatehandler\FlatrateTermRefund_Handler.java
1
请完成以下Java代码
public void multiplyMatrices() throws Exception { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2, 3}, {4, 5, 6} }); Matrix m2 = new DenseMatrix(new double[][]{ {1, 4}, {2, 5}, {3, 6} }); Matrix m3 = m1.multiply(m2); log.info("Multiplying matrices: {}", m3); } public void multiplyIncorrectMatrices() throws Exception { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2, 3}, {4, 5, 6} }); Matrix m2 = new DenseMatrix(new double[][]{ {3, 2, 1}, {6, 5, 4} }); Matrix m3 = m1.multiply(m2); log.info("Multiplying matrices: {}", m3); } public void inverseMatrix() { Matrix m1 = new DenseMatrix(new double[][]{ {1, 2},
{3, 4} }); Inverse m2 = new Inverse(m1); log.info("Inverting a matrix: {}", m2); log.info("Verifying a matrix inverse: {}", m1.multiply(m2)); } public Polynomial createPolynomial() { return new Polynomial(new double[]{3, -5, 1}); } public void evaluatePolynomial(Polynomial p) { // Evaluate using a real number log.info("Evaluating a polynomial using a real number: {}", p.evaluate(5)); // Evaluate using a complex number log.info("Evaluating a polynomial using a complex number: {}", p.evaluate(new Complex(1, 2))); } public void solvePolynomial() { Polynomial p = new Polynomial(new double[]{2, 2, -4}); PolyRootSolver solver = new PolyRoot(); List<? extends Number> roots = solver.solve(p); log.info("Finding polynomial roots: {}", roots); } }
repos\tutorials-master\libraries-data-2\src\main\java\com\baeldung\suanshu\SuanShuMath.java
1
请完成以下Java代码
public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Distribution List. @param M_DistributionList_ID Distribution Lists allow to distribute products to a selected list of partners */ public void setM_DistributionList_ID (int M_DistributionList_ID) { if (M_DistributionList_ID < 1) set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, null); else set_ValueNoCheck (COLUMNNAME_M_DistributionList_ID, Integer.valueOf(M_DistributionList_ID)); } /** Get Distribution List. @return Distribution Lists allow to distribute products to a selected list of partners */ public int getM_DistributionList_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_DistributionList_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()); } /** Set Process Now. @param Processing Process Now */ public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Process Now. @return Process Now */ public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Total Ratio. @param RatioTotal Total of relative weight in a distribution */ public void setRatioTotal (BigDecimal RatioTotal) { set_Value (COLUMNNAME_RatioTotal, RatioTotal); } /** Get Total Ratio. @return Total of relative weight in a distribution */ public BigDecimal getRatioTotal () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_RatioTotal); 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_DistributionList.java
1
请完成以下Java代码
protected JsonNode toJson(Object value) { if (value != null) { return JacksonUtil.valueToTree(value); } else { return null; } } protected <T> T fromJson(JsonNode json, Class<T> type) { return JacksonUtil.convertValue(json, type); } protected String listToString(List<?> list) { if (list != null) { return StringUtils.join(list, ',');
} else { return ""; } } protected <E> List<E> listFromString(String string, Function<String, E> mappingFunction) { if (string != null) { return Arrays.stream(StringUtils.split(string, ',')) .filter(StringUtils::isNotBlank) .map(mappingFunction).collect(Collectors.toList()); } else { return Collections.emptyList(); } } }
repos\thingsboard-master\dao\src\main\java\org\thingsboard\server\dao\model\BaseSqlEntity.java
1
请完成以下Java代码
public class InstantMessage { private String to; private String from; private String message; private Calendar created = Calendar.getInstance(); public String getTo() { return this.to; } public void setTo(String to) { this.to = to; } public String getFrom() { return this.from; }
public void setFrom(String from) { this.from = from; } public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } public Calendar getCreated() { return this.created; } public void setCreated(Calendar created) { this.created = created; } }
repos\spring-session-main\spring-session-samples\spring-session-sample-boot-websocket\src\main\java\sample\data\InstantMessage.java
1
请在Spring Boot框架中完成以下Java代码
public class SessionProperties { /** * Session timeout. If a duration suffix is not specified, seconds will be used. */ @DurationUnit(ChronoUnit.SECONDS) private @Nullable Duration timeout; private Servlet servlet = new Servlet(); public @Nullable Duration getTimeout() { return this.timeout; } public void setTimeout(@Nullable Duration timeout) { this.timeout = timeout; } public Servlet getServlet() { return this.servlet; } public void setServlet(Servlet servlet) { this.servlet = servlet; } /** * Determine the session timeout. If no timeout is configured, the * {@code fallbackTimeout} is used. * @param fallbackTimeout a fallback timeout value if the timeout isn't configured * @return the session timeout * @deprecated since 4.0.1 for removal in 4.2.0 in favor of {@link SessionTimeout} */ @Deprecated(since = "4.0.1", forRemoval = true) public Duration determineTimeout(Supplier<Duration> fallbackTimeout) { return (this.timeout != null) ? this.timeout : fallbackTimeout.get();
} /** * Servlet-related properties. */ public static class Servlet { /** * Session repository filter order. */ private int filterOrder = SessionRepositoryFilter.DEFAULT_ORDER; /** * Session repository filter dispatcher types. */ private Set<DispatcherType> filterDispatcherTypes = new HashSet<>( Arrays.asList(DispatcherType.ASYNC, DispatcherType.ERROR, DispatcherType.REQUEST)); public int getFilterOrder() { return this.filterOrder; } public void setFilterOrder(int filterOrder) { this.filterOrder = filterOrder; } public Set<DispatcherType> getFilterDispatcherTypes() { return this.filterDispatcherTypes; } public void setFilterDispatcherTypes(Set<DispatcherType> filterDispatcherTypes) { this.filterDispatcherTypes = filterDispatcherTypes; } } }
repos\spring-boot-4.0.1\module\spring-boot-session\src\main\java\org\springframework\boot\session\autoconfigure\SessionProperties.java
2
请完成以下Java代码
static FileLock getReadLockFromInputStream(long from, long size) throws IOException { Path path = Files.createTempFile("foo", "txt"); try (FileInputStream fis = new FileInputStream(path.toFile()); FileLock lock = fis.getChannel() .lock(from, size, true)) { if (lock.isValid()) { LOG.debug("This is a valid shared lock"); return lock; } return null; } } /** * Gets an exclusive lock from a RandomAccessFile. Works because the file is readable. * @param from beginning of the locked region * @param size how many bytes to lock * @return A lock object representing the newly-acquired lock * @throws IOException if there is a problem creating the temporary file
*/ static FileLock getReadLockFromRandomAccessFile(long from, long size) throws IOException { Path path = Files.createTempFile("foo", "txt"); try (RandomAccessFile file = new RandomAccessFile(path.toFile(), "r"); // could also be "rw", but "r" is sufficient for reading FileLock lock = file.getChannel() .lock(from, size, true)) { if (lock.isValid()) { LOG.debug("This is a valid shared lock"); return lock; } } catch (Exception e) { LOG.error(e.getMessage()); } return null; } }
repos\tutorials-master\core-java-modules\core-java-nio\src\main\java\com\baeldung\lock\FileLocks.java
1
请完成以下Java代码
public void setContextAttributesMapper( Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> contextAttributesMapper) { Assert.notNull(contextAttributesMapper, "contextAttributesMapper cannot be null"); this.contextAttributesMapper = contextAttributesMapper; } /** * Sets the handler that handles successful authorizations. * * The default saves {@link OAuth2AuthorizedClient}s in the * {@link ReactiveOAuth2AuthorizedClientService}. * @param authorizationSuccessHandler the handler that handles successful * authorizations. * @since 5.3 */ public void setAuthorizationSuccessHandler(ReactiveOAuth2AuthorizationSuccessHandler authorizationSuccessHandler) { Assert.notNull(authorizationSuccessHandler, "authorizationSuccessHandler cannot be null"); this.authorizationSuccessHandler = authorizationSuccessHandler; } /** * Sets the handler that handles authorization failures. * * <p> * A {@link RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler} is used * by default.
* </p> * @param authorizationFailureHandler the handler that handles authorization failures. * @since 5.3 * @see RemoveAuthorizedClientReactiveOAuth2AuthorizationFailureHandler */ public void setAuthorizationFailureHandler(ReactiveOAuth2AuthorizationFailureHandler authorizationFailureHandler) { Assert.notNull(authorizationFailureHandler, "authorizationFailureHandler cannot be null"); this.authorizationFailureHandler = authorizationFailureHandler; } /** * The default implementation of the {@link #setContextAttributesMapper(Function) * contextAttributesMapper}. */ public static class DefaultContextAttributesMapper implements Function<OAuth2AuthorizeRequest, Mono<Map<String, Object>>> { private final AuthorizedClientServiceOAuth2AuthorizedClientManager.DefaultContextAttributesMapper mapper = new AuthorizedClientServiceOAuth2AuthorizedClientManager.DefaultContextAttributesMapper(); @Override public Mono<Map<String, Object>> apply(OAuth2AuthorizeRequest authorizeRequest) { return Mono.fromCallable(() -> this.mapper.apply(authorizeRequest)); } } }
repos\spring-security-main\oauth2\oauth2-client\src\main\java\org\springframework\security\oauth2\client\AuthorizedClientServiceReactiveOAuth2AuthorizedClientManager.java
1