instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public void setM_Warehouse_ID (final int M_Warehouse_ID) { if (M_Warehouse_ID < 1) set_Value (COLUMNNAME_M_Warehouse_ID, null); else set_Value (COLUMNNAME_M_Warehouse_ID, M_Warehouse_ID); } @Override public int getM_Warehouse_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_ID); } @Override public void setName (final java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } @Override public java.lang.String getName() { return get_ValueAsString(COLUMNNAME_Name); } @Override public void setProcessed (final boolean Processed) {
set_ValueNoCheck (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Forecast.java
1
请完成以下Java代码
Optional<ProductAndHUPIItemProductId> lookupProductByGTIN( @NonNull final ExternalIdentifier productIdentifier) { final String gtin = productIdentifier.asGTIN(); final ICompositeQueryFilter<I_M_HU_PI_Item_Product> hupiFilter = queryBL.createCompositeQueryFilter(I_M_HU_PI_Item_Product.class) .setJoinOr() .addEqualsFilter(I_M_HU_PI_Item_Product.COLUMNNAME_GTIN, gtin) .addEqualsFilter(I_M_HU_PI_Item_Product.COLUMNNAME_EAN_TU, gtin) .addEqualsFilter(I_M_HU_PI_Item_Product.COLUMNNAME_UPC, gtin); final I_M_HU_PI_Item_Product hupi = queryBL.createQueryBuilder(I_M_HU_PI_Item_Product.class) .addOnlyActiveRecordsFilter() .filter(hupiFilter) .addNotNull(I_M_HU_PI_Item_Product.COLUMNNAME_M_Product_ID) .orderBy(I_M_HU_PI_Item_Product.COLUMNNAME_M_HU_PI_Item_Product_ID) .create().first(); if (hupi != null) { return ProductAndHUPIItemProductId.opt( ProductId.ofRepoId(hupi.getM_Product_ID()), HUPIItemProductId.ofRepoId(hupi.getM_HU_PI_Item_Product_ID())); } // TODO refactor this logic and use some BPartnerProductDAO methods final ICompositeQueryFilter<I_C_BPartner_Product> bppFilter = queryBL.createCompositeQueryFilter(I_C_BPartner_Product.class) .setJoinOr() .addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_GTIN, gtin) .addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_EAN_CU, gtin) .addEqualsFilter(I_C_BPartner_Product.COLUMNNAME_UPC, gtin); final I_C_BPartner_Product bpp = queryBL.createQueryBuilder(I_C_BPartner_Product.class) .addOnlyActiveRecordsFilter() .filter(bppFilter) .addNotNull(I_C_BPartner_Product.COLUMNNAME_M_Product_ID) .orderBy(I_C_BPartner_Product.COLUMNNAME_C_BPartner_Product_ID)
.create().first(); if (bpp != null) { return ProductAndHUPIItemProductId.opt(ProductId.ofRepoId(bpp.getM_Product_ID())); } final ICompositeQueryFilter<I_M_Product> pFilter = queryBL.createCompositeQueryFilter(I_M_Product.class) .setJoinOr() .addEqualsFilter(I_M_Product.COLUMNNAME_GTIN, gtin) .addEqualsFilter(I_M_Product.COLUMNNAME_EAN13_ProductCode, gtin) .addEqualsFilter(I_M_Product.COLUMNNAME_UPC, gtin); final I_M_Product p = queryBL.createQueryBuilder(I_M_Product.class) .addOnlyActiveRecordsFilter() .filter(pFilter) .orderBy(I_M_Product.COLUMNNAME_M_Product_ID) .create().first(); if (p != null) { return ProductAndHUPIItemProductId.opt(ProductId.ofRepoId(p.getM_Product_ID())); } return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\v2\product\ExternalIdentifierProductLookupService.java
1
请完成以下Spring Boot application配置
# Port serves the monitoring traffic. server.port=8080 # Expose the prometheus metrics via the monitoring port. # By default, expose on `/actuator/prometheus`. management.endpoints.web.exposure.include=prometheus,configprops,env,info management.endpoint.env.show-values=ALWAYS management.endpoint.configprops.show-values=ALWAYS # The backend service address, for local testing. grpc.client.backend.address=static://loc
alhost:9091 # Teh backend service address, for kubernetes. # grpc.client.backend.address=dns:///backend.default.svc.cluster.local:9091 grpc.client.backend.negotiationType=PLAINTEXT
repos\grpc-spring-master\examples\grpc-observability\frontend\src\main\resources\application.properties
2
请完成以下Java代码
public JsonExternalId of(@NonNull final ExternalId externalId) { return JsonExternalId.of(externalId.getValue()); } public JsonExternalId ofOrNull(@Nullable final ExternalId externalId) { if (externalId == null) { return null; } return JsonExternalId.of(externalId.getValue()); } public boolean equals(@Nullable final JsonExternalId id1, @Nullable final JsonExternalId id2) { return Objects.equals(id1, id2); }
public static boolean isEqualTo( @Nullable final JsonExternalId jsonExternalId, @Nullable final ExternalId externalId) { if (jsonExternalId == null && externalId == null) { return true; } if (jsonExternalId == null ^ externalId == null) { return false; // one is null, the other one isn't } return Objects.equals(jsonExternalId.getValue(), externalId.getValue()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.util.web\src\main\java\de\metas\rest_api\utils\JsonExternalIds.java
1
请完成以下Java代码
public static MessageBuilder withBody(byte[] body) { Assert.notNull(body, BODY_CANNOT_BE_NULL); return new MessageBuilder(body); } /** * The final message body will be a copy of 'body' in a new array. * @param body The body. * @return The builder. */ public static MessageBuilder withClonedBody(byte[] body) { Assert.notNull(body, BODY_CANNOT_BE_NULL); return new MessageBuilder(Arrays.copyOf(body, body.length)); } /** * The final message body will be a new array containing the byte range from * 'body'. * @param body The body. * @param from The starting index. * @param to The ending index. * @return The builder. * * @see Arrays#copyOfRange(byte[], int, int) */ public static MessageBuilder withBody(byte[] body, int from, int to) { Assert.notNull(body, BODY_CANNOT_BE_NULL); return new MessageBuilder(Arrays.copyOfRange(body, from, to)); } /** * The final message body will be a direct reference to the message * body, the MessageProperties will be a shallow copy. * @param message The message. * @return The builder. */ public static MessageBuilder fromMessage(Message message) { Assert.notNull(message, MESSAGE_CANNOT_BE_NULL); return new MessageBuilder(message); } /** * The final message will have a copy of the message * body, the MessageProperties will be cloned (top level only). * @param message The message. * @return The builder. */ public static MessageBuilder fromClonedMessage(Message message) {
Assert.notNull(message, MESSAGE_CANNOT_BE_NULL); byte[] body = message.getBody(); Assert.notNull(body, BODY_CANNOT_BE_NULL); return new MessageBuilder(Arrays.copyOf(body, body.length), message.getMessageProperties()); } private MessageBuilder(byte[] body) { //NOSONAR this.body = body; } private MessageBuilder(Message message) { this(message.getBody(), message.getMessageProperties()); } private MessageBuilder(byte[] body, MessageProperties properties) { //NOSONAR this.body = body; this.copyProperties(properties); } /** * Makes this builder's properties builder use a reference to properties. * @param properties The properties. * @return this. */ public MessageBuilder andProperties(MessageProperties properties) { this.setProperties(properties); return this; } @Override public Message build() { return new Message(this.body, this.buildProperties()); } }
repos\spring-amqp-main\spring-amqp\src\main\java\org\springframework\amqp\core\MessageBuilder.java
1
请完成以下Java代码
public final class OAuth2TokenValidatorResult { static final OAuth2TokenValidatorResult NO_ERRORS = new OAuth2TokenValidatorResult(Collections.emptyList()); private final Collection<OAuth2Error> errors; private OAuth2TokenValidatorResult(Collection<OAuth2Error> errors) { Assert.notNull(errors, "errors cannot be null"); this.errors = new ArrayList<>(errors); } /** * Say whether this result indicates success * @return whether this result has errors */ public boolean hasErrors() { return !this.errors.isEmpty(); } /** * Return error details regarding the validation attempt * @return the collection of results in this result, if any; returns an empty list * otherwise */ public Collection<OAuth2Error> getErrors() { return this.errors; } /**
* Construct a successful {@link OAuth2TokenValidatorResult} * @return an {@link OAuth2TokenValidatorResult} with no errors */ public static OAuth2TokenValidatorResult success() { return NO_ERRORS; } /** * Construct a failure {@link OAuth2TokenValidatorResult} with the provided detail * @param errors the list of errors * @return an {@link OAuth2TokenValidatorResult} with the errors specified */ public static OAuth2TokenValidatorResult failure(OAuth2Error... errors) { return failure(Arrays.asList(errors)); } /** * Construct a failure {@link OAuth2TokenValidatorResult} with the provided detail * @param errors the list of errors * @return an {@link OAuth2TokenValidatorResult} with the errors specified */ public static OAuth2TokenValidatorResult failure(Collection<OAuth2Error> errors) { return (errors.isEmpty()) ? NO_ERRORS : new OAuth2TokenValidatorResult(errors); } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\OAuth2TokenValidatorResult.java
1
请完成以下Java代码
public ResourceEntity getResource() { return resource; } public void setResource(ResourceEntity resource) { this.resource = resource; } public DefaultCmmnElementHandlerRegistry getHandlerRegistry() { return handlerRegistry; } public void setHandlerRegistry(DefaultCmmnElementHandlerRegistry handlerRegistry) { this.handlerRegistry = handlerRegistry; } @SuppressWarnings("unchecked") protected <V extends CmmnElement> CmmnElementHandler<V, CmmnActivity> getDefinitionHandler(Class<V> cls) { return (CmmnElementHandler<V, CmmnActivity>) getHandlerRegistry().getDefinitionElementHandlers().get(cls); } protected ItemHandler getPlanItemHandler(Class<? extends PlanItemDefinition> cls) { return getHandlerRegistry().getPlanItemElementHandlers().get(cls); } protected ItemHandler getDiscretionaryItemHandler(Class<? extends PlanItemDefinition> cls) { return getHandlerRegistry().getDiscretionaryElementHandlers().get(cls);
} protected SentryHandler getSentryHandler() { return getHandlerRegistry().getSentryHandler(); } public ExpressionManager getExpressionManager() { return expressionManager; } public void setExpressionManager(ExpressionManager expressionManager) { this.expressionManager = expressionManager; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\transformer\CmmnTransform.java
1
请完成以下Java代码
public class ValueFieldsImpl implements ValueFields { protected String text; protected String text2; protected Long longValue; protected Double doubleValue; protected byte[] byteArrayValue; public String getName() { return null; } public String getTextValue() { return text; } public void setTextValue(String textValue) { this.text = textValue; } public String getTextValue2() { return text2; } public void setTextValue2(String textValue2) { this.text2 = textValue2;
} public Long getLongValue() { return longValue; } public void setLongValue(Long longValue) { this.longValue = longValue; } public Double getDoubleValue() { return doubleValue; } public void setDoubleValue(Double doubleValue) { this.doubleValue = doubleValue; } public byte[] getByteArrayValue() { return byteArrayValue; } public void setByteArrayValue(byte[] bytes) { this.byteArrayValue = bytes; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\variable\serializer\ValueFieldsImpl.java
1
请完成以下Java代码
private static final String toMessageId(final Object messageIdObj) { if (messageIdObj == null) { return null; } return messageIdObj.toString(); } private static ZonedDateTime toZonedDateTime(final Object dateObj) { return TimeUtil.asZonedDateTime(dateObj); } private static final ImmutableMap<String, Object> convertMailHeadersToJson(final MultiValueMap<String, Object> mailRawHeaders) { return mailRawHeaders.entrySet() .stream() .map(entry -> GuavaCollectors.entry(entry.getKey(), convertListToJson(entry.getValue()))) .filter(entry -> entry.getValue() != null) .collect(GuavaCollectors.toImmutableMap()); } private static final Object convertListToJson(final List<Object> values) { if (values == null || values.isEmpty()) { return ImmutableList.of();
} else if (values.size() == 1) { return convertValueToJson(values.get(0)); } else { return values.stream() .map(v -> convertValueToJson(v)) .filter(Objects::nonNull) .collect(ImmutableList.toImmutableList()); } } private static final Object convertValueToJson(final Object value) { if (value == null) { return null; } return value.toString(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.inbound.mail\src\main\java\de\metas\inbound\mail\InboundEMailMessageHandler.java
1
请完成以下Java代码
public Long getId() { return id; } public void setId(Long id) { this.id = id; } public String getState() { return state; } public void setState(String state) { this.state = state; } public String getCity() { return city; }
public void setCity(String city) { this.city = city; } public String getStreet() { return street; } public void setStreet(String street) { this.street = street; } public String getZipCode() { return zipCode; } public void setZipCode(String zipCode) { this.zipCode = zipCode; } }
repos\tutorials-master\persistence-modules\spring-data-jpa-simple\src\main\java\com\baeldung\jpa\projection\model\Address.java
1
请完成以下Java代码
public void setIsPrimary (boolean IsPrimary) { set_Value (COLUMNNAME_IsPrimary, Boolean.valueOf(IsPrimary)); } /** Get Primary. @return Indicates if this is the primary budget */ public boolean isPrimary () { Object oo = get_Value(COLUMNNAME_IsPrimary); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; }
/** Set Sequence. @param SeqNo Method of ordering records; lowest number comes first */ public void setSeqNo (int SeqNo) { set_Value (COLUMNNAME_SeqNo, Integer.valueOf(SeqNo)); } /** Get Sequence. @return Method of ordering records; lowest number comes first */ public int getSeqNo () { Integer ii = (Integer)get_Value(COLUMNNAME_SeqNo); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_WorkbenchWindow.java
1
请完成以下Java代码
public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } @Override public void setProductValue (final java.lang.String ProductValue) { set_Value (COLUMNNAME_ProductValue, ProductValue); } @Override public java.lang.String getProductValue() { return get_ValueAsString(COLUMNNAME_ProductValue); } @Override public void setProjectValue (final @Nullable java.lang.String ProjectValue) { set_Value (COLUMNNAME_ProjectValue, ProjectValue); } @Override public java.lang.String getProjectValue() { return get_ValueAsString(COLUMNNAME_ProjectValue); } @Override public void setQty (final @Nullable BigDecimal Qty) { set_Value (COLUMNNAME_Qty, Qty); } @Override public BigDecimal getQty() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_Qty); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setQtyCalculated (final @Nullable BigDecimal QtyCalculated) {
set_Value (COLUMNNAME_QtyCalculated, QtyCalculated); } @Override public BigDecimal getQtyCalculated() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_QtyCalculated); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setUOM (final java.lang.String UOM) { set_Value (COLUMNNAME_UOM, UOM); } @Override public java.lang.String getUOM() { return get_ValueAsString(COLUMNNAME_UOM); } @Override public void setWarehouseValue (final java.lang.String WarehouseValue) { set_Value (COLUMNNAME_WarehouseValue, WarehouseValue); } @Override public java.lang.String getWarehouseValue() { return get_ValueAsString(COLUMNNAME_WarehouseValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_I_Forecast.java
1
请完成以下Java代码
public void beforeSave(final I_C_AcctSchema acctSchema) { acctSchema.setAD_Org_ID(OrgId.ANY.getRepoId()); if (acctSchema.getTaxCorrectionType() == null) { final TaxCorrectionType taxCorrectionType = acctSchema.isDiscountCorrectsTax() ? TaxCorrectionType.WRITEOFF_AND_DISCOUNT : TaxCorrectionType.NONE; acctSchema.setTaxCorrectionType(taxCorrectionType.getCode()); } if (acctSchema.getGAAP() == null) { acctSchema.setGAAP(X_C_AcctSchema.GAAP_InternationalGAAP); } // NOTE: allow having only org restriction for primary accounting schema too. // if (acctSchema.getAD_OrgOnly_ID() > 0 && isPrimaryAcctSchema(acctSchema)) // { // acctSchema.setAD_OrgOnly_ID(OrgId.ANY.getRepoId()); // } // checkCosting(acctSchema); } /** * Check Costing Setup. * Make sure that there is a Cost Type and Cost Element */ private void checkCosting(final I_C_AcctSchema acctSchema) { // Create Cost Type if (acctSchema.getM_CostType_ID() <= 0) { final I_M_CostType costType = InterfaceWrapperHelper.newInstance(I_M_CostType.class); costType.setAD_Org_ID(Env.CTXVALUE_AD_Org_ID_Any); costType.setName(acctSchema.getName()); InterfaceWrapperHelper.save(costType); acctSchema.setM_CostType_ID(costType.getM_CostType_ID()); } // Create Cost Elements final ClientId clientId = ClientId.ofRepoId(acctSchema.getAD_Client_ID()); costElementRepo.getOrCreateMaterialCostElement(clientId, CostingMethod.ofNullableCode(acctSchema.getCostingMethod())); // Default Costing Level if (acctSchema.getCostingLevel() == null) { acctSchema.setCostingLevel(CostingLevel.Client.getCode()); } if (acctSchema.getCostingMethod() == null)
{ acctSchema.setCostingMethod(CostingMethod.StandardCosting.getCode()); } } @ModelChange(timings = { ModelValidator.TYPE_BEFORE_CHANGE }, ifColumnsChanged = I_C_AcctSchema.COLUMNNAME_C_Currency_ID) public void checkCurrency(final I_C_AcctSchema acctSchema) { if(DISABLE_CHECK_CURRENCY.getValue(acctSchema, Boolean.FALSE)) { logger.debug("Skip currency check for {} because of dynamic attribute {}", acctSchema, DISABLE_CHECK_CURRENCY); return; } final PO po = InterfaceWrapperHelper.getPO(acctSchema); final CurrencyId previousCurrencyId = CurrencyId.ofRepoIdOrNull(po.get_ValueOldAsInt(I_C_AcctSchema.COLUMNNAME_C_Currency_ID)); if (previousCurrencyId != null && currentCostsRepository.hasCostsInCurrency(AcctSchemaId.ofRepoId(acctSchema.getC_AcctSchema_ID()), previousCurrencyId)) { throw new AdempiereException(MSG_ACCT_SCHEMA_HAS_ASSOCIATED_COSTS); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\interceptor\C_AcctSchema.java
1
请在Spring Boot框架中完成以下Java代码
public String resetOperatorPwdUI(HttpServletRequest req, Long id, Model model) { PmsOperator operator = pmsOperatorService.getDataById(id); if (operator == null) { return operateError("无法获取要重置的信息", model); } // 普通操作员没有修改超级管理员的权限 if ("USER".equals(this.getPmsOperator().getType()) && "ADMIN".equals(operator.getType())) { return operateError("权限不足", model); } model.addAttribute("operator", operator); return "pms/pmsOperatorResetPwd"; } /** * 重置操作员密码. * * @return */ @RequiresPermissions("pms:operator:resetpwd") @RequestMapping("/resetPwd") public String resetOperatorPwd(HttpServletRequest req, Long id, String newPwd, String newPwd2, Model model, DwzAjax dwz) { try { PmsOperator operator = pmsOperatorService.getDataById(id); if (operator == null) { return operateError("无法获取要重置密码的操作员信息", model); } // 普通操作员没有修改超级管理员的权限 if ("USER".equals(this.getPmsOperator().getType()) && "ADMIN".equals(operator.getType())) { return operateError("权限不足", model); } String validateMsg = validatePassword(newPwd, newPwd2); if (StringUtils.isNotBlank(validateMsg)) { return operateError(validateMsg, model); // 返回错误信息 } operator.setLoginPwd(newPwd); PasswordHelper.encryptPassword(operator); pmsOperatorService.updateData(operator); return operateSuccess(model, dwz); } catch (Exception e) { log.error("== resetOperatorPwd exception:", e); return operateError("密码重置出错:" + e.getMessage(), model); } } /** * 得到角色和操作员关联的ID字符串 * * @return */
private String getRoleOperatorStr(String selectVal) throws Exception { String roleStr = selectVal; if (StringUtils.isNotBlank(roleStr) && roleStr.length() > 0) { roleStr = roleStr.substring(0, roleStr.length() - 1); } return roleStr; } /*** * 验证重置密码 * * @param newPwd * @param newPwd2 * @return */ private String validatePassword(String newPwd, String newPwd2) { String msg = ""; // 用于存放校验提示信息的变量 if (StringUtils.isBlank(newPwd)) { msg += "新密码不能为空,"; } else if (newPwd.length() < 6) { msg += "新密码不能少于6位长度,"; } if (!newPwd.equals(newPwd2)) { msg += "两次输入的密码不一致"; } return msg; } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\controller\PmsOperatorController.java
2
请在Spring Boot框架中完成以下Java代码
public Duration getKeepAlive() { return this.keepAlive; } public void setKeepAlive(Duration keepAlive) { this.keepAlive = keepAlive; } public Shutdown getShutdown() { return this.shutdown; } public static class Shutdown { /** * Whether to accept further tasks after the application context close phase * has begun. */ private boolean acceptTasksAfterContextClose; public boolean isAcceptTasksAfterContextClose() { return this.acceptTasksAfterContextClose; } public void setAcceptTasksAfterContextClose(boolean acceptTasksAfterContextClose) { this.acceptTasksAfterContextClose = acceptTasksAfterContextClose; } } } public static class Shutdown { /** * Whether the executor should wait for scheduled tasks to complete on shutdown. */ private boolean awaitTermination; /** * Maximum time the executor should wait for remaining tasks to complete. */ private @Nullable Duration awaitTerminationPeriod; public boolean isAwaitTermination() { return this.awaitTermination; }
public void setAwaitTermination(boolean awaitTermination) { this.awaitTermination = awaitTermination; } public @Nullable Duration getAwaitTerminationPeriod() { return this.awaitTerminationPeriod; } public void setAwaitTerminationPeriod(@Nullable Duration awaitTerminationPeriod) { this.awaitTerminationPeriod = awaitTerminationPeriod; } } /** * Determine when the task executor is to be created. * * @since 3.5.0 */ public enum Mode { /** * Create the task executor if no user-defined executor is present. */ AUTO, /** * Create the task executor even if a user-defined executor is present. */ FORCE } }
repos\spring-boot-4.0.1\core\spring-boot-autoconfigure\src\main\java\org\springframework\boot\autoconfigure\task\TaskExecutionProperties.java
2
请在Spring Boot框架中完成以下Java代码
public Duration getConfigRefreshFrequency() { return this.configRefreshFrequency; } public void setConfigRefreshFrequency(Duration configRefreshFrequency) { this.configRefreshFrequency = configRefreshFrequency; } public Duration getConfigTimeToLive() { return this.configTimeToLive; } public void setConfigTimeToLive(Duration configTimeToLive) { this.configTimeToLive = configTimeToLive; } public String getConfigUri() { return this.configUri;
} public void setConfigUri(String configUri) { this.configUri = configUri; } public String getEvalUri() { return this.evalUri; } public void setEvalUri(String evalUri) { this.evalUri = evalUri; } }
repos\spring-boot-4.0.1\module\spring-boot-micrometer-metrics\src\main\java\org\springframework\boot\micrometer\metrics\autoconfigure\export\atlas\AtlasProperties.java
2
请完成以下Java代码
public boolean deleteById(final int notificationId) { final I_AD_Note notificationPO = retrieveAD_Note(notificationId); if (notificationPO == null) { return false; } deleteNotification(notificationPO); return true; } @Override public void deleteByUserAndTableRecordRef(final @NonNull UserId adUserId, final @NonNull TableRecordReference tableRecordReference) { retrieveNotesByUserId(adUserId) .addEqualsFilter(I_AD_Note.COLUMNNAME_AD_Table_ID, tableRecordReference.getAdTableId()) .addEqualsFilter(I_AD_Note.COLUMNNAME_Record_ID, tableRecordReference.getRecord_ID()) .create() .delete(false); } @Override public void deleteAllByUserId(final UserId adUserId) { retrieveNotesByUserId(adUserId) .create() .list() .forEach(this::deleteNotification); } private void deleteNotification(final I_AD_Note notificationPO)
{ notificationPO.setProcessed(false); InterfaceWrapperHelper.delete(notificationPO); } @Override public int getUnreadCountByUserId(final UserId adUserId) { return retrieveNotesByUserId(adUserId) .addEqualsFilter(I_AD_Note.COLUMN_Processed, false) .create() .count(); } @Override public int getTotalCountByUserId(final UserId adUserId) { return retrieveNotesByUserId(adUserId) .create() .count(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\notification\impl\NotificationRepository.java
1
请完成以下Java代码
public IAttributeSplitterStrategy retrieveSplitterStrategy() { return NullSplitterStrategy.instance; } /** * @return {@link CopyHUAttributeTransferStrategy#instance}. */ @Override public IHUAttributeTransferStrategy retrieveTransferStrategy() { return CopyHUAttributeTransferStrategy.instance; } /** * @return {@code true}. */ @Override public boolean isReadonlyUI() { return true; } /** * @return {@code true}. */ @Override public boolean isDisplayedUI() { return true; } @Override public boolean isMandatory() { return false; } @Override public boolean isOnlyIfInProductAttributeSet() { return false;
} /** * @return our attribute instance's {@code M_Attribute_ID}. */ @Override public int getDisplaySeqNo() { return attributeInstance.getM_Attribute_ID(); } /** * @return {@code true} */ @Override public boolean isUseInASI() { return true; } /** * @return {@code false}, since no HU-PI attribute is involved. */ @Override public boolean isDefinedByTemplate() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\storage\AIAttributeValue.java
1
请完成以下Java代码
public class FindFileJava7Utils { private FindFileJava7Utils() { } public static List<Path> find(Path startPath, String extension) throws IOException { if (!Files.isDirectory(startPath)) { throw new IllegalArgumentException("Provided path is not a directory: " + startPath); } final List<Path> matches = new ArrayList<>(); MatchExtensionPredicate filter = new MatchExtensionPredicate(extension); Files.walkFileTree(startPath, new SimpleFileVisitor<Path>() { @Override public FileVisitResult visitFile(Path file, BasicFileAttributes attributes) {
if (filter.test(file)) { matches.add(file); } return FileVisitResult.CONTINUE; } @Override public FileVisitResult visitFileFailed(Path file, IOException exc) { return FileVisitResult.CONTINUE; } }); return matches; } }
repos\tutorials-master\libraries-files\src\main\java\com\baeldung\findfiles\FindFileJava7Utils.java
1
请完成以下Java代码
public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final AuthorId other = (AuthorId) obj;
if (!Objects.equals(this.name, other.name)) { return false; } if (!Objects.equals(this.publisher, other.publisher)) { return false; } return true; } @Override public String toString() { return "AuthorId{ " + "publisher=" + publisher + ", name=" + name + '}'; } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootCompositeKeyEmbeddableMapRel\src\main\java\com\bookstore\entity\AuthorId.java
1
请完成以下Java代码
public void setTaskId(String taskId) { this.taskId = taskId; } @Override public T getValue() { return value; } @Override public String toString() { return ( "VariableInstanceImpl{" + "name='" + name + '\'' +
", type='" + type + '\'' + ", processInstanceId='" + processInstanceId + '\'' + ", taskId='" + taskId + '\'' + ", value='" + value + '\'' + '}' ); } }
repos\Activiti-develop\activiti-core\activiti-api-impl\activiti-api-model-shared-impl\src\main\java\org\activiti\api\runtime\model\impl\VariableInstanceImpl.java
1
请完成以下Java代码
protected void initializeBinding(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context, BaseCallableElement callableElement) { String binding = getBinding(element, activity, context); if (CallableElementBinding.DEPLOYMENT.getValue().equals(binding)) { callableElement.setBinding(CallableElementBinding.DEPLOYMENT); } else if (CallableElementBinding.LATEST.getValue().equals(binding)) { callableElement.setBinding(CallableElementBinding.LATEST); } else if (CallableElementBinding.VERSION.getValue().equals(binding)) { callableElement.setBinding(CallableElementBinding.VERSION); } } protected void initializeVersion(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context, BaseCallableElement callableElement) { ExpressionManager expressionManager = context.getExpressionManager(); String version = getVersion(element, activity, context); ParameterValueProvider versionProvider = createParameterValueProvider(version, expressionManager); callableElement.setVersionValueProvider(versionProvider); } protected void initializeTenantId(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context, BaseCallableElement callableElement) { ParameterValueProvider tenantIdProvider = null; ExpressionManager expressionManager = context.getExpressionManager(); String tenantId = getTenantId(element, activity, context); if (tenantId != null && tenantId.length() > 0) { tenantIdProvider = createParameterValueProvider(tenantId, expressionManager); } callableElement.setTenantIdProvider(tenantIdProvider); } protected ParameterValueProvider createParameterValueProvider(String value, ExpressionManager expressionManager) { if (value == null) { return new NullValueProvider(); } else if (isCompositeExpression(value, expressionManager)) { Expression expression = expressionManager.createExpression(value); return new ElValueProvider(expression);
} else { return new ConstantValueProvider(value); } } protected abstract BaseCallableElement createCallableElement(); protected abstract String getDefinitionKey(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context); protected abstract String getBinding(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context); protected abstract String getVersion(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context); protected abstract String getTenantId(CmmnElement element, CmmnActivity activity, CmmnHandlerContext context); }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmmn\handler\CallingTaskItemHandler.java
1
请完成以下Java代码
private TableColumnExt getTableColumnExt() { return columnExtRef.getValue(); } @Override public void propertyChange(final PropertyChangeEvent evt) { // Avoid recursion if (running) { return; } running = true; try { final TableColumnInfo columnMetaInfo = (TableColumnInfo)evt.getSource();
final TableColumnExt columnExt = getTableColumnExt(); if (columnExt == null) { // ColumnExt reference expired: // * remove this listener because there is no point to have this listener invoked in future // * exit quickly because there is nothing to do columnMetaInfo.removePropertyChangeListener(this); return; } updateColumnExtFromMetaInfo(columnExt, columnMetaInfo); } finally { running = false; } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\swing\table\AnnotatedTableColumnFactory.java
1
请完成以下Java代码
protected DatatypeFactory initialValue() { try { return DatatypeFactory.newInstance(); } catch (final DatatypeConfigurationException e) { throw new IllegalStateException("failed to create " + DatatypeFactory.class.getSimpleName(), e); } } }; public static XMLGregorianCalendar toXMLGregorianCalendar(final LocalDateTime date) { if (date == null) { return null; } final GregorianCalendar c = new GregorianCalendar(); c.setTimeInMillis(date.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()); return datatypeFactoryHolder.get().newXMLGregorianCalendar(c); } public static XMLGregorianCalendar toXMLGregorianCalendar(final ZonedDateTime date) { if (date == null) { return null; } final GregorianCalendar c = new GregorianCalendar(); c.setTimeInMillis(date.toInstant().toEpochMilli()); return datatypeFactoryHolder.get().newXMLGregorianCalendar(c); } public static LocalDateTime toLocalDateTime(final XMLGregorianCalendar xml) { if (xml == null) { return null; } return xml.toGregorianCalendar().toZonedDateTime().toLocalDateTime(); }
public static ZonedDateTime toZonedDateTime(final XMLGregorianCalendar xml) { if (xml == null) { return null; } return xml.toGregorianCalendar().toZonedDateTime(); } public static java.util.Date toDate(final XMLGregorianCalendar xml) { return xml == null ? null : xml.toGregorianCalendar().getTime(); } public static Timestamp toTimestamp(final XMLGregorianCalendar xmlGregorianCalendar) { final Date date = toDate(xmlGregorianCalendar); if (date == null) { return null; } return new Timestamp(date.getTime()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\util\JAXBDateUtils.java
1
请完成以下Java代码
public class SimpleProcessingHandler extends ChannelInboundHandlerAdapter { private ByteBuf tmp; @Override public void handlerAdded(ChannelHandlerContext ctx) { System.out.println("Handler added"); tmp = ctx.alloc().buffer(4); } @Override public void handlerRemoved(ChannelHandlerContext ctx) { System.out.println("Handler removed"); tmp.release(); tmp = null; }
@Override public void channelRead(ChannelHandlerContext ctx, Object msg) { ByteBuf m = (ByteBuf) msg; tmp.writeBytes(m); m.release(); if (tmp.readableBytes() >= 4) { RequestData requestData = new RequestData(); requestData.setIntValue(tmp.readInt()); ResponseData responseData = new ResponseData(); responseData.setIntValue(requestData.getIntValue() * 2); ChannelFuture future = ctx.writeAndFlush(responseData); future.addListener(ChannelFutureListener.CLOSE); } } }
repos\tutorials-master\libraries-server\src\main\java\com\baeldung\netty\SimpleProcessingHandler.java
1
请完成以下Java代码
public ITableRecordReference nextFromQueue() { final WorkQueue result = nextFromQueue0(); if (result.getDLM_Partition_Workqueue_ID() > 0) { queueItemsToDelete.add(result); } return result.getTableRecordReference(); } private WorkQueue nextFromQueue0() { if (iterator.hasNext()) { // once we get the record from the queue, we also add it to our result final WorkQueue next = iterator.next(); final ITableRecordReference tableRecordReference = next.getTableRecordReference(); final IDLMAware model = tableRecordReference.getModel(ctxAware, IDLMAware.class); add0(tableRecordReference, model.getDLM_Partition_ID(), true); return next; } return queueItemsToProcess.removeFirst(); } @Override public List<WorkQueue> getQueueRecordsToStore() { return queueItemsToProcess; } @Override public List<WorkQueue> getQueueRecordsToDelete() { return queueItemsToDelete; } /** * @return the {@link Partition} from the last invokation of {@link #clearAfterPartitionStored(Partition)}, or an empty partition. */ @Override public Partition getPartition() { return partition; }
@Override public void registerHandler(IIterateResultHandler handler) { handlerSupport.registerListener(handler); } @Override public List<IIterateResultHandler> getRegisteredHandlers() { return handlerSupport.getRegisteredHandlers(); } @Override public boolean isHandlerSignaledToStop() { return handlerSupport.isHandlerSignaledToStop(); } @Override public String toString() { return "IterateResult [queueItemsToProcess.size()=" + queueItemsToProcess.size() + ", queueItemsToDelete.size()=" + queueItemsToDelete.size() + ", size=" + size + ", tableName2Record.size()=" + tableName2Record.size() + ", dlmPartitionId2Record.size()=" + dlmPartitionId2Record.size() + ", iterator=" + iterator + ", ctxAware=" + ctxAware + ", partition=" + partition + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.dlm\base\src\main\java\de\metas\dlm\partitioner\impl\CreatePartitionIterateResult.java
1
请在Spring Boot框架中完成以下Java代码
public class MasterDataSourceConfig { // 精确到 master 目录,以便跟其他数据源隔离 static final String PACKAGE = "org.spring.springboot.dao.master"; static final String MAPPER_LOCATION = "classpath:mapper/master/*.xml"; @Value("${master.datasource.url}") private String url; @Value("${master.datasource.username}") private String user; @Value("${master.datasource.password}") private String password; @Value("${master.datasource.driverClassName}") private String driverClass; @Bean(name = "masterDataSource") @Primary public DataSource masterDataSource() { DruidDataSource dataSource = new DruidDataSource(); dataSource.setDriverClassName(driverClass); dataSource.setUrl(url); dataSource.setUsername(user); dataSource.setPassword(password); return dataSource;
} @Bean(name = "masterTransactionManager") @Primary public DataSourceTransactionManager masterTransactionManager() { return new DataSourceTransactionManager(masterDataSource()); } @Bean(name = "masterSqlSessionFactory") @Primary public SqlSessionFactory masterSqlSessionFactory(@Qualifier("masterDataSource") DataSource masterDataSource) throws Exception { final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean(); sessionFactory.setDataSource(masterDataSource); sessionFactory.setMapperLocations(new PathMatchingResourcePatternResolver() .getResources(MasterDataSourceConfig.MAPPER_LOCATION)); return sessionFactory.getObject(); } }
repos\springboot-learning-example-master\springboot-mybatis-mutil-datasource\src\main\java\org\spring\springboot\config\ds\MasterDataSourceConfig.java
2
请完成以下Java代码
public java.lang.String getHelp () { return (java.lang.String)get_Value(COLUMNNAME_Help); } /** Set Displayed. @param IsDisplayed Determines, if this field is displayed */ @Override public void setIsDisplayed (boolean IsDisplayed) { set_Value (COLUMNNAME_IsDisplayed, Boolean.valueOf(IsDisplayed)); } /** Get Displayed. @return Determines, if this field is displayed */ @Override public boolean isDisplayed () { Object oo = get_Value(COLUMNNAME_IsDisplayed); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set ModelPackage. @param ModelPackage Java Package of the model classes */ @Override public void setModelPackage (java.lang.String ModelPackage) { set_Value (COLUMNNAME_ModelPackage, ModelPackage); } /** Get ModelPackage. @return Java Package of the model classes */ @Override public java.lang.String getModelPackage () { return (java.lang.String)get_Value(COLUMNNAME_ModelPackage); } /** Set Name. @param Name Alphanumeric identifier of the entity */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } /** Set Verarbeiten. @param Processing Verarbeiten */ @Override public void setProcessing (boolean Processing) { set_Value (COLUMNNAME_Processing, Boolean.valueOf(Processing)); } /** Get Verarbeiten. @return Verarbeiten */ @Override public boolean isProcessing () { Object oo = get_Value(COLUMNNAME_Processing); if (oo != null) {
if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Version. @param Version Version of the table definition */ @Override public void setVersion (java.lang.String Version) { set_Value (COLUMNNAME_Version, Version); } /** Get Version. @return Version of the table definition */ @Override public java.lang.String getVersion () { return (java.lang.String)get_Value(COLUMNNAME_Version); } /** Set WebUIServletListener Class. @param WebUIServletListenerClass Optional class to execute custom code on WebUI startup; A declared class needs to implement IWebUIServletListener */ @Override public void setWebUIServletListenerClass (java.lang.String WebUIServletListenerClass) { set_Value (COLUMNNAME_WebUIServletListenerClass, WebUIServletListenerClass); } /** Get WebUIServletListener Class. @return Optional class to execute custom code on WebUI startup; A declared class needs to implement IWebUIServletListener */ @Override public java.lang.String getWebUIServletListenerClass () { return (java.lang.String)get_Value(COLUMNNAME_WebUIServletListenerClass); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_EntityType.java
1
请完成以下Java代码
public class PmsUtil { private static String uploadPath; @Value("${jeecg.path.upload:}") public void setUploadPath(String uploadPath) { PmsUtil.uploadPath = uploadPath; } public static String saveErrorTxtByList(List<String> msg, String name) { Date d = new Date(); String saveDir = "logs" + File.separator + DateUtils.yyyyMMdd.get().format(d) + File.separator; String saveFullDir = uploadPath + File.separator + saveDir; File saveFile = new File(saveFullDir); if (!saveFile.exists()) { saveFile.mkdirs(); } name += DateUtils.yyyymmddhhmmss.get().format(d) + Math.round(Math.random() * 10000); String saveFilePath = saveFullDir + name + ".txt"; try { //封装目的地 BufferedWriter bw = new BufferedWriter(new FileWriter(saveFilePath));
//遍历集合 for (String s : msg) { //写数据 if (s.indexOf("_") > 0) { String[] arr = s.split("_"); bw.write("第" + arr[0] + "行:" + arr[1]); } else { bw.write(s); } //bw.newLine(); bw.write("\r\n"); } //释放资源 bw.flush(); bw.close(); } catch (Exception e) { log.info("excel导入生成错误日志文件异常:" + e.getMessage()); } return saveDir + name + ".txt"; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-boot-base-core\src\main\java\org\jeecg\common\util\PmsUtil.java
1
请完成以下Java代码
public boolean mutateColor(byte color) { int o = __offset(8); if (o != 0) { bb.put(o + bb_pos, color); return true; } else { return false; } } public String navigation() { int o = __offset(10); return o != 0 ? __string(o + bb_pos) : null; } public ByteBuffer navigationAsByteBuffer() { return __vector_as_bytebuffer(10, 1); } public ByteBuffer navigationInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 10, 1); } public MyGame.terrains.Effect effects(int j) { return effects(new MyGame.terrains.Effect(), j); } public MyGame.terrains.Effect effects(MyGame.terrains.Effect obj, int j) { int o = __offset(12); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } public int effectsLength() { int o = __offset(12); return o != 0 ? __vector_len(o) : 0; } public MyGame.terrains.Effect.Vector effectsVector() { return effectsVector(new MyGame.terrains.Effect.Vector()); } public MyGame.terrains.Effect.Vector effectsVector(MyGame.terrains.Effect.Vector obj) { int o = __offset(12); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } public static void startTerrain(FlatBufferBuilder builder) { builder.startTable(5); } public static void addPos(FlatBufferBuilder builder, int posOffset) { builder.addStruct(0, posOffset, 0); } public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(1, nameOffset, 0); } public static void addColor(FlatBufferBuilder builder, byte color) { builder.addByte(2, color, 3); } public static void addNavigation(FlatBufferBuilder builder, int navigationOffset) { builder.addOffset(3, navigationOffset, 0); } public static void addEffects(FlatBufferBuilder builder, int effectsOffset) { builder.addOffset(4, effectsOffset, 0); }
public static int createEffectsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } public static void startEffectsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } public static int endTerrain(FlatBufferBuilder builder) { int o = builder.endTable(); return o; } public static void finishTerrainBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset); } public static void finishSizePrefixedTerrainBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset); } public static final class Vector extends BaseVector { public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } public Terrain get(int j) { return get(new Terrain(), j); } public Terrain get(Terrain obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } } }
repos\tutorials-master\libraries-data-io-2\src\main\java\com\baeldung\flatbuffers\MyGame\terrains\Terrain.java
1
请完成以下Java代码
public class AddApiReqVo { private String app; private String ip; private Integer port; private String apiName; private List<ApiPredicateItemVo> predicateItems; public String getApp() { return app; } public void setApp(String app) { this.app = app; } public String getIp() { return ip; } public void setIp(String ip) { this.ip = ip; } public Integer getPort() { return port; } public void setPort(Integer port) {
this.port = port; } public String getApiName() { return apiName; } public void setApiName(String apiName) { this.apiName = apiName; } public List<ApiPredicateItemVo> getPredicateItems() { return predicateItems; } public void setPredicateItems(List<ApiPredicateItemVo> predicateItems) { this.predicateItems = predicateItems; } }
repos\spring-boot-student-master\spring-boot-student-sentinel-dashboard\src\main\java\com\alibaba\csp\sentinel\dashboard\domain\vo\gateway\api\AddApiReqVo.java
1
请在Spring Boot框架中完成以下Java代码
public Object createCompositeIndex() { // 设置字段名称 String field1 = "name"; String field2 = "age"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field1, field2)); } /** * 创建文字索引 * * @return 索引信息 */ public Object createTextIndex() { // 设置字段名称 String field = "name"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.text(field)); } /** * 创建哈希索引 * * @return 索引信息 */ public Object createHashIndex() { // 设置字段名称 String field = "name"; // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.hashed(field)); }
/** * 创建升序唯一索引 * * @return 索引信息 */ public Object createUniqueIndex() { // 设置字段名称 String indexName = "name"; // 配置索引选项 IndexOptions options = new IndexOptions(); // 设置为唯一索引 options.unique(true); // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(indexName), options); } /** * 创建局部索引 * * @return 索引信息 */ public Object createPartialIndex() { // 设置字段名称 String field = "name"; // 配置索引选项 IndexOptions options = new IndexOptions(); // 设置过滤条件 options.partialFilterExpression(Filters.exists("name", true)); // 创建索引 return mongoTemplate.getCollection(COLLECTION_NAME).createIndex(Indexes.ascending(field), options); } }
repos\springboot-demo-master\mongodb\src\main\java\demo\et\mongodb\service\CreateIndexService.java
2
请完成以下Java代码
public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } public String getTenantId() { return tenantId; } public void setTenantId(String tenantId) { this.tenantId = tenantId; } public String getUserOperationId() { return userOperationId; } public void setUserOperationId(String userOperationId) { this.userOperationId = userOperationId; } public String getRootProcessInstanceId() { return rootProcessInstanceId; } public void setRootProcessInstanceId(String rootProcessInstanceId) { this.rootProcessInstanceId = rootProcessInstanceId; } public void delete() { Context .getCommandContext() .getDbEntityManager() .delete(this); }
@Override public String toString() { return this.getClass().getSimpleName() + "[activityInstanceId=" + activityInstanceId + ", taskId=" + taskId + ", timestamp=" + timestamp + ", eventType=" + eventType + ", executionId=" + executionId + ", processDefinitionId=" + processDefinitionId + ", rootProcessInstanceId=" + rootProcessInstanceId + ", removalTime=" + removalTime + ", processInstanceId=" + processInstanceId + ", id=" + id + ", tenantId=" + tenantId + ", userOperationId=" + userOperationId + "]"; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\history\event\HistoricDetailEventEntity.java
1
请完成以下Java代码
public class ProprietaryPrice2 { @XmlElement(name = "Tp", required = true) protected String tp; @XmlElement(name = "Pric", required = true) protected ActiveOrHistoricCurrencyAndAmount pric; /** * Gets the value of the tp property. * * @return * possible object is * {@link String } * */ public String getTp() { return tp; } /** * Sets the value of the tp property. * * @param value * allowed object is * {@link String } * */ public void setTp(String value) { this.tp = value; } /** * Gets the value of the pric property. * * @return
* possible object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public ActiveOrHistoricCurrencyAndAmount getPric() { return pric; } /** * Sets the value of the pric property. * * @param value * allowed object is * {@link ActiveOrHistoricCurrencyAndAmount } * */ public void setPric(ActiveOrHistoricCurrencyAndAmount value) { this.pric = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.camt53\src\main\java-xjc\de\metas\banking\camt53\jaxb\camt053_001_02\ProprietaryPrice2.java
1
请完成以下Java代码
public String getLineStrokeType () { return (String)get_Value(COLUMNNAME_LineStrokeType); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name.
@return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_PrintTableFormat.java
1
请完成以下Java代码
public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Properties that = (Properties) o; return this.delayMs == that.delayMs && this.maxAttempts == that.maxAttempts && this.numPartitions == that.numPartitions && this.suffix.equals(that.suffix) && this.type == that.type && this.dltStrategy == that.dltStrategy && this.kafkaOperations.equals(that.kafkaOperations); } @Override public int hashCode() { return Objects.hash(this.delayMs, this.suffix, this.type, this.maxAttempts, this.numPartitions, this.dltStrategy, this.kafkaOperations); } @Override public String toString() { return "Properties{" + "delayMs=" + this.delayMs + ", suffix='" + this.suffix + '\'' + ", type=" + this.type + ", maxAttempts=" + this.maxAttempts + ", numPartitions=" + this.numPartitions + ", dltStrategy=" + this.dltStrategy + ", kafkaOperations=" + this.kafkaOperations + ", shouldRetryOn=" + this.shouldRetryOn +
", timeout=" + this.timeout + '}'; } public boolean isMainEndpoint() { return Type.MAIN.equals(this.type); } } enum Type { MAIN, RETRY, /** * A retry topic reused along sequential retries * with the same back off interval. * * @since 3.0.4 */ REUSABLE_RETRY_TOPIC, DLT, NO_OPS } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\DestinationTopic.java
1
请完成以下Spring Boot application配置
logging.level.root=info logging.file=gaoxi-log/order-log.log spring.datasource.driverClassName = com.mysql.jdbc.Driver spring.datasource.url = jdbc:mysql://172.17.0.9:3306/gaoxi?useUnicode=true&characterEncoding=utf-8 spring.datasource.username = root spring.datasource.password = jishimen.2018 ## Dubbo 服务提供者配置 spring.dubbo.application.name=order-provider spring.dubbo.registry.address=zookeeper://172.17.0.2:2181 spring
.dubbo.protocol.name=dubbo spring.dubbo.protocol.port=20880 spring.dubbo.scan=com.gaoxi.order.service spring.redis.host=172.17.0.10 spring.redis.port=6379 spring.redis.timeout=60000
repos\SpringBoot-Dubbo-Docker-Jenkins-master\Gaoxi-Order\src\main\resources\application-test.properties
2
请完成以下Java代码
public void setOverrides_Window(final org.compiere.model.I_AD_Window Overrides_Window) { set_ValueFromPO(COLUMNNAME_Overrides_Window_ID, org.compiere.model.I_AD_Window.class, Overrides_Window); } @Override public void setOverrides_Window_ID (final int Overrides_Window_ID) { if (Overrides_Window_ID < 1) set_Value (COLUMNNAME_Overrides_Window_ID, null); else set_Value (COLUMNNAME_Overrides_Window_ID, Overrides_Window_ID); } @Override public int getOverrides_Window_ID() { return get_ValueAsInt(COLUMNNAME_Overrides_Window_ID); } @Override public void setProcessing (final boolean Processing) { set_Value (COLUMNNAME_Processing, Processing); } @Override public boolean isProcessing() { return get_ValueAsBoolean(COLUMNNAME_Processing); } /** * WindowType AD_Reference_ID=108 * Reference name: AD_Window Types */ public static final int WINDOWTYPE_AD_Reference_ID=108; /** Single Record = S */ public static final String WINDOWTYPE_SingleRecord = "S"; /** Maintain = M */ public static final String WINDOWTYPE_Maintain = "M"; /** Transaktion = T */ public static final String WINDOWTYPE_Transaktion = "T"; /** Query Only = Q */ public static final String WINDOWTYPE_QueryOnly = "Q"; @Override public void setWindowType (final java.lang.String WindowType) { set_Value (COLUMNNAME_WindowType, WindowType); } @Override public java.lang.String getWindowType() { return get_ValueAsString(COLUMNNAME_WindowType); } @Override public void setWinHeight (final int WinHeight) { set_Value (COLUMNNAME_WinHeight, WinHeight); }
@Override public int getWinHeight() { return get_ValueAsInt(COLUMNNAME_WinHeight); } @Override public void setWinWidth (final int WinWidth) { set_Value (COLUMNNAME_WinWidth, WinWidth); } @Override public int getWinWidth() { return get_ValueAsInt(COLUMNNAME_WinWidth); } @Override public void setZoomIntoPriority (final int ZoomIntoPriority) { set_Value (COLUMNNAME_ZoomIntoPriority, ZoomIntoPriority); } @Override public int getZoomIntoPriority() { return get_ValueAsInt(COLUMNNAME_ZoomIntoPriority); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Window.java
1
请完成以下Java代码
public String getChildJobId() { return childJobId; } public void setChildJobId(String childJobId) { this.childJobId = childJobId; } public int getTriggerStatus() { return triggerStatus; } public void setTriggerStatus(int triggerStatus) { this.triggerStatus = triggerStatus; } public long getTriggerLastTime() {
return triggerLastTime; } public void setTriggerLastTime(long triggerLastTime) { this.triggerLastTime = triggerLastTime; } public long getTriggerNextTime() { return triggerNextTime; } public void setTriggerNextTime(long triggerNextTime) { this.triggerNextTime = triggerNextTime; } }
repos\JeecgBoot-main\jeecg-boot\jeecg-server-cloud\jeecg-visual\jeecg-cloud-xxljob\src\main\java\com\xxl\job\admin\core\model\XxlJobInfo.java
1
请完成以下Java代码
public void addMouseListener (MouseListener l) { m_textPane.addMouseListener(l); } /** * Add Key Listener * @param l listner */ @Override public void addKeyListener (KeyListener l) { m_textPane.addKeyListener(l); } /** * Add Input Method Listener * @param l listener */ @Override public void addInputMethodListener (InputMethodListener l) { m_textPane.addInputMethodListener(l); } /** * Get Input Method Requests * @return requests */ @Override public InputMethodRequests getInputMethodRequests() { return m_textPane.getInputMethodRequests(); } /** * Set Input Verifier * @param l verifyer */ @Override public void setInputVerifier (InputVerifier l) { m_textPane.setInputVerifier(l); } // metas: begin public String getContentType() { if (m_textPane != null) return m_textPane.getContentType(); return null; } 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 void setDescription(String value) { set(3, value); } /** * Getter for <code>public.Book.description</code>. */ public String getDescription() { return (String) get(3); } /** * Setter for <code>public.Book.store_id</code>. */ public void setStoreId(Integer value) { set(4, value); } /** * Getter for <code>public.Book.store_id</code>. */ public Integer getStoreId() { return (Integer) get(4); } // ------------------------------------------------------------------------- // Primary key information // ------------------------------------------------------------------------- @Override public Record1<Integer> key() { return (Record1) super.key(); } // ------------------------------------------------------------------------- // Constructors // ------------------------------------------------------------------------- /** * Create a detached BookRecord */
public BookRecord() { super(Book.BOOK); } /** * Create a detached, initialised BookRecord */ public BookRecord(Integer id, Integer authorId, String title, String description, Integer storeId) { super(Book.BOOK); setId(id); setAuthorId(authorId); setTitle(title); setDescription(description); setStoreId(storeId); resetChangedOnNotNull(); } }
repos\tutorials-master\persistence-modules\jooq\src\main\java\com\baeldung\jooq\jointables\public_\tables\records\BookRecord.java
1
请完成以下Java代码
public boolean isNewUser(User user) { return ((UserEntity) user).getRevision() == 0; } @Override public Picture getUserPicture(User user) { UserEntity userEntity = (UserEntity) user; return userEntity.getPicture(); } @Override public void setUserPicture(User user, Picture picture) { UserEntity userEntity = (UserEntity) user; userEntity.setPicture(picture); dataManager.update(userEntity); } @Override public List<User> findUsersByPrivilegeId(String name) {
return dataManager.findUsersByPrivilegeId(name); } public UserDataManager getUserDataManager() { return dataManager; } public void setUserDataManager(UserDataManager userDataManager) { this.dataManager = userDataManager; } protected IdentityInfoEntityManager getIdentityInfoEntityManager() { return engineConfiguration.getIdentityInfoEntityManager(); } protected MembershipEntityManager getMembershipEntityManager() { return engineConfiguration.getMembershipEntityManager(); } }
repos\flowable-engine-main\modules\flowable-idm-engine\src\main\java\org\flowable\idm\engine\impl\persistence\entity\UserEntityManagerImpl.java
1
请完成以下Java代码
public static void collectionExistsSolution() { MongoDatabase db = mongoClient.getDatabase(databaseName); System.out.println("collectionName " + testCollectionName + db.listCollectionNames().into(new ArrayList<>()).contains(testCollectionName)); } public static void createCollectionSolution() { MongoDatabase database = mongoClient.getDatabase(databaseName); try { database.createCollection(testCollectionName); } catch (Exception exception) { System.err.println("Collection already Exists"); } } public static void listCollectionNamesSolution() { MongoDatabase database = mongoClient.getDatabase(databaseName); boolean collectionExists = database.listCollectionNames() .into(new ArrayList<String>()) .contains(testCollectionName); System.out.println("collectionExists:- " + collectionExists); } public static void countSolution() { MongoDatabase database = mongoClient.getDatabase(databaseName); MongoCollection<Document> collection = database.getCollection(testCollectionName); System.out.println(collection.countDocuments()); } public static void main(String args[]) { // // Connect to cluster (default is localhost:27017) // setUp();
// // Check the db existence using DB class's method // collectionExistsSolution(); // // Check the db existence using the createCollection method of MongoDatabase class // createCollectionSolution(); // // Check the db existence using the listCollectionNames method of MongoDatabase class // listCollectionNamesSolution(); // // Check the db existence using the count method of MongoDatabase class // countSolution(); } }
repos\tutorials-master\persistence-modules\java-mongodb-3\src\main\java\com\baeldung\mongo\collectionexistence\CollectionExistence.java
1
请完成以下Java代码
public class PostalAddressSEPA { @XmlElement(name = "Ctry") protected String ctry; @XmlElement(name = "AdrLine") protected List<String> adrLine; /** * Gets the value of the ctry property. * * @return * possible object is * {@link String } * */ public String getCtry() { return ctry; } /** * Sets the value of the ctry property. * * @param value * allowed object is * {@link String } * */ public void setCtry(String value) { this.ctry = value; } /** * Gets the value of the adrLine property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the adrLine property. * * <p> * For example, to add a new item, do as follows:
* <pre> * getAdrLine().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link String } * * */ public List<String> getAdrLine() { if (adrLine == null) { adrLine = new ArrayList<String>(); } return this.adrLine; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sepa\schema-pain_008_003_02\src\main\java-xjc\de\metas\payment\sepa\jaxb\sct\pain_008_003_02\PostalAddressSEPA.java
1
请完成以下Java代码
public Long getMilliseconds() { return milliseconds; } public void setMilliseconds(Long milliseconds) { this.milliseconds = milliseconds; } public String getName() { return name; } public void setName(String name) { this.name = name; } public long getValue() { return value; } public void setValue(long value) { this.value = value; } public String getReporter() { return reporter; } public void setReporter(String reporter) { this.reporter = reporter; } public Object getPersistentState() { // immutable
return MeterLogEntity.class; } @Override public Set<String> getReferencedEntityIds() { Set<String> referencedEntityIds = new HashSet<String>(); return referencedEntityIds; } @Override public Map<String, Class> getReferencedEntitiesIdAndClass() { Map<String, Class> referenceIdAndClass = new HashMap<String, Class>(); return referenceIdAndClass; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\persistence\entity\MeterLogEntity.java
1
请完成以下Java代码
public void onAttributeUpdate(UUID sessionId, TransportProtos.AttributeUpdateNotificationMsg notification) { log.trace("[{}] Received attributes update notification to device", sessionId); try { parent.getPayloadAdaptor().convertToGatewayPublish(this, getDeviceInfo().getDeviceName(), notification).ifPresent(parent::writeAndFlush); } catch (Exception e) { log.trace("[{}] Failed to convert device attributes response to MQTT msg", sessionId, e); } } @Override public void onToDeviceRpcRequest(UUID sessionId, TransportProtos.ToDeviceRpcRequestMsg request) { log.trace("[{}] Received RPC command to device", sessionId); try { parent.getPayloadAdaptor().convertToGatewayPublish(this, getDeviceInfo().getDeviceName(), request).ifPresent( payload -> { ChannelFuture channelFuture = parent.writeAndFlush(payload); if (request.getPersisted()) { channelFuture.addListener(result -> { if (result.cause() == null) { if (!isAckExpected(payload)) { transportService.process(getSessionInfo(), request, RpcStatus.DELIVERED, TransportServiceCallback.EMPTY); } else if (request.getPersisted()) { transportService.process(getSessionInfo(), request, RpcStatus.SENT, TransportServiceCallback.EMPTY); } } }); } } ); } catch (Exception e) { transportService.process(getSessionInfo(), TransportProtos.ToDeviceRpcResponseMsg.newBuilder()
.setRequestId(request.getRequestId()).setError("Failed to convert device RPC command to MQTT msg").build(), TransportServiceCallback.EMPTY); log.trace("[{}] Failed to convert device attributes response to MQTT msg", sessionId, e); } } @Override public void onRemoteSessionCloseCommand(UUID sessionId, TransportProtos.SessionCloseNotificationProto sessionCloseNotification) { log.trace("[{}] Received the remote command to close the session: {}", sessionId, sessionCloseNotification.getMessage()); parent.deregisterSession(getDeviceInfo().getDeviceName()); } @Override public void onToServerRpcResponse(TransportProtos.ToServerRpcResponseMsg toServerResponse) { // This feature is not supported in the TB IoT Gateway yet. } @Override public void onDeviceDeleted(DeviceId deviceId) { parent.onDeviceDeleted(this.getSessionInfo().getDeviceName()); } private boolean isAckExpected(MqttMessage message) { return message.fixedHeader().qosLevel().value() > 0; } }
repos\thingsboard-master\common\transport\mqtt\src\main\java\org\thingsboard\server\transport\mqtt\session\AbstractGatewayDeviceSessionContext.java
1
请完成以下Java代码
String getAdLanguage() { return Env.getContext(getCtx(), Env.CTXNAME_AD_Language); } Language getLanguage() { return Env.getLanguage(getCtx()); } /** * @return previous language */ String verifyLanguageAndSet(final Language lang) { final Properties ctx = getCtx(); final String adLanguageOld = Env.getContext(ctx, Env.CTXNAME_AD_Language);
// // Check the language (and update it if needed) final Language validLang = Env.verifyLanguageFallbackToBase(lang); // // Actual update final String adLanguageNew = validLang.getAD_Language(); Env.setContext(ctx, Env.CTXNAME_AD_Language, adLanguageNew); this.locale = validLang.getLocale(); UserSession.logger.debug("Changed AD_Language: {} -> {}, {}", adLanguageOld, adLanguageNew, validLang); return adLanguageOld; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\session\InternalUserSessionData.java
1
请完成以下Java代码
public ModelQuery orderByModelCategory() { return orderBy(ModelQueryProperty.MODEL_CATEGORY); } @Override public ModelQuery orderByModelId() { return orderBy(ModelQueryProperty.MODEL_ID); } @Override public ModelQuery orderByModelKey() { return orderBy(ModelQueryProperty.MODEL_KEY); } @Override public ModelQuery orderByModelVersion() { return orderBy(ModelQueryProperty.MODEL_VERSION); } @Override public ModelQuery orderByModelName() { return orderBy(ModelQueryProperty.MODEL_NAME); } @Override public ModelQuery orderByCreateTime() { return orderBy(ModelQueryProperty.MODEL_CREATE_TIME); } @Override public ModelQuery orderByLastUpdateTime() { return orderBy(ModelQueryProperty.MODEL_LAST_UPDATE_TIME); } @Override public ModelQuery orderByTenantId() { return orderBy(ModelQueryProperty.MODEL_TENANT_ID); } // results //////////////////////////////////////////// @Override public long executeCount(CommandContext commandContext) { return CommandContextUtil.getModelEntityManager(commandContext).findModelCountByQueryCriteria(this); } @Override public List<Model> executeList(CommandContext commandContext) { return CommandContextUtil.getModelEntityManager(commandContext).findModelsByQueryCriteria(this); } // getters //////////////////////////////////////////// public String getId() { return id; } public String getName() { return name; } public String getNameLike() { return nameLike; } public Integer getVersion() { return version; } public String getCategory() { return category; } public String getCategoryLike() { return categoryLike; }
public String getCategoryNotEquals() { return categoryNotEquals; } public static long getSerialversionuid() { return serialVersionUID; } public String getKey() { return key; } public boolean isLatest() { return latest; } public String getDeploymentId() { return deploymentId; } public boolean isNotDeployed() { return notDeployed; } public boolean isDeployed() { return deployed; } public String getTenantId() { return tenantId; } public String getTenantIdLike() { return tenantIdLike; } public boolean isWithoutTenantId() { return withoutTenantId; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ModelQueryImpl.java
1
请完成以下Java代码
public File getPDF(String fileNamePrefix) { throw new UnsupportedOperationException(); } private void actionPreview() { // final ReportEngine re = getReportEngine(); // ReportCtl.preview(re); File pdf = getPDF(null); if (pdf != null) { Env.startBrowser(pdf.toURI().toString()); } } private Dialog getParentDialog() { Dialog parent = null; Container e = getParent(); while (e != null) { if (e instanceof Dialog) { parent = (Dialog)e; break; } e = e.getParent(); } return parent; } public boolean print() { throw new UnsupportedOperationException(); } public static boolean isHtml(String s) { if (s == null) return false; String s2 = s.trim().toUpperCase(); return s2.startsWith("<HTML>"); } public static String convertToHtml(String plainText)
{ if (plainText == null) return null; return plainText.replaceAll("[\r]*\n", "<br/>\n"); } public boolean isResolveVariables() { return boilerPlateMenu.isResolveVariables(); } public void setResolveVariables(boolean isResolveVariables) { boilerPlateMenu.setResolveVariables(isResolveVariables); } public void setEnablePrint(boolean enabled) { butPrint.setEnabled(enabled); butPrint.setVisible(enabled); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\compiere\grid\ed\RichTextEditor.java
1
请完成以下Java代码
public class BCDtoDecimalConverter { /** * Converts a single packed BCD byte to an integer. * Each byte represents two decimal digits. * * @param bcdByte The BCD byte to convert. * @return The decimal integer value. * @throws IllegalArgumentException if any nibble contains a non-BCD value (>9). */ public static int convertPackedByte(byte bcdByte) { int resultDecimal; int upperNibble = (bcdByte >> 4) & 0x0F; int lowerNibble = bcdByte & 0x0F; if (upperNibble > 9 || lowerNibble > 9) { throw new IllegalArgumentException( String.format("Invalid BCD format: byte 0x%02X contains non-decimal digit.", bcdByte) ); } resultDecimal = upperNibble * 10 + lowerNibble; return resultDecimal; } /** * Converts a BCD byte array to a long decimal value. * Each byte in the array iis mapped to a packed BCD byte,
* representing two BCD nibbles. * * @param bcdArray The array of BCD bytes. * @return The combined long decimal value. * @throws IllegalArgumentException if any nibble contains a non-BCD value (>9). */ public static long convertPackedByteArray(byte[] bcdArray) { long resultDecimal = 0; for (byte bcd : bcdArray) { int upperNibble = (bcd >> 4) & 0x0F; int lowerNibble = bcd & 0x0F; if (upperNibble > 9 || lowerNibble > 9) { throw new IllegalArgumentException("Invalid BCD format: nibble contains non-decimal digit."); } resultDecimal = resultDecimal * 100 + (upperNibble * 10 + lowerNibble); } return resultDecimal; } }
repos\tutorials-master\algorithms-modules\algorithms-numeric\src\main\java\com\baeldung\algorithms\bcdtodecimal\BCDtoDecimalConverter.java
1
请完成以下Java代码
public Object start() { return Timer.start(this.registry); } public void success(Object sample, String queue) { Timer timer = this.timers.get(queue + "none"); if (timer == null) { timer = buildTimer(this.listenerId, "success", queue, "none"); } ((Sample) sample).stop(timer); } public void failure(Object sample, String queue, String exception) { Timer timer = this.timers.get(queue + exception); if (timer == null) { timer = buildTimer(this.listenerId, "failure", queue, exception); } ((Sample) sample).stop(timer); } private Timer buildTimer(String aListenerId, String result, String queue, String exception) {
Builder builder = Timer.builder("spring.rabbitmq.listener") .description("Spring RabbitMQ Listener") .tag("listener.id", aListenerId) .tag("queue", queue) .tag("result", result) .tag("exception", exception); if (!CollectionUtils.isEmpty(this.tags)) { this.tags.forEach(builder::tag); } Timer registeredTimer = builder.register(this.registry); this.timers.put(queue + exception, registeredTimer); return registeredTimer; } void destroy() { this.timers.values().forEach(this.registry::remove); this.timers.clear(); } }
repos\spring-amqp-main\spring-rabbit\src\main\java\org\springframework\amqp\rabbit\listener\MicrometerHolder.java
1
请完成以下Java代码
private static Object[] invokeSuppliers(final Object... params) { if (params == null) { return null; } final ArrayList<Object> result = new ArrayList<>(params.length); for (final Object param : params) { if (param instanceof Supplier) { @SuppressWarnings("rawtypes") final Supplier paramSupplier = (Supplier)param; result.add(paramSupplier.get()); } else { result.add(param); } } return result.toArray(); } public static <T> T singleElement(@NonNull final Collection<T> collection)
{ Check.errorUnless(collection.size() == 1, "The given collection needs to have exactly one 1 item, but has {} items; collection={}", collection.size(), collection); return collection.iterator().next(); } public static <T> boolean isSingleElement(@Nullable final Collection<T> collection) { if (isEmpty(collection)) { return false; } return collection.size() == 1; } }
repos\metasfresh-new_dawn_uat\misc\de-metas-common\de-metas-common-util\src\main\java\de\metas\common\util\Check.java
1
请在Spring Boot框架中完成以下Java代码
public class AppConfig implements WebMvcConfigurer { @Bean public InMemoryUserDetailsManager userDetailsService(PasswordEncoder passwordEncoder) { UserDetails user = User.withUsername("user") .password(passwordEncoder.encode("userPass")) .roles("USER") .build(); UserDetails admin = User.withUsername("admin") .password(passwordEncoder.encode("adminPass")) .roles("ADMIN") .build(); return new InMemoryUserDetailsManager(user, admin); } @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { http.authorizeHttpRequests(auth -> auth
.anyRequest() .authenticated()) .httpBasic(Customizer.withDefaults()) .csrf(AbstractHttpConfigurer::disable); return http.build(); } @Bean public PasswordEncoder passwordEncoder() { return new BCryptPasswordEncoder(); } public enum Role { ROLE_USER, ROLE_ADMIN } }
repos\tutorials-master\spring-security-modules\spring-security-core-2\src\main\java\com\baeldung\filterresponse\config\AppConfig.java
2
请完成以下Java代码
public WarehouseId retrieveWarehouseId(final I_M_Storage storage) { final int locatorId = storage.getM_Locator_ID(); return Services.get(IWarehouseDAO.class).getWarehouseIdByLocatorRepoId(locatorId); } /** * Invokes {@link MStorage#getQtyAvailable(int, int, int, int, String)}. */ @Override public BigDecimal retrieveQtyAvailable(final int wareHouseId, final int locatorId, final int productId, final int attributeSetInstanceId, final String trxName) { return MStorage.getQtyAvailable(wareHouseId, locatorId, productId, attributeSetInstanceId, trxName); } @Override public BigDecimal retrieveQtyOrdered(final int productId, final int warehouseId) { ResultSet rs = null; final PreparedStatement pstmt = DB.prepareStatement( SQL_SELECT_QTY_ORDERED, null); try { pstmt.setInt(1, productId); pstmt.setInt(2, warehouseId); rs = pstmt.executeQuery(); if (rs.next()) { final BigDecimal qtyOrdered = rs.getBigDecimal(1); if (qtyOrdered == null) { return BigDecimal.ZERO;
} return qtyOrdered; } throw new RuntimeException( "Unable to retrive qtyOrdererd for M_Product_ID '" + productId + "'"); } catch (SQLException e) { throw new RuntimeException(e); } finally { DB.close(rs, pstmt); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\product\impl\StoragePA.java
1
请完成以下Java代码
public void setPostal (final @Nullable java.lang.String Postal) { set_ValueNoCheck (COLUMNNAME_Postal, Postal); } @Override public java.lang.String getPostal() { return get_ValueAsString(COLUMNNAME_Postal); } /** * TerminationReason AD_Reference_ID=540761 * Reference name: Contracts_TerminationaReason */ public static final int TERMINATIONREASON_AD_Reference_ID=540761; /** HighAge = Hi */ public static final String TERMINATIONREASON_HighAge = "Hi"; /** DidNotOrder = Dno */ public static final String TERMINATIONREASON_DidNotOrder = "Dno"; /** General = Ge */ public static final String TERMINATIONREASON_General = "Ge"; /** Religion = Rel */ public static final String TERMINATIONREASON_Religion = "Rel"; /** NoTime = Nt */ public static final String TERMINATIONREASON_NoTime = "Nt"; /** TooMuchPapers = Tmp */ public static final String TERMINATIONREASON_TooMuchPapers = "Tmp"; /** FinancialReasons = Fr */ public static final String TERMINATIONREASON_FinancialReasons = "Fr"; /** TooModern = Tm */ public static final String TERMINATIONREASON_TooModern = "Tm"; /** NoInterest = Ni */ public static final String TERMINATIONREASON_NoInterest = "Ni"; /** NewSubscriptionType = Nst */ public static final String TERMINATIONREASON_NewSubscriptionType = "Nst"; /** GiftNotRenewed = Gnr */ public static final String TERMINATIONREASON_GiftNotRenewed = "Gnr"; /** StayingForeign = Sf */ public static final String TERMINATIONREASON_StayingForeign = "Sf";
/** Died = Di */ public static final String TERMINATIONREASON_Died = "Di"; /** Sick = Si */ public static final String TERMINATIONREASON_Sick = "Si"; /** DoubleReader = Dr */ public static final String TERMINATIONREASON_DoubleReader = "Dr"; /** SubscriptionSwitch = Ss */ public static final String TERMINATIONREASON_SubscriptionSwitch = "Ss"; /** LimitedDelivery = Ld */ public static final String TERMINATIONREASON_LimitedDelivery = "Ld"; /** PrivateReasons = Pr */ public static final String TERMINATIONREASON_PrivateReasons = "Pr"; /** CanNotRead = Cnr */ public static final String TERMINATIONREASON_CanNotRead = "Cnr"; /** NotReachable = Nr */ public static final String TERMINATIONREASON_NotReachable = "Nr"; /** IncorrectlyRecorded = Err */ public static final String TERMINATIONREASON_IncorrectlyRecorded = "Err"; /** OrgChange = Os */ public static final String TERMINATIONREASON_OrgChange = "Os"; @Override public void setTerminationReason (final @Nullable java.lang.String TerminationReason) { set_ValueNoCheck (COLUMNNAME_TerminationReason, TerminationReason); } @Override public java.lang.String getTerminationReason() { return get_ValueAsString(COLUMNNAME_TerminationReason); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Export.java
1
请完成以下Java代码
public static PPOrderRoutingProductId ofRepoId(@NonNull final PPOrderRoutingActivityId orderId, final int repoId) { return new PPOrderRoutingProductId(orderId, repoId); } @Nullable public static PPOrderRoutingProductId ofRepoIdOrNull(@NonNull final PPOrderRoutingActivityId orderId, final int repoId) { return repoId > 0 ? new PPOrderRoutingProductId(orderId, repoId) : null; } public static int toRepoId(@Nullable final PPOrderRoutingProductId id) { return id != null ? id.getRepoId() : -1; }
private PPOrderRoutingProductId(@NonNull final PPOrderRoutingActivityId activityId, final int repoId) { this.activityId = activityId; this.repoId = Check.assumeGreaterThanZero(repoId, "PP_Order_Node_ID"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final PPOrderRoutingProductId id1, @Nullable final PPOrderRoutingProductId id2) { return Objects.equals(id1, id2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.manufacturing\src\main\java\org\eevolution\api\PPOrderRoutingProductId.java
1
请在Spring Boot框架中完成以下Java代码
public void setMaxInactiveInterval(Duration maxInactiveInterval) { this.maxInactiveInterval = maxInactiveInterval; } @Deprecated public void setMaxInactiveIntervalInSeconds(int maxInactiveIntervalInSeconds) { setMaxInactiveInterval(Duration.ofSeconds(maxInactiveIntervalInSeconds)); } protected Duration getMaxInactiveInterval() { return this.maxInactiveInterval; } public void setRedisNamespace(String namespace) { Assert.hasText(namespace, "namespace must not be empty"); this.redisNamespace = namespace; } protected String getRedisNamespace() { return this.redisNamespace; } public void setFlushMode(FlushMode flushMode) { Assert.notNull(flushMode, "flushMode must not be null"); this.flushMode = flushMode; } protected FlushMode getFlushMode() { return this.flushMode; } public void setSaveMode(SaveMode saveMode) { Assert.notNull(saveMode, "saveMode must not be null"); this.saveMode = saveMode; } protected SaveMode getSaveMode() { return this.saveMode; } @Autowired public void setRedisConnectionFactory( @SpringSessionRedisConnectionFactory ObjectProvider<RedisConnectionFactory> springSessionRedisConnectionFactory, ObjectProvider<RedisConnectionFactory> redisConnectionFactory) { this.redisConnectionFactory = springSessionRedisConnectionFactory .getIfAvailable(redisConnectionFactory::getObject); } protected RedisConnectionFactory getRedisConnectionFactory() { return this.redisConnectionFactory; } @Autowired(required = false) @Qualifier("springSessionDefaultRedisSerializer") public void setDefaultRedisSerializer(RedisSerializer<Object> defaultRedisSerializer) { this.defaultRedisSerializer = defaultRedisSerializer; } protected RedisSerializer<Object> getDefaultRedisSerializer() { return this.defaultRedisSerializer; }
@Autowired(required = false) public void setSessionRepositoryCustomizer( ObjectProvider<SessionRepositoryCustomizer<T>> sessionRepositoryCustomizers) { this.sessionRepositoryCustomizers = sessionRepositoryCustomizers.orderedStream().collect(Collectors.toList()); } protected List<SessionRepositoryCustomizer<T>> getSessionRepositoryCustomizers() { return this.sessionRepositoryCustomizers; } @Override public void setBeanClassLoader(ClassLoader classLoader) { this.classLoader = classLoader; } protected RedisTemplate<String, Object> createRedisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setKeySerializer(RedisSerializer.string()); redisTemplate.setHashKeySerializer(RedisSerializer.string()); if (getDefaultRedisSerializer() != null) { redisTemplate.setDefaultSerializer(getDefaultRedisSerializer()); } redisTemplate.setConnectionFactory(getRedisConnectionFactory()); redisTemplate.setBeanClassLoader(this.classLoader); redisTemplate.afterPropertiesSet(); return redisTemplate; } }
repos\spring-session-main\spring-session-data-redis\src\main\java\org\springframework\session\data\redis\config\annotation\web\http\AbstractRedisHttpSessionConfiguration.java
2
请完成以下Java代码
public BigDecimal getInvoicedAmt() { return invoicedAmt; } public BigDecimal getPaymentExistingAmt() { return paymentExistingAmt; } public BigDecimal getPaymentCandidatesAmt() { return paymentCandidatesAmt; } public BigDecimal getDiffInvoiceMinusPay() { return diffInvoiceMinusPay; } public boolean hasDifferences() { return diffInvoiceMinusPay.signum() != 0; } public boolean isMoreInvoicedThanPaid() { final int invoicedAmtSign = invoicedAmt.signum(); final int paymentAmtSign = paymentTotalAmt.signum(); if (invoicedAmtSign >= 0) { // Positive invoiced, positive paid if (paymentAmtSign >= 0) { return invoicedAmt.compareTo(paymentTotalAmt) > 0; } // Positive invoiced, negative paid else { return true; // more invoiced than paid } } else { // Negative invoiced, positive paid if (paymentAmtSign >= 0) { return false; // more paid than invoiced } // Negative invoiced, negative paid else { return invoicedAmt.abs().compareTo(paymentTotalAmt.abs()) > 0; } } } // // // ------------------------------------------------------------------------------------------------------------------------------ // // public static final class Builder { private BigDecimal invoicedAmt = BigDecimal.ZERO; private BigDecimal paymentExistingAmt = BigDecimal.ZERO;
private BigDecimal paymentCandidatesAmt = BigDecimal.ZERO; private Builder() { super(); } public PaymentAllocationTotals build() { return new PaymentAllocationTotals(this); } public Builder setInvoicedAmt(final BigDecimal invoicedAmt) { this.invoicedAmt = invoicedAmt; return this; } public Builder setPaymentExistingAmt(final BigDecimal paymentExistingAmt) { this.paymentExistingAmt = paymentExistingAmt; return this; } public Builder setPaymentCandidatesAmt(final BigDecimal paymentCandidatesAmt) { this.paymentCandidatesAmt = paymentCandidatesAmt; return this; } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.banking\de.metas.banking.swingui\src\main\java\de\metas\banking\payment\paymentallocation\model\PaymentAllocationTotals.java
1
请完成以下Java代码
public String getEmail() { return email; } public void setEmail(String username) { this.email = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Collection<Role> getRoles() { return roles; } public void setRoles(Collection<Role> roles) { this.roles = roles; } public boolean isEnabled() { return enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public boolean isUsing2FA() { return isUsing2FA; } public void setUsing2FA(boolean isUsing2FA) { this.isUsing2FA = isUsing2FA; }
@Override public int hashCode() { int prime = 31; int result = 1; result = (prime * result) + ((email == null) ? 0 : email.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } User user = (User) obj; if (!email.equals(user.email)) { return false; } return true; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("User [id=").append(id).append(", firstName=") .append(firstName).append(", lastName=").append(lastName).append(", email=").append(email).append(", password=").append(password).append(", enabled=").append(enabled).append(", roles=").append(roles).append("]"); return builder.toString(); } }
repos\tutorials-master\spring-security-modules\spring-security-web-boot-1\src\main\java\com\baeldung\roles\rolesauthorities\model\User.java
1
请完成以下Java代码
public PO getPO() { return po; } @Override public AdWindowId getAD_Window_ID() { return adWindowId; } @Override public String getTableName() { return po.get_TableName(); } @Override public int getAD_Table_ID() { return po.get_Table_ID(); } @Override public String getKeyColumnNameOrNull() { return keyColumnName; } @Override public int getRecord_ID() { return po.get_ID(); } @Override public boolean isSingleKeyRecord() { return keyColumnName != null; } @Override public Properties getCtx() { return po.getCtx(); } @Override public String getTrxName() { return po.get_TrxName(); } @Override public Evaluatee createEvaluationContext() { final Properties privateCtx = Env.deriveCtx(getCtx()); final PO po = getPO(); final POInfo poInfo = po.getPOInfo(); for (int i = 0; i < poInfo.getColumnCount(); i++) { final Object val; final int dispType = poInfo.getColumnDisplayType(i); if (DisplayType.isID(dispType)) { // make sure we get a 0 instead of a null for foreign keys val = po.get_ValueAsInt(i); } else
{ val = po.get_Value(i); } if (val == null) { continue; } if (val instanceof Integer) { Env.setContext(privateCtx, "#" + po.get_ColumnName(i), (Integer)val); } else if (val instanceof String) { Env.setContext(privateCtx, "#" + po.get_ColumnName(i), (String)val); } } return Evaluatees.ofCtx(privateCtx, Env.WINDOW_None, false); } @Override public boolean hasField(final String columnName) { return po.getPOInfo().hasColumnName(columnName); } @Override public Object getFieldValue(final String columnName) { return po.get_Value(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\document\references\related_documents\POZoomSource.java
1
请完成以下Java代码
public void setSetup_Place_No (final @Nullable java.lang.String Setup_Place_No) { set_Value (COLUMNNAME_Setup_Place_No, Setup_Place_No); } @Override public java.lang.String getSetup_Place_No() { return get_ValueAsString(COLUMNNAME_Setup_Place_No); } @Override public void setValidFrom (final @Nullable java.sql.Timestamp ValidFrom) { set_Value (COLUMNNAME_ValidFrom, ValidFrom); } @Override public java.sql.Timestamp getValidFrom() { return get_ValueAsTimestamp(COLUMNNAME_ValidFrom); } @Override public void setVATaxID (final @Nullable java.lang.String VATaxID) {
set_Value (COLUMNNAME_VATaxID, VATaxID); } @Override public java.lang.String getVATaxID() { return get_ValueAsString(COLUMNNAME_VATaxID); } @Override public void setVisitorsAddress (final boolean VisitorsAddress) { set_Value (COLUMNNAME_VisitorsAddress, VisitorsAddress); } @Override public boolean isVisitorsAddress() { return get_ValueAsBoolean(COLUMNNAME_VisitorsAddress); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_BPartner_Location.java
1
请完成以下Java代码
private static DhlClientConfig retrieveConfig(final int shipperId) { final I_DHL_Shipper_Config configPO = Services.get(IQueryBL.class) .createQueryBuilder(I_DHL_Shipper_Config.class) .addOnlyActiveRecordsFilter() .addEqualsFilter(I_DHL_Shipper_Config.COLUMNNAME_M_Shipper_ID, shipperId) .orderBy(I_DHL_Shipper_Config.COLUMNNAME_DHL_Shipper_Config_ID) .create() .first(); if (configPO == null) { throw new AdempiereException("No DHL shipper configuration found for shipperId=" + shipperId); } return DhlClientConfig.builder() .applicationID(configPO.getapplicationID()) .applicationToken(configPO.getApplicationToken())
.baseUrl(configPO.getdhl_api_url()) .accountNumber(configPO.getAccountNumber()) .username(configPO.getUserName()) .signature(configPO.getSignature()) .lengthUomId(UomId.ofRepoId(configPO.getDhl_LenghtUOM_ID())) .trackingUrlBase(retrieveTrackingUrl(configPO.getM_Shipper_ID())) .build(); } private static String retrieveTrackingUrl(final int m_shipper_id) { final I_M_Shipper shipperPo = InterfaceWrapperHelper.load(m_shipper_id, I_M_Shipper.class); return shipperPo.getTrackingURL(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dhl\src\main\java\de\metas\shipper\gateway\dhl\model\DhlClientConfigRepository.java
1
请完成以下Java代码
public void setDueDate (final java.sql.Timestamp DueDate) { set_Value (COLUMNNAME_DueDate, DueDate); } @Override public java.sql.Timestamp getDueDate() { return get_ValueAsTimestamp(COLUMNNAME_DueDate); } @Override public void setOffsetDays (final int OffsetDays) { set_Value (COLUMNNAME_OffsetDays, OffsetDays); } @Override public int getOffsetDays() { return get_ValueAsInt(COLUMNNAME_OffsetDays); } @Override public void setPercent (final int Percent) { set_Value (COLUMNNAME_Percent, Percent); } @Override public int getPercent() { return get_ValueAsInt(COLUMNNAME_Percent); } /** * ReferenceDateType AD_Reference_ID=541989 * Reference name: ReferenceDateType */ public static final int REFERENCEDATETYPE_AD_Reference_ID=541989; /** InvoiceDate = IV */ public static final String REFERENCEDATETYPE_InvoiceDate = "IV"; /** BLDate = BL */ public static final String REFERENCEDATETYPE_BLDate = "BL"; /** OrderDate = OD */ public static final String REFERENCEDATETYPE_OrderDate = "OD"; /** LCDate = LC */ public static final String REFERENCEDATETYPE_LCDate = "LC"; /** ETADate = ET */ public static final String REFERENCEDATETYPE_ETADate = "ET"; @Override public void setReferenceDateType (final java.lang.String ReferenceDateType) { set_Value (COLUMNNAME_ReferenceDateType, ReferenceDateType); }
@Override public java.lang.String getReferenceDateType() { return get_ValueAsString(COLUMNNAME_ReferenceDateType); } @Override public void setSeqNo (final int SeqNo) { set_Value (COLUMNNAME_SeqNo, SeqNo); } @Override public int getSeqNo() { return get_ValueAsInt(COLUMNNAME_SeqNo); } /** * Status AD_Reference_ID=541993 * Reference name: C_OrderPaySchedule_Status */ public static final int STATUS_AD_Reference_ID=541993; /** Pending_Ref = PR */ public static final String STATUS_Pending_Ref = "PR"; /** Awaiting_Pay = WP */ public static final String STATUS_Awaiting_Pay = "WP"; /** Paid = P */ public static final String STATUS_Paid = "P"; @Override public void setStatus (final java.lang.String Status) { set_Value (COLUMNNAME_Status, Status); } @Override public java.lang.String getStatus() { return get_ValueAsString(COLUMNNAME_Status); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_OrderPaySchedule.java
1
请完成以下Java代码
protected boolean beforeSave(final boolean newRecord) { if (getAD_User_ID() == -1) // Summary Project in Dimensions setAD_User_ID(0); // Set Currency if (is_ValueChanged("M_PriceList_Version_ID") && getM_PriceList_Version_ID() != 0) { final I_M_PriceList pl = Services.get(IPriceListDAO.class).getById(getM_PriceList_ID()); if (pl != null && pl.getM_PriceList_ID() > 0) setC_Currency_ID(pl.getC_Currency_ID()); } return true; } // beforeSave /** * After Save * * @param newRecord new * @param success success * @return success */ @Override protected boolean afterSave(final boolean newRecord, final boolean success) { if (newRecord && success) { insert_Accounting("C_Project_Acct", "C_AcctSchema_Default", null); }
// Value/Name change if (success && !newRecord && (is_ValueChanged("Value") || is_ValueChanged("Name"))) MAccount.updateValueDescription(getCtx(), "C_Project_ID=" + getC_Project_ID(), get_TrxName()); return success; } // afterSave /** * Before Delete * * @return true */ @Override protected boolean beforeDelete() { return delete_Accounting("C_Project_Acct"); } // beforeDelete }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MProject.java
1
请完成以下Java代码
private static ProductId computeProductIdEffective( @NonNull final I_PP_Order_BOMLine orderBOMLine, @Nullable final ProductId productId) { final ProductId bomLineProductId = ProductId.ofRepoId(orderBOMLine.getM_Product_ID()); if (productId == null) { return bomLineProductId; } else if (orderBOMLine.isAllowIssuingAnyProduct()) { return productId; } else { if (!ProductId.equals(productId, bomLineProductId)) { throw new AdempiereException("Product " + productId + " is not matching BOM line product " + bomLineProductId) .appendParametersToMessage() .setParameter("orderBOMLine", orderBOMLine); } return bomLineProductId; } } /** * @return infinite capacity because we don't want to enforce how many items we can allocate on this storage */ @Override protected Capacity retrieveTotalCapacity() { checkStaled(); final I_C_UOM uom = ppOrderBOMBL.getBOMLineUOM(orderBOMLine); return Capacity.createInfiniteCapacity(productId, uom); } /** * @return quantity that was already issued/received on this order BOM Line */ @Override protected BigDecimal retrieveQtyInitial() {
checkStaled(); final Quantity qtyCapacity; final Quantity qtyToIssueOrReceive; final BOMComponentType componentType = BOMComponentType.ofCode(orderBOMLine.getComponentType()); if (componentType.isReceipt()) { qtyCapacity = ppOrderBOMBL.getQtyRequiredToReceive(orderBOMLine); qtyToIssueOrReceive = ppOrderBOMBL.getQtyToReceive(orderBOMLine); } else { qtyCapacity = ppOrderBOMBL.getQtyRequiredToIssue(orderBOMLine); qtyToIssueOrReceive = ppOrderBOMBL.getQtyToIssue(orderBOMLine); } final Quantity qtyIssued = qtyCapacity.subtract(qtyToIssueOrReceive); return qtyIssued.toBigDecimal(); } @Override protected void beforeMarkingStalled() { staled = true; } /** * refresh BOM line if staled */ private void checkStaled() { if (!staled) { return; } InterfaceWrapperHelper.refresh(orderBOMLine); staled = false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\pporder\api\impl\PPOrderBOMLineProductStorage.java
1
请完成以下Java代码
public class Employee { private String name; private String department; private String city; private Integer salary; public Employee(String name, String department, String city, Integer salary) { this.name = name; this.department = department; this.city = city; this.salary = salary; } public Integer getSalary() { return salary; } public void setSalary(Integer salary) { this.salary = salary; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getDepartment() {
return department; } public void setDepartment(String department) { this.department = department; } public String getCity() { return city; } public void setCity(String city) { this.city = city; } }
repos\tutorials-master\spring-cloud-modules\spring-cloud-functions-azure\src\main\java\com\baeldung\azure\functions\entity\Employee.java
1
请在Spring Boot框架中完成以下Java代码
public class HistoricMilestoneInstanceResponse { protected String id; protected String name; protected String elementId; @JsonSerialize(using = DateToStringSerializer.class, as = Date.class) protected Date timestamp; protected String caseInstanceId; protected String caseDefinitionId; protected String url; protected String historicCaseInstanceUrl; protected String caseDefinitionUrl; @ApiModelProperty(example = "5") public String getId() { return id; } public void setId(String id) { this.id = id; } @ApiModelProperty(example = "milestoneName") public String getName() { return name; } public void setName(String name) { this.name = name; } @ApiModelProperty(example = "milestonePlanItemId") public String getElementId() { return elementId; } public void setElementId(String elementId) { this.elementId = elementId; } @ApiModelProperty(example = "2013-04-18T14:06:32.715+0000") public Date getTimestamp() { return timestamp; } public void setTimestamp(Date timestamp) { this.timestamp = timestamp; } @ApiModelProperty(example = "12345") public String getCaseInstanceId() { return caseInstanceId; } public void setCaseInstanceId(String caseInstanceId) { this.caseInstanceId = caseInstanceId; }
@ApiModelProperty(example = "oneMilestoneCase%3A1%3A4") public String getCaseDefinitionId() { return caseDefinitionId; } public void setCaseDefinitionId(String caseDefinitionId) { this.caseDefinitionId = caseDefinitionId; } @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-milestone-instances/5") public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } @ApiModelProperty(example = "http://localhost:8182/cmmn-history/historic-case-instances/12345") public String getHistoricCaseInstanceUrl() { return historicCaseInstanceUrl; } public void setHistoricCaseInstanceUrl(String historicCaseInstanceUrl) { this.historicCaseInstanceUrl = historicCaseInstanceUrl; } @ApiModelProperty(example = "http://localhost:8182/cmmn-repository/case-definitions/oneMilestoneCase%3A1%3A4") public String getCaseDefinitionUrl() { return caseDefinitionUrl; } public void setCaseDefinitionUrl(String caseDefinitionUrl) { this.caseDefinitionUrl = caseDefinitionUrl; } }
repos\flowable-engine-main\modules\flowable-cmmn-rest\src\main\java\org\flowable\cmmn\rest\service\api\history\milestone\HistoricMilestoneInstanceResponse.java
2
请完成以下Java代码
static int pairs(List<Integer> dices, int nrOfPairs) { Map<Integer, Long> frequency = dices.stream() .collect(groupingBy(identity(), counting())); List<Integer> pairs = frequency .entrySet().stream() .filter(it -> it.getValue() >= 2) .map(Map.Entry::getKey) .toList(); if (pairs.size() < nrOfPairs) { return 0; } return pairs.stream() .sorted(reverseOrder()) .limit(nrOfPairs) .mapToInt(it -> it * 2) .sum(); } static Integer moreOfSameKind(List<Integer> roll, int nrOfDicesOfSameKind) {
Map<Integer, Long> frequency = roll.stream() .collect(groupingBy(identity(), counting())); Optional<Integer> diceValue = frequency.entrySet().stream() .filter(entry -> entry.getValue() >= nrOfDicesOfSameKind) .map(Map.Entry::getKey) .max(Integer::compare); return diceValue.map(it -> it * nrOfDicesOfSameKind) .orElse(0); } static Integer specificValue(List<Integer> dices, Integer value) { return dices.stream() .filter(value::equals) .mapToInt(it -> it) .sum(); } }
repos\tutorials-master\patterns-modules\data-oriented-programming\src\main\java\com\baeldung\patterns\ScoringRules.java
1
请完成以下Java代码
public JsonNode createJsonNode(String parameter) { return objectMapper.getNodeFactory().textNode(parameter); } public JsonNode createJsonNode(Integer parameter) { return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Float parameter) { return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Double parameter) { return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Long parameter) { return objectMapper.getNodeFactory().numberNode(parameter); } public JsonNode createJsonNode(Boolean parameter) { return objectMapper.getNodeFactory().booleanNode(parameter); } public JsonNode createJsonNode(List<Object> parameter) { if (parameter != null) { ArrayNode node = objectMapper.getNodeFactory().arrayNode(); for(Object entry : parameter) { node.add(createJsonNode(entry)); } return node; } else { return createNullJsonNode(); } }
public JsonNode createJsonNode(Map<String, Object> parameter) { if (parameter != null) { ObjectNode node = objectMapper.getNodeFactory().objectNode(); for (Map.Entry<String, Object> entry : parameter.entrySet()) { node.set(entry.getKey(), createJsonNode(entry.getValue())); } return node; } else { return createNullJsonNode(); } } public JsonNode createNullJsonNode() { return objectMapper.getNodeFactory().nullNode(); } }
repos\camunda-bpm-platform-master\spin\dataformat-json-jackson\src\main\java\org\camunda\spin\impl\json\jackson\format\JacksonJsonDataFormat.java
1
请在Spring Boot框架中完成以下Java代码
public class SubscriptionLineDescriptor implements DocumentLineDescriptor { public static SubscriptionLineDescriptor cast(@NonNull final DocumentLineDescriptor documentLineDescriptor) { return (SubscriptionLineDescriptor)documentLineDescriptor; } int subscriptionProgressId; int flatrateTermId; int subscriptionBillBPartnerId; @Builder @JsonCreator public SubscriptionLineDescriptor( @JsonProperty("subscriptionProgressId") final int subscriptionProgressId,
@JsonProperty("flatrateTermId") final int flatrateTermId, @JsonProperty("subscriptionBillBPartnerId") final int subscriptionBillBPartnerId) { this.subscriptionProgressId = subscriptionProgressId; this.flatrateTermId = flatrateTermId; this.subscriptionBillBPartnerId = subscriptionBillBPartnerId; } @Override public void validate() { checkIdGreaterThanZero("subscriptionProgressId", subscriptionProgressId); checkIdGreaterThanZero("flatrateTermId", flatrateTermId); checkIdGreaterThanZero("subscriptionBillBPartnerId", subscriptionBillBPartnerId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.material\event\src\main\java\de\metas\material\event\commons\SubscriptionLineDescriptor.java
2
请完成以下Java代码
public MMovementLine getLine() { if (m_line == null) m_line = new MMovementLine (getCtx(), getM_MovementLine_ID(), get_TrxName()); return m_line; } // getLine /** * Process Confirmation Line. * - Update Movement Line * @return success */ public boolean processLine () { MMovementLine line = getLine(); line.setTargetQty(getTargetQty()); line.setMovementQty(getConfirmedQty()); line.setConfirmedQty(getConfirmedQty()); line.setScrappedQty(getScrappedQty()); return line.save(get_TrxName()); } // processConfirmation /** * Is Fully Confirmed * @return true if Target = Confirmed qty */ public boolean isFullyConfirmed() { return getTargetQty().compareTo(getConfirmedQty()) == 0; } // isFullyConfirmed /** * Before Delete - do not delete * @return false */ protected boolean beforeDelete () {
return false; } // beforeDelete /** * Before Save * @param newRecord new * @return true */ protected boolean beforeSave (boolean newRecord) { // Calculate Difference = Target - Confirmed - Scrapped BigDecimal difference = getTargetQty(); difference = difference.subtract(getConfirmedQty()); difference = difference.subtract(getScrappedQty()); setDifferenceQty(difference); // return true; } // beforeSave } // M_MovementLineConfirm
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\compiere\model\MMovementLineConfirm.java
1
请完成以下Java代码
public class PlanItemOnPartImpl extends OnPartImpl implements PlanItemOnPart { protected static AttributeReference<PlanItem> sourceRefAttribute; protected static ChildElement<PlanItemTransitionStandardEvent> standardEventChild; // cmmn 1.0 @Deprecated protected static AttributeReference<Sentry> sentryRefAttribute; // cmmn 1.1 protected static AttributeReference<ExitCriterion> exitCriterionRefAttribute; public PlanItemOnPartImpl(ModelTypeInstanceContext instanceContext) { super(instanceContext); } public Sentry getSentry() { return sentryRefAttribute.getReferenceTargetElement(this); } public void setSentry(Sentry sentry) { sentryRefAttribute.setReferenceTargetElement(this, sentry); } public ExitCriterion getExitCriterion() { return exitCriterionRefAttribute.getReferenceTargetElement(this); } public void setExitCriterion(ExitCriterion exitCriterion) { exitCriterionRefAttribute.setReferenceTargetElement(this, exitCriterion); } public PlanItem getSource() { return sourceRefAttribute.getReferenceTargetElement(this); } public void setSource(PlanItem source) { sourceRefAttribute.setReferenceTargetElement(this, source); } public PlanItemTransition getStandardEvent() { PlanItemTransitionStandardEvent child = standardEventChild.getChild(this); return child.getValue(); } public void setStandardEvent(PlanItemTransition standardEvent) { PlanItemTransitionStandardEvent child = standardEventChild.getChild(this); child.setValue(standardEvent); } public static void registerType(ModelBuilder modelBuilder) { ModelElementTypeBuilder typeBuilder = modelBuilder.defineType(PlanItemOnPart.class, CMMN_ELEMENT_PLAN_ITEM_ON_PART) .extendsType(OnPart.class) .namespaceUri(CMMN11_NS)
.instanceProvider(new ModelTypeInstanceProvider<PlanItemOnPart>() { public PlanItemOnPart newInstance(ModelTypeInstanceContext instanceContext) { return new PlanItemOnPartImpl(instanceContext); } }); sourceRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SOURCE_REF) .idAttributeReference(PlanItem.class) .build(); exitCriterionRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_EXIT_CRITERION_REF) .idAttributeReference(ExitCriterion.class) .build(); sentryRefAttribute = typeBuilder.stringAttribute(CMMN_ATTRIBUTE_SENTRY_REF) .namespace(CMMN10_NS) .idAttributeReference(Sentry.class) .build(); SequenceBuilder sequenceBuilder = typeBuilder.sequence(); standardEventChild = sequenceBuilder.element(PlanItemTransitionStandardEvent.class) .build(); typeBuilder.build(); } }
repos\camunda-bpm-platform-master\model-api\cmmn-model\src\main\java\org\camunda\bpm\model\cmmn\impl\instance\PlanItemOnPartImpl.java
1
请完成以下Java代码
public class MapRequestHeaderGatewayFilterFactory extends AbstractGatewayFilterFactory<MapRequestHeaderGatewayFilterFactory.Config> { /** * From Header key. */ public static final String FROM_HEADER_KEY = "fromHeader"; /** * To Header key. */ public static final String TO_HEADER_KEY = "toHeader"; public MapRequestHeaderGatewayFilterFactory() { super(Config.class); } @Override public List<String> shortcutFieldOrder() { return Arrays.asList(FROM_HEADER_KEY, TO_HEADER_KEY); } @Override public GatewayFilter apply(MapRequestHeaderGatewayFilterFactory.Config config) { return new GatewayFilter() { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { String fromHeader = Objects.requireNonNull(config.getFromHeader(), "fromHeader must be set"); String toHeader = Objects.requireNonNull(config.getToHeader(), "toHeader must be set"); if (!exchange.getRequest().getHeaders().containsHeader(fromHeader)) { return chain.filter(exchange); } List<String> headerValues = exchange.getRequest().getHeaders().get(fromHeader); if (headerValues == null) { return chain.filter(exchange); } ServerHttpRequest request = exchange.getRequest() .mutate() .headers(i -> i.addAll(toHeader, headerValues)) .build(); return chain.filter(exchange.mutate().request(request).build()); } @Override public String toString() { // @formatter:off String fromHeader = config.getFromHeader(); String toHeader = config.getToHeader(); return filterToStringCreator(MapRequestHeaderGatewayFilterFactory.this) .append(FROM_HEADER_KEY, fromHeader != null ? fromHeader : "") .append(TO_HEADER_KEY, toHeader != null ? toHeader : "") .toString(); // @formatter:on } }; } public static class Config { private @Nullable String fromHeader;
private @Nullable String toHeader; public @Nullable String getFromHeader() { return this.fromHeader; } public Config setFromHeader(String fromHeader) { this.fromHeader = fromHeader; return this; } public @Nullable String getToHeader() { return this.toHeader; } public Config setToHeader(String toHeader) { this.toHeader = toHeader; return this; } @Override public String toString() { // @formatter:off return new ToStringCreator(this) .append("fromHeader", fromHeader) .append("toHeader", toHeader) .toString(); // @formatter:on } } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webflux\src\main\java\org\springframework\cloud\gateway\filter\factory\MapRequestHeaderGatewayFilterFactory.java
1
请完成以下Java代码
public class UserHandler implements Handler { private static final Logger LOGGER = Logger.getLogger(UserHandler.class.getSimpleName()); private static final List<User> USERS = new ArrayList<>(); private final GraphQL graphql; public UserHandler() throws Exception { graphql = GraphQL.newGraphQL(new UserSchema().getSchema()).build(); } @Override public void handle(Context context) { context.parse(Map.class) .then(payload -> { Map<String, Object> parameters = (Map<String, Object>) payload.get("parameters"); ExecutionResult executionResult = graphql.execute(payload.get(SchemaUtils.QUERY) .toString(), null, this, parameters); Map<String, Object> result = new LinkedHashMap<>(); if (executionResult.getErrors().isEmpty()) { result.put(SchemaUtils.DATA, executionResult.getData()); } else {
result.put(SchemaUtils.ERRORS, executionResult.getErrors()); LOGGER.warning("Errors: " + executionResult.getErrors()); } context.render(json(result)); }); } public List<User> getUsers() { return USERS; } public static List<User> getUsers(DataFetchingEnvironment env) { return ((UserHandler) env.getSource()).getUsers(); } }
repos\tutorials-master\graphql-modules\graphql-java\src\main\java\com\baeldung\graphql\handler\UserHandler.java
1
请在Spring Boot框架中完成以下Java代码
public R<IPage<DataScopeVO>> list(DataScope dataScope, Query query) { IPage<DataScope> pages = dataScopeService.page(Condition.getPage(query), Condition.getQueryWrapper(dataScope)); return R.data(DataScopeWrapper.build().pageVO(pages)); } /** * 新增 */ @PostMapping("/save") @ApiOperationSupport(order = 3) @Operation(summary = "新增", description = "传入dataScope") public R save(@Valid @RequestBody DataScope dataScope) { CacheUtil.clear(SYS_CACHE); return R.status(dataScopeService.save(dataScope)); } /** * 修改 */ @PostMapping("/update") @ApiOperationSupport(order = 4) @Operation(summary = "修改", description = "传入dataScope") public R update(@Valid @RequestBody DataScope dataScope) { CacheUtil.clear(SYS_CACHE); return R.status(dataScopeService.updateById(dataScope)); } /** * 新增或修改 */ @PostMapping("/submit")
@ApiOperationSupport(order = 5) @Operation(summary = "新增或修改", description = "传入dataScope") public R submit(@Valid @RequestBody DataScope dataScope) { CacheUtil.clear(SYS_CACHE); return R.status(dataScopeService.saveOrUpdate(dataScope)); } /** * 删除 */ @PostMapping("/remove") @ApiOperationSupport(order = 6) @Operation(summary = "逻辑删除", description = "传入ids") public R remove(@Parameter(description = "主键集合", required = true) @RequestParam String ids) { CacheUtil.clear(SYS_CACHE); return R.status(dataScopeService.deleteLogic(Func.toLongList(ids))); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\controller\DataScopeController.java
2
请完成以下Java代码
public int sendRequestWithAuthenticator(String url) throws IOException, URISyntaxException { setAuthenticator(); HttpURLConnection connection = null; try { connection = createConnection(url); return connection.getResponseCode(); } finally { if (connection != null) { connection.disconnect(); } } } private HttpURLConnection createConnection(String urlString) throws MalformedURLException, IOException, URISyntaxException { URL url = new URI(String.format(urlString)).toURL(); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); return connection; }
private String createBasicAuthHeaderValue() { String auth = user + ":" + password; byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.UTF_8)); String authHeaderValue = "Basic " + new String(encodedAuth); return authHeaderValue; } private void setAuthenticator() { Authenticator.setDefault(new BasicAuthenticator()); } private final class BasicAuthenticator extends Authenticator { protected PasswordAuthentication getPasswordAuthentication() { return new PasswordAuthentication(user, password.toCharArray()); } } }
repos\tutorials-master\core-java-modules\core-java-networking-2\src\main\java\com\baeldung\url\auth\HttpClient.java
1
请完成以下Java代码
default Set<String> getDependsOnContextVariables() { return ImmutableSet.of(); } Evaluatee prepareContext(final IAttributeSet attributeSet); /** * List of available values. * * NOTE: in case of {@link #isHighVolume()} it might be that the returned list is empty. * * @return fixed list of attribute values that are accepted */ List<? extends NamePair> getAvailableValues(Evaluatee evalCtx); /** * Gets the value {@link NamePair} for given "value" ID. * * NOTE: if we are dealing with a high-volume attribute values list and if attribute is not found in loaded list, it will be loaded directly from database. * * @return attribute value or null */ NamePair getAttributeValueOrNull(final Evaluatee evalCtx, Object valueKey); AttributeValueId getAttributeValueIdOrNull(final Object valueKey); /**
* Value to be used for "nulls". * * In case the list has defined a particular value for Nulls, that one will be returned. If not, actual <code>null</code> will be returned. * * @return {@link NamePair} for null or <code>null</code> */ NamePair getNullValue(); /** * @return true if he have a high volume values list */ boolean isHighVolume(); // // Caching String getCachePrefix(); List<CCacheStats> getCacheStats(); }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\adempiere\mm\attributes\spi\IAttributeValuesProvider.java
1
请完成以下Java代码
public Throwable getError() { return error; } @Override public final void export(@NonNull final OutputStream out) { final IExportDataSource dataSource = getDataSource(); Check.assumeNotNull(dataSource, "dataSource not null"); Check.assume(ExportStatus.NotStarted.equals(getExportStatus()), "ExportStatus shall be " + ExportStatus.NotStarted + " and not {}", getExportStatus()); IExportDataDestination dataDestination = null; try { // Init dataDestination // NOTE: make sure we are doing this as first thing, because if anything fails, we need to close this "destination" dataDestination = createDataDestination(out); // Init status error = null; setExportStatus(ExportStatus.Running); monitor.exportStarted(this); while (dataSource.hasNext()) { final List<Object> values = dataSource.next(); // for (int i = 1; i <= 3000; i++) // debugging // { appendRow(dataDestination, values); incrementExportedRowCount(); // } } } catch (Exception e) { final AdempiereException ex = new AdempiereException("Error while exporting line " + getExportedRowCount() + ": " + e.getLocalizedMessage(), e); error = ex; throw ex; } finally { close(dataSource); close(dataDestination); dataDestination = null; setExportStatus(ExportStatus.Finished); // Notify the monitor but discard all exceptions because we don't want to throw an "false" exception in finally block try { monitor.exportFinished(this); } catch (Exception e) { logger.error("Error while invoking monitor(finish): " + e.getLocalizedMessage(), e); }
} logger.info("Exported " + getExportedRowCount() + " rows"); } protected abstract void appendRow(IExportDataDestination dataDestination, List<Object> values) throws IOException; protected abstract IExportDataDestination createDataDestination(OutputStream out) throws IOException; /** * Close {@link Closeable} object. * * NOTE: if <code>closeableObj</code> is not implementing {@link Closeable} or is null, nothing will happen * * @param closeableObj */ private static final void close(Object closeableObj) { if (closeableObj instanceof Closeable) { final Closeable closeable = (Closeable)closeableObj; try { closeable.close(); } catch (IOException e) { e.printStackTrace(); // NOPMD by tsa on 3/17/13 1:30 PM } } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\data\export\api\impl\AbstractExporter.java
1
请完成以下Java代码
public void preInit(ProcessEngineConfigurationImpl processEngineConfiguration) { LdapPluginLogger.INSTANCE.pluginActivated(getClass().getSimpleName(), processEngineConfiguration.getProcessEngineName()); if(acceptUntrustedCertificates) { CertificateHelper.acceptUntrusted(); LdapPluginLogger.INSTANCE.acceptingUntrustedCertificates(); } LdapIdentityProviderFactory ldapIdentityProviderFactory = new LdapIdentityProviderFactory(); ldapIdentityProviderFactory.setLdapConfiguration(this); processEngineConfiguration.setIdentityProviderSessionFactory(ldapIdentityProviderFactory); } public void postInit(ProcessEngineConfigurationImpl processEngineConfiguration) {
// nothing to do } public void postProcessEngineBuild(ProcessEngine processEngine) { // nothing to do } public void setAcceptUntrustedCertificates(boolean acceptUntrustedCertificates) { this.acceptUntrustedCertificates = acceptUntrustedCertificates; } public boolean isAcceptUntrustedCertificates() { return acceptUntrustedCertificates; } }
repos\camunda-bpm-platform-master\engine-plugins\identity-ldap\src\main\java\org\camunda\bpm\identity\impl\ldap\plugin\LdapIdentityProviderPlugin.java
1
请完成以下Java代码
protected void invokePostLifecycleListeners() { super.invokePostLifecycleListeners(); CommandContextUtil.getCmmnEngineConfiguration(commandContext).getEventDispatcher() .dispatchEvent(FlowableCmmnEventBuilder.createCaseEndedEvent(caseInstanceEntity, CaseInstanceState.TERMINATED), EngineConfigurationConstants.KEY_CMMN_ENGINE_CONFIG); } @Override public String getDeleteReason() { return "cmmn-state-transition-terminate-case"; } @Override public void addAdditionalCallbackData(CallbackData callbackData) { if (callbackData.getAdditionalData() == null) { callbackData.setAdditionalData(new HashMap<>()); } callbackData.getAdditionalData().put(CallbackConstants.EXIT_TYPE, exitType); callbackData.getAdditionalData().put(CallbackConstants.EXIT_EVENT_TYPE, exitEventType); callbackData.getAdditionalData().put(CallbackConstants.MANUAL_TERMINATION, manualTermination); } @Override public CaseInstanceEntity getCaseInstanceEntity() { if (caseInstanceEntity == null) { caseInstanceEntity = CommandContextUtil.getCaseInstanceEntityManager(commandContext).findById(caseInstanceEntityId); if (caseInstanceEntity == null) { throw new FlowableObjectNotFoundException("No case instance found for id " + caseInstanceEntityId); } } return caseInstanceEntity; } public boolean isManualTermination() { return manualTermination; }
public void setManualTermination(boolean manualTermination) { this.manualTermination = manualTermination; } public String getExitCriterionId() { return exitCriterionId; } public void setExitCriterionId(String exitCriterionId) { this.exitCriterionId = exitCriterionId; } public String getExitType() { return exitType; } public void setExitType(String exitType) { this.exitType = exitType; } public String getExitEventType() { return exitEventType; } public void setExitEventType(String exitEventType) { this.exitEventType = exitEventType; } }
repos\flowable-engine-main\modules\flowable-cmmn-engine\src\main\java\org\flowable\cmmn\engine\impl\agenda\operation\TerminateCaseInstanceOperation.java
1
请在Spring Boot框架中完成以下Java代码
public class CheckReviewEventHandler { private static final Logger logger = Logger.getLogger(CheckReviewEventHandler.class.getName()); public final BookReviewRepository bookReviewRepository; public CheckReviewEventHandler(BookReviewRepository bookReviewRepository) { this.bookReviewRepository = bookReviewRepository; } @Async @TransactionalEventListener @Transactional(propagation = Propagation.REQUIRES_NEW) public void handleCheckReviewEvent(CheckReviewEvent event) { BookReview bookReview = event.getBookReview(); logger.info(() -> "Starting checking of review: " + bookReview.getId()); try { // simulate a check out of review grammar, content, acceptance // policies, reviewer email, etc via artificial delay of 5s for demonstration purposes
String content = bookReview.getContent(); // check content String email = bookReview.getEmail(); // validate email Thread.sleep(40000); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); // log exception } if (new Random().nextBoolean()) { bookReview.setStatus(ReviewStatus.ACCEPT); logger.info(() -> "Book review " + bookReview.getId() + " was accepted ..."); } else { bookReview.setStatus(ReviewStatus.REJECT); logger.info(() -> "Book review " + bookReview.getId() + " was rejected ..."); } bookReviewRepository.save(bookReview); logger.info(() -> "Checking review " + bookReview.getId() + " done!"); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootDomainEvents\src\main\java\com\bookstore\event\CheckReviewEventHandler.java
2
请在Spring Boot框架中完成以下Java代码
public String getLangKey() { return langKey; } public void setLangKey(String langKey) { this.langKey = langKey; } public Set<Authority> getAuthorities() { return authorities; } public void setAuthorities(Set<Authority> authorities) { this.authorities = authorities; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof User)) { return false; }
return id != null && id.equals(((User) o).id); } @Override public int hashCode() { // see https://vladmihalcea.com/how-to-implement-equals-and-hashcode-using-the-jpa-entity-identifier/ return getClass().hashCode(); } // prettier-ignore @Override public String toString() { return "User{" + "login='" + login + '\'' + ", firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", email='" + email + '\'' + ", imageUrl='" + imageUrl + '\'' + ", activated='" + activated + '\'' + ", langKey='" + langKey + '\'' + ", activationKey='" + activationKey + '\'' + "}"; } }
repos\tutorials-master\jhipster-8-modules\jhipster-8-microservice\gateway-app\src\main\java\com\gateway\domain\User.java
2
请完成以下Java代码
private static AttributesIncludedTabDataField newDataField(final AttributesIncludedTabFieldBinding fieldBinding) { return AttributesIncludedTabDataField.builder() .attributeId(fieldBinding.getAttributeId()) .valueType(fieldBinding.getAttributeValueType()) .build(); } private void refreshDocumentFromData(@NonNull final Document document, @NonNull final AttributesIncludedTabData data) { document.refreshFromSupplier(new AttributesIncludedTabDataAsDocumentValuesSupplier(data)); } @Override
public void delete(final @NotNull Document document) { throw new UnsupportedOperationException(); } @Override public String retrieveVersion(final DocumentEntityDescriptor entityDescriptor, final int documentIdAsInt) {return AttributesIncludedTabDataAsDocumentValuesSupplier.VERSION_DEFAULT;} @Override public int retrieveLastLineNo(final DocumentQuery query) { throw new UnsupportedOperationException(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\attributes_included_tab\AttributesIncludedTabDocumentsRepository.java
1
请完成以下Java代码
public static boolean isCompensationThrowing(PvmExecutionImpl execution) { return isCompensationThrowing(execution, execution.createActivityExecutionMapping()); } protected static PvmExecutionImpl findCompensationThrowingAncestorExecution(PvmExecutionImpl execution) { ExecutionWalker walker = new ExecutionWalker(execution); walker.walkUntil(new ReferenceWalker.WalkCondition<PvmExecutionImpl>() { public boolean isFulfilled(PvmExecutionImpl element) { return element == null || CompensationBehavior.isCompensationThrowing(element); } }); return walker.getCurrentElement(); } /** * See #CAM-10978 * Use case process instance with <code>asyncBefore</code> startEvent * After unifying the history variable's creation<br> * The following changed:<br> * * variables will receive the <code>processInstanceId</code> as <code>activityInstanceId</code> in such cases (previously was the startEvent id)<br> * * historic details have new <code>initial</code> property to track initial variables that process is started with<br> * The jobs created prior <code>7.13</code> and not executed before do not have historic information of variables. * This method takes care of that.
*/ public static void createMissingHistoricVariables(PvmExecutionImpl execution) { Collection<VariableInstanceEntity> variables = ((ExecutionEntity) execution).getVariablesInternal(); if (variables != null && variables.size() > 0) { // trigger historic creation if the history is not presented already for (VariableInstanceEntity variable : variables) { if (variable.wasCreatedBefore713()) { VariableInstanceHistoryListener.INSTANCE.onCreate(variable, variable.getExecution()); } } } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\pvm\runtime\LegacyBehavior.java
1
请完成以下Java代码
public Error newInstance(ModelTypeInstanceContext instanceContext) { return new ErrorImpl(instanceContext); } }); nameAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_NAME) .build(); errorCodeAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_ERROR_CODE) .build(); camundaErrorMessageAttribute = typeBuilder.stringAttribute(CAMUNDA_ATTRIBUTE_ERROR_MESSAGE).namespace(CAMUNDA_NS) .build(); structureRefAttribute = typeBuilder.stringAttribute(BPMN_ATTRIBUTE_STRUCTURE_REF) .qNameAttributeReference(ItemDefinition.class) .build(); typeBuilder.build(); } public ErrorImpl(ModelTypeInstanceContext context) { super(context); } public String getName() { return nameAttribute.getValue(this); } public void setName(String name) { nameAttribute.setValue(this, name); }
public String getErrorCode() { return errorCodeAttribute.getValue(this); } public void setErrorCode(String errorCode) { errorCodeAttribute.setValue(this, errorCode); } public String getCamundaErrorMessage() { return camundaErrorMessageAttribute.getValue(this); } public void setCamundaErrorMessage(String camundaErrorMessage) { camundaErrorMessageAttribute.setValue(this, camundaErrorMessage); } public ItemDefinition getStructure() { return structureRefAttribute.getReferenceTargetElement(this); } public void setStructure(ItemDefinition structure) { structureRefAttribute.setReferenceTargetElement(this, structure); } }
repos\camunda-bpm-platform-master\model-api\bpmn-model\src\main\java\org\camunda\bpm\model\bpmn\impl\instance\ErrorImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class ChannelDefinitionResourceDataResource extends BaseDeploymentResourceDataResource { @ApiOperation(value = "Get a channel definition resource content", tags = { "Channel Definitions" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "Indicates both channel definition and resource have been found and the resource data has been returned."), @ApiResponse(code = 404, message = "Indicates the requested channel definition was not found or there is no resource with the given id present in the channel definition. The status-description contains additional information.") }) @GetMapping(value = "/event-registry-repository/channel-definitions/{channelDefinitionId}/resourcedata") public byte[] getChannelDefinitionResource(@ApiParam(name = "channelDefinitionId") @PathVariable String channelDefinitionId, HttpServletResponse response) { ChannelDefinition channelDefinition = getChannelDefinitionFromRequest(channelDefinitionId); return getDeploymentResourceData(channelDefinition.getDeploymentId(), channelDefinition.getResourceName(), response); } /** * Returns the {@link ChannelDefinition} that is requested. Throws the right exceptions when bad request was made or definition was not found.
*/ protected ChannelDefinition getChannelDefinitionFromRequest(String channelDefinitionId) { ChannelDefinition channelDefinition = repositoryService.createChannelDefinitionQuery().channelDefinitionId(channelDefinitionId).singleResult(); if (channelDefinition == null) { throw new FlowableObjectNotFoundException("Could not find a channel definition with id '" + channelDefinitionId + "'.", ChannelDefinition.class); } if (restApiInterceptor != null) { restApiInterceptor.accessChannelDefinitionById(channelDefinition); } return channelDefinition; } }
repos\flowable-engine-main\modules\flowable-event-registry-rest\src\main\java\org\flowable\eventregistry\rest\service\api\repository\ChannelDefinitionResourceDataResource.java
2
请在Spring Boot框架中完成以下Java代码
public void saveUser(UserEntity user) { mongoTemplate.save(user); } /** * 根据用户名查询对象 * @param userName * @return */ @Override public UserEntity findUserByUserName(String userName) { Query query=new Query(Criteria.where("userName").is(userName)); UserEntity user = mongoTemplate.findOne(query , UserEntity.class); return user; } /** * 更新对象 * @param user */ @Override public int updateUser(UserEntity user) {
Query query=new Query(Criteria.where("id").is(user.getId())); Update update= new Update().set("userName", user.getUserName()).set("passWord", user.getPassWord()); //更新查询返回结果集的第一条 WriteResult result =mongoTemplate.updateFirst(query,update,UserEntity.class); //更新查询返回结果集的所有 // mongoTemplate.updateMulti(query,update,UserEntity.class); if(result!=null) return result.getN(); else return 0; } /** * 删除对象 * @param id */ @Override public void deleteUserById(Long id) { Query query=new Query(Criteria.where("id").is(id)); mongoTemplate.remove(query,UserEntity.class); } }
repos\spring-boot-leaning-master\1.x\第12课:MongoDB 实战\spring-boot-mongodb-template\src\main\java\com\neo\repository\impl\UserDaoImpl.java
2
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } public String getIcon() { return icon; } public void setIcon(String icon) { this.icon = icon; } public Integer getType() { return type; } public void setType(Integer type) { this.type = type; } public String getUri() { return uri; } public void setUri(String uri) { this.uri = uri; } public Integer getStatus() { return status;
} public void setStatus(Integer status) { this.status = status; } public Date getCreateTime() { return createTime; } public void setCreateTime(Date createTime) { this.createTime = createTime; } public Integer getSort() { return sort; } public void setSort(Integer sort) { this.sort = sort; } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append(getClass().getSimpleName()); sb.append(" ["); sb.append("Hash = ").append(hashCode()); sb.append(", id=").append(id); sb.append(", pid=").append(pid); sb.append(", name=").append(name); sb.append(", value=").append(value); sb.append(", icon=").append(icon); sb.append(", type=").append(type); sb.append(", uri=").append(uri); sb.append(", status=").append(status); sb.append(", createTime=").append(createTime); sb.append(", sort=").append(sort); sb.append(", serialVersionUID=").append(serialVersionUID); sb.append("]"); return sb.toString(); } }
repos\mall-master\mall-mbg\src\main\java\com\macro\mall\model\UmsPermission.java
1
请在Spring Boot框架中完成以下Java代码
class PropertiesWebClientHttpServiceGroupConfigurer implements WebClientHttpServiceGroupConfigurer { private final HttpServiceClientProperties properties; private final HttpClientSettingsPropertyMapper clientSettingsPropertyMapper; private final ClientHttpConnectorBuilder<?> clientConnectorBuilder; PropertiesWebClientHttpServiceGroupConfigurer(@Nullable ClassLoader classLoader, HttpServiceClientProperties properties, @Nullable SslBundles sslBundles, ObjectProvider<ClientHttpConnectorBuilder<?>> clientConnectorBuilder, @Nullable HttpClientSettings httpClientSettings) { this.properties = properties; this.clientSettingsPropertyMapper = new HttpClientSettingsPropertyMapper(sslBundles, httpClientSettings); this.clientConnectorBuilder = clientConnectorBuilder .getIfAvailable(() -> ClientHttpConnectorBuilder.detect(classLoader)); } @Override public int getOrder() { return Ordered.HIGHEST_PRECEDENCE; } @Override public void configureGroups(Groups<WebClient.Builder> groups) { groups.forEachClient(this::configureClient); } private void configureClient(HttpServiceGroup group, WebClient.Builder builder) {
HttpClientProperties clientProperties = this.properties.get(group.name()); HttpClientSettings clientSettings = this.clientSettingsPropertyMapper.map(clientProperties); builder.clientConnector(this.clientConnectorBuilder.build(clientSettings)); if (clientProperties != null) { PropertyMapper map = PropertyMapper.get(); map.from(clientProperties::getBaseUrl).whenHasText().to(builder::baseUrl); map.from(clientProperties::getDefaultHeader).as(this::putAllHeaders).to(builder::defaultHeaders); map.from(clientProperties::getApiversion) .as(ApiversionProperties::getDefaultVersion) .to(builder::defaultApiVersion); map.from(clientProperties::getApiversion) .as(ApiversionProperties::getInsert) .as(PropertiesApiVersionInserter::get) .to(builder::apiVersionInserter); } } private Consumer<HttpHeaders> putAllHeaders(Map<String, List<String>> defaultHeaders) { return (httpHeaders) -> httpHeaders.putAll(defaultHeaders); } }
repos\spring-boot-4.0.1\module\spring-boot-webclient\src\main\java\org\springframework\boot\webclient\autoconfigure\service\PropertiesWebClientHttpServiceGroupConfigurer.java
2
请完成以下Java代码
public @Nullable EndpointHandlerMethod getDltHandlerMethod() { return this.dltHandlerMethod; } public List<DestinationTopic.Properties> getDestinationTopicProperties() { return this.destinationTopicProperties; } @Nullable public Integer getConcurrency() { return this.concurrency; } static class TopicCreation { private final boolean shouldCreateTopics; private final int numPartitions; private final short replicationFactor; TopicCreation(@Nullable Boolean shouldCreate, @Nullable Integer numPartitions, @Nullable Short replicationFactor) { this.shouldCreateTopics = shouldCreate == null || shouldCreate; this.numPartitions = numPartitions == null ? 1 : numPartitions; this.replicationFactor = replicationFactor == null ? -1 : replicationFactor; }
TopicCreation() { this.shouldCreateTopics = true; this.numPartitions = 1; this.replicationFactor = -1; } TopicCreation(boolean shouldCreateTopics) { this.shouldCreateTopics = shouldCreateTopics; this.numPartitions = 1; this.replicationFactor = -1; } public int getNumPartitions() { return this.numPartitions; } public short getReplicationFactor() { return this.replicationFactor; } public boolean shouldCreateTopics() { return this.shouldCreateTopics; } } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\retrytopic\RetryTopicConfiguration.java
1
请完成以下Java代码
private StockAvailabilityResponseItem fromJAXB(final VerfuegbarkeitsantwortArtikel soap) { return StockAvailabilityResponseItem.builder() .pzn(PZN.of(soap.getAnfragePzn())) .qty(Quantity.of(soap.getAnfrageMenge())) .substitution(fromJAXBorNull(soap.getSubstitution())) .parts(soap.getAnteile().stream() .map(this::fromJAXB) .collect(ImmutableList.toImmutableList())) .build(); } private VerfuegbarkeitSubstitution toJAXB(final StockAvailabilitySubstitution substitution) { if (substitution == null) { return null; } final VerfuegbarkeitSubstitution soap = jaxbObjectFactory.createVerfuegbarkeitSubstitution(); soap.setLieferPzn(substitution.getPzn().getValueAsLong()); soap.setGrund(substitution.getReason().getV1SoapCode()); soap.setSubstitutionsgrund(substitution.getType().getV1SoapCode()); return soap; } private StockAvailabilitySubstitution fromJAXBorNull(@Nullable final VerfuegbarkeitSubstitution soap) { if (soap == null) { return null; } return StockAvailabilitySubstitution.builder() .pzn(PZN.of(soap.getLieferPzn())) .reason(StockAvailabilitySubstitutionReason.fromV1SoapCode(soap.getGrund()))
.type(StockAvailabilitySubstitutionType.fromV1SoapCode(soap.getSubstitutionsgrund())) .build(); } private VerfuegbarkeitAnteil toJAXB(final StockAvailabilityResponseItemPart itemPart) { final VerfuegbarkeitAnteil soap = jaxbObjectFactory.createVerfuegbarkeitAnteil(); soap.setMenge(itemPart.getQty().getValueAsInt()); soap.setTyp(itemPart.getType().getV1SoapCode()); soap.setLieferzeitpunkt(itemPart.getDeliveryDate() != null ? JAXBDateUtils.toXMLGregorianCalendar(itemPart.getDeliveryDate()) : null); soap.setTour(itemPart.getTour()); soap.setGrund(itemPart.getReason() != null ? itemPart.getReason().getV1SoapCode() : null); // soap.setTourabweichung(itemPart.isTourDeviation()); return soap; } private StockAvailabilityResponseItemPart fromJAXB(@NonNull final VerfuegbarkeitAnteil soap) { return StockAvailabilityResponseItemPart.builder() .qty(Quantity.of(soap.getMenge())) .type(StockAvailabilityResponseItemPartType.fromV1SoapCode(soap.getTyp())) .deliveryDate(JAXBDateUtils.toZonedDateTime(soap.getLieferzeitpunkt())) .reason(StockAvailabilitySubstitutionReason.fromV1SoapCode(soap.getGrund())) .tour(soap.getTour()) // .tourDeviation(soap.isTourabweichung()) .build(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.vertical.pharma.msv3.commons\src\main\java\de\metas\vertical\pharma\msv3\protocol\stockAvailability\v1\StockAvailabilityJAXBConvertersV1.java
1
请完成以下Java代码
Builder withValue(String key, @Nullable String value) { if (value != null) { this.values.put(key, HtmlUtils.htmlEscape(value)); } return this; } /** * Inject value {@code value} in every {@code {{key}}} placeholder without * HTML-escaping. Useful for injecting "sub-templates". * @param key the placeholder name * @param value the value to inject * @return this instance for further templating */ Builder withRawHtml(String key, String value) { if (!value.isEmpty() && value.charAt(value.length() - 1) == '\n') { value = value.substring(0, value.length() - 1); } this.values.put(key, value); return this; } /** * Render the template. All placeholders MUST have a corresponding value. If a * placeholder does not have a corresponding value, throws * {@link IllegalStateException}. * @return the rendered template */ String render() { String template = this.template; for (String key : this.values.keySet()) {
String pattern = Pattern.quote("{{" + key + "}}"); template = template.replaceAll(pattern, this.values.get(key)); } String unusedPlaceholders = Pattern.compile("\\{\\{([a-zA-Z0-9]+)}}") .matcher(template) .results() .map((result) -> result.group(1)) .collect(Collectors.joining(", ")); if (StringUtils.hasLength(unusedPlaceholders)) { throw new IllegalStateException("Unused placeholders in template: [%s]".formatted(unusedPlaceholders)); } return template; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\ui\HtmlTemplates.java
1
请完成以下Java代码
public void setLanguageISO (String LanguageISO) { set_Value (COLUMNNAME_LanguageISO, LanguageISO); } /** Get ISO Language Code. @return Lower-case two-letter ISO-3166 code - http://www.ics.uci.edu/pub/ietf/http/related/iso639.txt */ public String getLanguageISO () { return (String)get_Value(COLUMNNAME_LanguageISO); } /** 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 Time Pattern. @param TimePattern Java Time Pattern */ public void setTimePattern (String TimePattern) { set_Value (COLUMNNAME_TimePattern, TimePattern); } /** Get Time Pattern. @return Java Time Pattern */ public String getTimePattern () { return (String)get_Value(COLUMNNAME_TimePattern); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_AD_Language.java
1
请完成以下Java代码
private Quantity getQtyToAllocate(@NonNull final List<ShipmentScheduleWithHU> alreadyAllocatedHUs, @NonNull final Quantity qtyToDeliver) { return alreadyAllocatedHUs.stream() .map(ShipmentScheduleWithHU::getQtyPicked) .reduce(qtyToDeliver, Quantity::subtract); } private void aggregateCUsToTUs(@NonNull final Set<ShipmentScheduleId> shipmentScheduleIds) { if (shipmentScheduleIds.isEmpty()) { return; } ShipmentSchedulesCUsToTUsAggregator.builder() .huShipmentScheduleBL(huShipmentScheduleBL) .shipmentScheduleAllocDAO(shipmentScheduleAllocDAO) .handlingUnitsBL(handlingUnitsBL) // .shipmentScheduleIds(shipmentScheduleIds)
// .build().execute(); } @NonNull public Set<InOutLineId> retrieveInOuLineIdByShipScheduleId(@NonNull final ShipmentScheduleAndJobScheduleIdSet scheduleIds) { return shipmentScheduleAllocDAO.retrieveOnShipmentLineRecordsByScheduleIds(scheduleIds) .values() .stream() .map(de.metas.inoutcandidate.model.I_M_ShipmentSchedule_QtyPicked::getM_InOutLine_ID) .map(InOutLineId::ofRepoIdOrNull) .filter(Objects::nonNull) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\shipmentschedule\api\ShipmentScheduleWithHUService.java
1
请在Spring Boot框架中完成以下Java代码
public final class SwingEventNotifierService { public static final transient SwingEventNotifierService instance = new SwingEventNotifierService(); private static final transient Logger logger = LogManager.getLogger(SwingEventNotifierService.class); /** Current notifications UI frame */ private SwingEventNotifierFrame frame = null; public static SwingEventNotifierService getInstance() { return instance; } private SwingEventNotifierService() { super(); try { JMXRegistry.get().registerJMX(new JMXSwingEventNotifierService(), OnJMXAlreadyExistsPolicy.Replace); } catch (Exception e) { logger.warn("Failed registering JMX bean", e); } } public final synchronized boolean isRunning() { return frame != null && !frame.isDisposed(); } /** * Start listening to subscribed topics and display the events. * * If this was already started, this method does nothing. */ public synchronized void start() { if (!EventBusConfig.isEnabled()) { logger.info("Not starting because it's not enabled"); return; } try { if (frame != null && frame.isDisposed()) { frame = null; } if (frame == null) { frame = new SwingEventNotifierFrame(); } } catch (Exception e) { logger.warn("Failed starting the notification frame: " + frame, e);
} } /** * Stop listening events and destroy the whole popup. * * If this was already started, this method does nothing. */ public synchronized void stop() { if (frame == null) { return; } try { frame.dispose(); } catch (Exception e) { logger.warn("Failed disposing the notification frame: " + frame, e); } } public synchronized Set<String> getSubscribedTopicNames() { if (frame != null && !frame.isDisposed()) { return frame.getSubscribedTopicNames(); } else { return ImmutableSet.of(); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\notifications\SwingEventNotifierService.java
2
请完成以下Java代码
public boolean isGeneratedTaxLine() { return parentId != null && taxId != null; } /** * This logic expects, that tax lines always generated from an base account with tax set (included or not) */ public boolean isTaxLine() { return taxId != null && (determineTaxBaseSAP || parentId != null); } public boolean isTaxLineGeneratedForBaseLine(@NonNull final SAPGLJournalLine taxBaseLine) { return isTaxLine() && parentId != null && SAPGLJournalLineId.equals(parentId, taxBaseLine.getIdOrNull()); } public boolean isBaseTaxLine()
{ return parentId == null && taxId != null && !determineTaxBaseSAP; } @NonNull public Optional<SAPGLJournalLine> getReverseChargeCounterPart( @NonNull final SAPGLJournalTaxProvider taxProvider, @NonNull final AcctSchemaId acctSchemaId) { return Optional.ofNullable(taxId) .filter(taxProvider::isReverseCharge) .map(reverseChargeTaxId -> toBuilder() .postingSign(getPostingSign().reverse()) .account(taxProvider.getTaxAccount(reverseChargeTaxId, acctSchemaId, getPostingSign().reverse())) .build()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\gljournal_sap\SAPGLJournalLine.java
1
请完成以下Java代码
public String toString() { return "JwDepartmentTree{" + "children=" + children + "} " + super.toString(); } /** * 静态辅助方法,将list转为tree结构 */ public static List<JdtDepartmentTreeVo> listToTree(List<Department> allDepartment) { // 先找出所有的父级 List<JdtDepartmentTreeVo> treeList = getByParentId(1, allDepartment); Optional<Department> departmentOptional = allDepartment.stream().filter(item -> item.getParent_id() == null).findAny(); Department department = new Department(); //判断是否找到数据 if(departmentOptional.isPresent()){ department = departmentOptional.get(); } getChildrenRecursion(treeList, allDepartment); // 代码逻辑说明: 【issues/6017】钉钉同步部门时没有最顶层的部门名,同步用户时,用户没有部门信息--- JdtDepartmentTreeVo treeVo = new JdtDepartmentTreeVo(department); treeVo.setChildren(treeList); List<JdtDepartmentTreeVo> list = new ArrayList<>(); list.add(treeVo); return list; } private static List<JdtDepartmentTreeVo> getByParentId(Integer parentId, List<Department> allDepartment) { List<JdtDepartmentTreeVo> list = new ArrayList<>(); for (Department department : allDepartment) { if (parentId.equals(department.getParent_id())) {
list.add(new JdtDepartmentTreeVo(department)); } } return list; } private static void getChildrenRecursion(List<JdtDepartmentTreeVo> treeList, List<Department> allDepartment) { for (JdtDepartmentTreeVo departmentTree : treeList) { // 递归寻找子级 List<JdtDepartmentTreeVo> children = getByParentId(departmentTree.getDept_id(), allDepartment); if (children.size() > 0) { departmentTree.setChildren(children); getChildrenRecursion(children, allDepartment); } } } }
repos\JeecgBoot-main\jeecg-boot\jeecg-module-system\jeecg-system-biz\src\main\java\org\jeecg\modules\system\vo\thirdapp\JdtDepartmentTreeVo.java
1
请完成以下Java代码
public class SUMUP_Config_DeleteCardReader extends JavaProcess implements IProcessPrecondition { @NonNull private final SumUpService sumUpService = SpringContextHolder.instance.getBean(SumUpService.class); @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final @NonNull IProcessPreconditionsContext context) { if (context.getSelectedIncludedRecords().isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection().toInternal(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt()
{ final SumUpConfigId configId = SumUpConfigId.ofRepoId(getRecord_ID()); final Set<SumUpCardReaderExternalId> ids = getCardReaderExternalIds(); sumUpService.deleteCardReaders(configId, ids); return MSG_OK; } private Set<SumUpCardReaderExternalId> getCardReaderExternalIds() { return getSelectedIncludedRecords(I_SUMUP_CardReader.class) .stream() .map(record -> SumUpCardReaderExternalId.ofString(record.getExternalId())) .collect(ImmutableSet.toImmutableSet()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.payment.sumup.webui\src\main\java\de\metas\payment\sumup\webui\process\SUMUP_Config_DeleteCardReader.java
1
请完成以下Java代码
public int getRetryWaitTimeInMillis() { return retryWaitTimeInMillis; } public void setRetryWaitTimeInMillis(int retryWaitTimeInMillis) { this.retryWaitTimeInMillis = retryWaitTimeInMillis; } public int getResetExpiredJobsInterval() { return resetExpiredJobsInterval; } public void setResetExpiredJobsInterval(int resetExpiredJobsInterval) { this.resetExpiredJobsInterval = resetExpiredJobsInterval; }
public int getResetExpiredJobsPageSize() { return resetExpiredJobsPageSize; } public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) { this.resetExpiredJobsPageSize = resetExpiredJobsPageSize; } public ExecuteAsyncRunnableFactory getExecuteAsyncRunnableFactory() { return executeAsyncRunnableFactory; } public void setExecuteAsyncRunnableFactory(ExecuteAsyncRunnableFactory executeAsyncRunnableFactory) { this.executeAsyncRunnableFactory = executeAsyncRunnableFactory; } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\DefaultAsyncJobExecutor.java
1
请完成以下Java代码
public class JAXBHelper { private static void print(String xmlContent) { System.out.println(xmlContent); } private static Unmarshaller getContextUnmarshaller(Class clazz) { Unmarshaller unmarshaller = null; try { JAXBContext context = JAXBContext.newInstance(clazz); unmarshaller = context.createUnmarshaller(); } catch (Exception ex) { System.out.println(EXCEPTION_ENCOUNTERED + ex); } return unmarshaller; } private static Marshaller getContextMarshaller(Class clazz) { Marshaller marshaller = null; try { JAXBContext context = JAXBContext.newInstance(clazz); marshaller = context.createMarshaller(); marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); marshaller.setProperty("jaxb.fragment", Boolean.TRUE); } catch (Exception ex) { System.out.println(EXCEPTION_ENCOUNTERED + ex); } return marshaller; } public static void example() { try { XMLExample xml = (XMLExample) JAXBHelper.getContextUnmarshaller(XMLExample.class).unmarshal(new File(XML_FILE_IN)); JAXBHelper.print(xml.toString()); ExampleHTML html = new ExampleHTML(); Body body = new Body();
CustomElement customElement = new CustomElement(); NestedElement nested = new NestedElement(); CustomElement child = new CustomElement(); customElement.setValue("descendantOne: " + xml.getAncestor().getDescendantOne().getValue()); child.setValue("descendantThree: " + xml.getAncestor().getDescendantTwo().getDescendantThree().getValue()); nested.setCustomElement(child); body.setCustomElement(customElement); body.setNestedElement(nested); Meta meta = new Meta(); meta.setTitle("example"); html.getHead().add(meta); html.setBody(body); JAXBHelper.getContextMarshaller(ExampleHTML.class).marshal(html, new File(JAXB_FILE_OUT)); } catch (Exception ex) { System.out.println(EXCEPTION_ENCOUNTERED + ex); } } }
repos\tutorials-master\xml-modules\xml-2\src\main\java\com\baeldung\xmlhtml\helpers\jaxb\JAXBHelper.java
1