instruction
string
input
string
output
string
source_file
string
priority
int64
请完成以下Java代码
public VariableMap execute(CommandContext commandContext) { final TaskManager taskManager = commandContext.getTaskManager(); TaskEntity task = taskManager.findTaskById(resourceId); ensureNotNull(BadUserRequestException.class, "Cannot find task with id '" + resourceId + "'.", "task", task); checkGetTaskFormVariables(task, commandContext); VariableMapImpl result = new VariableMapImpl(); // first, evaluate form fields TaskDefinition taskDefinition = task.getTaskDefinition(); if (taskDefinition != null) { TaskFormData taskFormData = taskDefinition.getTaskFormHandler().createTaskForm(task); for (FormField formField : taskFormData.getFormFields()) { if(formVariableNames == null || formVariableNames.contains(formField.getId())) {
result.put(formField.getId(), createVariable(formField, task)); } } } // collect remaining variables from task scope and parent scopes task.collectVariables(result, formVariableNames, false, deserializeObjectValues); return result; } protected void checkGetTaskFormVariables(TaskEntity task, CommandContext commandContext) { for(CommandChecker checker : commandContext.getProcessEngineConfiguration().getCommandCheckers()) { checker.checkReadTaskVariable(task); } } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cmd\GetTaskFormVariablesCmd.java
1
请完成以下Java代码
public class AstLambdaInvocation extends AstRightValue { private final AstNode lambdaNode; private final AstParameters params; public AstLambdaInvocation(AstNode lambdaNode, AstParameters params) { this.lambdaNode = lambdaNode; this.params = params; } @Override public void appendStructure(StringBuilder builder, Bindings bindings) { lambdaNode.appendStructure(builder, bindings); params.appendStructure(builder, bindings); } @Override public Object eval(Bindings bindings, ELContext context) { // Evaluate the lambda expression Object lambdaObj = lambdaNode.eval(bindings, context); if (!(lambdaObj instanceof LambdaExpression)) { throw new ELException("Expected LambdaExpression but got: " + (lambdaObj == null ? "null" : lambdaObj.getClass().getName())); } LambdaExpression lambda = (LambdaExpression) lambdaObj; // Evaluate the arguments Object[] args = params.eval(bindings, context); // Invoke the lambda Object result = lambda.invoke(context, args); return result; }
@Override public int getCardinality() { return 2; } @Override public AstNode getChild(int i) { return i == 0 ? lambdaNode : i == 1 ? params : null; } @Override public String toString() { return lambdaNode.toString() + params.toString(); } }
repos\flowable-engine-main\modules\flowable-engine-common\src\main\java\org\flowable\common\engine\impl\de\odysseus\el\tree\impl\ast\AstLambdaInvocation.java
1
请完成以下Java代码
public String getCallbackId() { return callbackId; } public Set<String> getCallbackIds() { return callbackIds; } public String getCallbackType() { return callbackType; } public String getParentCaseInstanceId() { return parentCaseInstanceId; } public String getReferenceId() { return referenceId; } public String getReferenceType() { return referenceType; } public List<ProcessInstanceQueryImpl> getOrQueryObjects() { return orQueryObjects; } /** * Methods needed for ibatis because of re-use of query-xml for executions. ExecutionQuery contains a parentId property. */ public String getParentId() { return null; } public boolean isOnlyChildExecutions() { return onlyChildExecutions; } public boolean isOnlyProcessInstanceExecutions() { return onlyProcessInstanceExecutions; } public boolean isOnlySubProcessExecutions() { return onlySubProcessExecutions; } public Date getStartedBefore() { return startedBefore; } public void setStartedBefore(Date startedBefore) { this.startedBefore = startedBefore; }
public Date getStartedAfter() { return startedAfter; } public void setStartedAfter(Date startedAfter) { this.startedAfter = startedAfter; } public String getStartedBy() { return startedBy; } public void setStartedBy(String startedBy) { this.startedBy = startedBy; } public boolean isWithJobException() { return withJobException; } public String getLocale() { return locale; } public boolean isNeedsProcessDefinitionOuterJoin() { if (isNeedsPaging()) { if (AbstractEngineConfiguration.DATABASE_TYPE_ORACLE.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_DB2.equals(databaseType) || AbstractEngineConfiguration.DATABASE_TYPE_MSSQL.equals(databaseType)) { // When using oracle, db2 or mssql we don't need outer join for the process definition join. // It is not needed because the outer join order by is done by the row number instead return false; } } return hasOrderByForColumn(ProcessInstanceQueryProperty.PROCESS_DEFINITION_KEY.getName()); } public List<List<String>> getSafeProcessInstanceIds() { return safeProcessInstanceIds; } public void setSafeProcessInstanceIds(List<List<String>> safeProcessInstanceIds) { this.safeProcessInstanceIds = safeProcessInstanceIds; } public List<List<String>> getSafeInvolvedGroups() { return safeInvolvedGroups; } public void setSafeInvolvedGroups(List<List<String>> safeInvolvedGroups) { this.safeInvolvedGroups = safeInvolvedGroups; } }
repos\flowable-engine-main\modules\flowable-engine\src\main\java\org\flowable\engine\impl\ProcessInstanceQueryImpl.java
1
请完成以下Java代码
public class UserServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { processRequest(request, response); forwardRequest(request, response, "/WEB-INF/jsp/result.jsp"); } @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("name", getRequestParameter(request, "name")); request.setAttribute("email", getRequestParameter(request, "email")); request.setAttribute("province", getContextParameter("province")); request.setAttribute("country", getContextParameter("country")); }
protected String getRequestParameter(HttpServletRequest request, String name) { String param = request.getParameter(name); return !param.isEmpty() ? param : getInitParameter(name); } protected String getContextParameter(String name) { return getServletContext().getInitParameter(name); } protected void forwardRequest(HttpServletRequest request, HttpServletResponse response, String path) throws ServletException, IOException { request.getRequestDispatcher(path).forward(request, response); } }
repos\tutorials-master\web-modules\jakarta-servlets-2\src\main\java\com\baeldung\UserServlet.java
1
请完成以下Java代码
public double getWidth() { return width; } // getWidth /** * Get Height * @return height */ public double getHeight() { return height; } // getHeight /*************************************************************************/ /** * Hash Code * @return hash code */ public int hashCode() { long bits = Double.doubleToLongBits(width); bits ^= Double.doubleToLongBits(height) * 31; return (((int) bits) ^ ((int) (bits >> 32))); } // hashCode /** * Equals * @param obj object * @return true if w/h is same */ public boolean equals (Object obj) { if (obj != null && obj instanceof Dimension2D) {
Dimension2D d = (Dimension2D)obj; if (d.getWidth() == width && d.getHeight() == height) return true; } return false; } // equals /** * String Representation * @return info */ public String toString() { StringBuffer sb = new StringBuffer(); sb.append("Dimension2D[w=").append(width).append(",h=").append(height).append("]"); return sb.toString(); } // toString } // Dimension2DImpl
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\print\layout\Dimension2DImpl.java
1
请完成以下Java代码
public void setMaxAmt (BigDecimal MaxAmt) { set_Value (COLUMNNAME_MaxAmt, MaxAmt); } /** Get Max Amount. @return Maximum Amount in invoice currency */ public BigDecimal getMaxAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MaxAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Min Amount. @param MinAmt Minimum Amount in invoice currency */ public void setMinAmt (BigDecimal MinAmt) { set_Value (COLUMNNAME_MinAmt, MinAmt); } /** Get Min Amount. @return Minimum Amount in invoice currency */ public BigDecimal getMinAmt () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_MinAmt); if (bd == null) return Env.ZERO; return bd; } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Percent. @param Percent Percentage */ public void setPercent (BigDecimal Percent) { set_Value (COLUMNNAME_Percent, Percent); } /** Get Percent. @return Percentage */ public BigDecimal getPercent () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Percent);
if (bd == null) return Env.ZERO; return bd; } /** Set Threshold max. @param ThresholdMax Maximum gross amount for withholding calculation (0=no limit) */ public void setThresholdMax (BigDecimal ThresholdMax) { set_Value (COLUMNNAME_ThresholdMax, ThresholdMax); } /** Get Threshold max. @return Maximum gross amount for withholding calculation (0=no limit) */ public BigDecimal getThresholdMax () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_ThresholdMax); if (bd == null) return Env.ZERO; return bd; } /** Set Threshold min. @param Thresholdmin Minimum gross amount for withholding calculation */ public void setThresholdmin (BigDecimal Thresholdmin) { set_Value (COLUMNNAME_Thresholdmin, Thresholdmin); } /** Get Threshold min. @return Minimum gross amount for withholding calculation */ public BigDecimal getThresholdmin () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Thresholdmin); if (bd == null) return Env.ZERO; return bd; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_C_Withholding.java
1
请完成以下Java代码
public class TimeseriesDeleteRequest implements CalculatedFieldSystemAwareRequest { private final TenantId tenantId; private final EntityId entityId; private final List<String> keys; private final List<DeleteTsKvQuery> deleteHistoryQueries; private final List<CalculatedFieldId> previousCalculatedFieldIds; private final UUID tbMsgId; private final TbMsgType tbMsgType; private final FutureCallback<List<String>> callback; public static Builder builder() { return new Builder(); } public static class Builder { private TenantId tenantId; private EntityId entityId; private List<String> keys; private List<DeleteTsKvQuery> deleteHistoryQueries; private List<CalculatedFieldId> previousCalculatedFieldIds; private UUID tbMsgId; private TbMsgType tbMsgType; private FutureCallback<List<String>> callback; Builder() {} public Builder tenantId(TenantId tenantId) { this.tenantId = tenantId; return this; } public Builder entityId(EntityId entityId) { this.entityId = entityId; return this; } public Builder keys(List<String> keys) { this.keys = keys; return this; } public Builder deleteHistoryQueries(List<DeleteTsKvQuery> deleteHistoryQueries) { this.deleteHistoryQueries = deleteHistoryQueries; return this; } public Builder previousCalculatedFieldIds(List<CalculatedFieldId> previousCalculatedFieldIds) {
this.previousCalculatedFieldIds = previousCalculatedFieldIds; return this; } public Builder tbMsgId(UUID tbMsgId) { this.tbMsgId = tbMsgId; return this; } public Builder tbMsgType(TbMsgType tbMsgType) { this.tbMsgType = tbMsgType; return this; } public Builder callback(FutureCallback<List<String>> callback) { this.callback = callback; return this; } public TimeseriesDeleteRequest build() { return new TimeseriesDeleteRequest(tenantId, entityId, keys, deleteHistoryQueries, previousCalculatedFieldIds, tbMsgId, tbMsgType, callback); } } }
repos\thingsboard-master\rule-engine\rule-engine-api\src\main\java\org\thingsboard\rule\engine\api\TimeseriesDeleteRequest.java
1
请完成以下Java代码
private final IQuery<I_M_Material_Tracking_Ref> createMaterialTrackingRefQueryForModels(final List<?> models) { final IQueryBuilder<I_M_Material_Tracking_Ref> queryBuilder = createMaterialTrackingRefQueryBuilderForModels(models); if (queryBuilder == null) { return null; } return queryBuilder.create(); } public final IQueryBuilder<I_M_Material_Tracking_Ref> createMaterialTrackingRefQueryBuilderForModels(final List<?> models) { if (models == null || models.isEmpty()) { return null; } final IQueryBL queryBL = Services.get(IQueryBL.class); // // Iterate models and build model filters final ICompositeQueryFilter<I_M_Material_Tracking_Ref> modelFilters = queryBL.createCompositeQueryFilter(I_M_Material_Tracking_Ref.class) .setJoinOr(); for (final Object model : models) { if (model == null) { continue; } final int adTableId = InterfaceWrapperHelper.getModelTableId(model); final int recordId = InterfaceWrapperHelper.getId(model); final ICompositeQueryFilter<I_M_Material_Tracking_Ref> filter = queryBL .createCompositeQueryFilter(I_M_Material_Tracking_Ref.class) .addEqualsFilter(I_M_Material_Tracking_Ref.COLUMNNAME_AD_Table_ID, adTableId) .addEqualsFilter(I_M_Material_Tracking_Ref.COLUMNNAME_Record_ID, recordId); modelFilters.addFilter(filter); }
// No models provided if (modelFilters.isEmpty()) { return null; } // // Create M_Material_Tracking_Ref query final IQueryBuilder<I_M_Material_Tracking_Ref> materialTrackingRefQueryBuilder = queryBL .createQueryBuilder(I_M_Material_Tracking_Ref.class, getCtx(), getTrxName()) .filter(modelFilters); return materialTrackingRefQueryBuilder; } public final <T> IQueryBuilder<I_M_Material_Tracking_Ref> createMaterialTrackingRefQueryBuilderForModels(final IQueryBuilder<T> modelsQuery) { final IQueryBL queryBL = Services.get(IQueryBL.class); final Class<T> modelClass = modelsQuery.getModelClass(); final int modelTableId = InterfaceWrapperHelper.getTableId(modelClass); final String modelKeyColumnName = InterfaceWrapperHelper.getKeyColumnName(modelClass); // // Create M_Material_Tracking_Ref query final IQueryBuilder<I_M_Material_Tracking_Ref> materialTrackingRefQueryBuilder = queryBL .createQueryBuilder(I_M_Material_Tracking_Ref.class, getCtx(), getTrxName()) .addEqualsFilter(I_M_Material_Tracking_Ref.COLUMNNAME_AD_Table_ID, modelTableId) .addInSubQueryFilter(I_M_Material_Tracking_Ref.COLUMNNAME_Record_ID, modelKeyColumnName, modelsQuery.create()); return materialTrackingRefQueryBuilder; } public final IQueryBuilder<I_M_Material_Tracking_Ref> createMaterialTrackingRefQueryBuilderForModel(final Object model) { final List<Object> models = Collections.singletonList(model); return createMaterialTrackingRefQueryBuilderForModels(models); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.materialtracking\src\main\java\de\metas\materialtracking\impl\MaterialTrackingQueryCompiler.java
1
请在Spring Boot框架中完成以下Java代码
public String getEmail() { return email; } /** * Sets the value of the email property. * * @param value * allowed object is * {@link String } * */ public void setEmail(String value) { this.email = value; } /** * Gets the value of the comment property. * * @return * possible object is * {@link String } * */ public String getComment() { return comment; } /** * Sets the value of the comment property. * * @param value * allowed object is * {@link String } * */ public void setComment(String value) {
this.comment = value; } /** * Gets the value of the iaccount property. * * @return * possible object is * {@link String } * */ public String getIaccount() { return iaccount; } /** * Sets the value of the iaccount property. * * @param value * allowed object is * {@link String } * */ public void setIaccount(String value) { this.iaccount = value; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.shipper.gateway.dpd\src\main\java-xjc\com\dpd\common\service\types\shipmentservice\_3\Address.java
2
请在Spring Boot框架中完成以下Java代码
public class Workplace { @NonNull WorkplaceId id; @NonNull String name; @NonNull WarehouseId warehouseId; @Nullable LocatorId pickFromLocatorId; @Nullable PickingSlotId pickingSlotId; @NonNull SeqNo seqNo; @Nullable PriorityRule priorityRule; @Nullable OrderPickingType orderPickingType; int maxPickingJobs; @NonNull ImmutableSet<ProductId> productIds; @NonNull ImmutableSet<ProductCategoryId> productCategoryIds; @NonNull ImmutableSet<CarrierProductId> carrierProductIds; @NonNull ImmutableSet<ExternalSystemId> externalSystemIds; @Builder private Workplace( @NonNull final WorkplaceId id, @NonNull final String name, @NonNull final WarehouseId warehouseId, @Nullable final LocatorId pickFromLocatorId, @Nullable final PickingSlotId pickingSlotId, @NonNull final SeqNo seqNo, @Nullable final PriorityRule priorityRule, @Nullable final OrderPickingType orderPickingType, final int maxPickingJobs,
@Nullable final ImmutableSet<ProductId> productIds, @Nullable final ImmutableSet<ProductCategoryId> productCategoryIds, @Nullable final ImmutableSet<CarrierProductId> carrierProductIds, @Nullable final ImmutableSet<ExternalSystemId> externalSystemIds) { if (pickFromLocatorId != null) { pickFromLocatorId.assetWarehouseId(warehouseId); } this.id = id; this.name = name; this.warehouseId = warehouseId; this.pickFromLocatorId = pickFromLocatorId; this.pickingSlotId = pickingSlotId; this.seqNo = seqNo; this.priorityRule = priorityRule; this.orderPickingType = orderPickingType; this.maxPickingJobs = maxPickingJobs; this.productIds = productIds != null ? productIds : ImmutableSet.of(); this.productCategoryIds = productCategoryIds != null ? productCategoryIds : ImmutableSet.of(); this.carrierProductIds = carrierProductIds != null ? carrierProductIds : ImmutableSet.of(); this.externalSystemIds = externalSystemIds != null ? externalSystemIds : ImmutableSet.of(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\workplace\Workplace.java
2
请在Spring Boot框架中完成以下Java代码
private HttpSession getCurrentHttpSessionOrNull() { final ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes(); if (servletRequestAttributes == null) { return null; } return servletRequestAttributes.getRequest().getSession(); } private LanguageData getLanguageData(@Nullable final LanguageKey language) { final LanguageKey languageEffective = language != null ? language : LanguageKey.getDefault(); return cache.computeIfAbsent(languageEffective, LanguageData::new); } public ImmutableMap<String, String> getMessagesMap(@NonNull final LanguageKey language) { return getLanguageData(language).getFrontendMessagesMap(); } private static class LanguageData { @Getter private final ResourceBundle resourceBundle; @Getter private final ImmutableMap<String, String> frontendMessagesMap; private LanguageData(final @NonNull LanguageKey language) { resourceBundle = ResourceBundle.getBundle("messages", language.toLocale()); frontendMessagesMap = computeMessagesMap(resourceBundle); }
private static ImmutableMap<String, String> computeMessagesMap(@NonNull final ResourceBundle bundle) { final Set<String> keys = bundle.keySet(); final HashMap<String, String> map = new HashMap<>(keys.size()); for (final String key : keys) { // shall not happen if (key == null || key.isBlank()) { continue; } final String value = Strings.nullToEmpty(bundle.getString(key)); map.put(key, value); } return ImmutableMap.copyOf(map); } } }
repos\metasfresh-new_dawn_uat\misc\services\procurement-webui\procurement-webui-backend\src\main\java\de\metas\procurement\webui\service\I18N.java
2
请完成以下Java代码
public void setModel(final ISideActionsGroupsListModel model) { if (this.model == model) { return; } if (this.model != null) { model.getGroups().removeListDataListener(groupsListModelListener); } this.model = model; renderAll(); if (this.model != null) { model.getGroups().addListDataListener(groupsListModelListener); } } private void renderAll() { final ListModel<ISideActionsGroupModel> groups = model.getGroups(); for (int i = 0; i < groups.getSize(); i++) { final ISideActionsGroupModel group = groups.getElementAt(i); final SideActionsGroupPanel groupComp = createGroupComponent(group); contentPanel.add(groupComp); } refreshUI(); } private final SideActionsGroupPanel createGroupComponent(final ISideActionsGroupModel group) { final SideActionsGroupPanel groupComp = new SideActionsGroupPanel(); groupComp.setModel(group); groupComp.addPropertyChangeListener(SideActionsGroupPanel.PROPERTY_Visible, groupPanelChangedListener); return groupComp;
} private void destroyGroupComponent(final SideActionsGroupPanel groupComp) { groupComp.removePropertyChangeListener(SideActionsGroupPanel.PROPERTY_Visible, groupPanelChangedListener); } protected void refreshUI() { autoHideIfNeeded(); contentPanel.revalidate(); } /** * Auto-hide if no groups or groups are not visible */ private final void autoHideIfNeeded() { boolean haveVisibleGroups = false; for (Component groupComp : contentPanel.getComponents()) { if (groupComp.isVisible()) { haveVisibleGroups = true; break; } } setVisible(haveVisibleGroups); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java\org\adempiere\ui\sideactions\swing\SideActionsGroupsListPanel.java
1
请在Spring Boot框架中完成以下Java代码
public class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } // Optional-based API public Optional<User> findUserByUsername(String username) { return userRepository.findByUsername(username); } public Optional<User> findUserByEmail(String email) { return userRepository.findByEmail(email); } // Business-level exception handling
public User findUserByUsernameOrThrow(String username) { return userRepository.findByUsername(username) .orElseThrow(() -> new UserNotFoundException("User not found: " + username)); } public User findUserByEmailOrThrow(String email) { return userRepository.findByEmail(email) .orElseThrow(() -> new UserNotFoundException("User not found: " + email)); } public List<User> getAllUsers() { return userRepository.findAll(); } }
repos\tutorials-master\persistence-modules\spring-boot-persistence-5\src\main\java\com\baeldung\exception\service\UserService.java
2
请在Spring Boot框架中完成以下Java代码
public static Optional<DocOutboundConfigId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } @JsonCreator public static DocOutboundConfigId ofObject(@NonNull final Object object) { return RepoIdAwares.ofObject(object, DocOutboundConfigId.class, DocOutboundConfigId::ofRepoId); } public static int toRepoId(@Nullable final DocOutboundConfigId docOutboundConfigId) { return toRepoIdOr(docOutboundConfigId, -1); } public static int toRepoIdOr(@Nullable final DocOutboundConfigId docOutboundConfigId, final int defaultValue) { return docOutboundConfigId != null ? docOutboundConfigId.getRepoId() : defaultValue; } private DocOutboundConfigId(final int repoId)
{ this.repoId = Check.assumeGreaterThanZero(repoId, "C_Doc_Outbound_Config_ID"); } @JsonValue public int toJson() { return getRepoId(); } public static boolean equals(@Nullable final DocOutboundConfigId o1, @Nullable final DocOutboundConfigId o2) { return Objects.equals(o1, o2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.document.archive\de.metas.document.archive.base\src\main\java\de\metas\document\archive\config\DocOutboundConfigId.java
2
请完成以下Java代码
public class AD_User_ChangeMyPassword extends JavaProcess implements IProcessPrecondition { private final IUserBL usersService = Services.get(IUserBL.class); @Param(parameterName = "OldPassword", mandatory = false) private String oldPassword; @Param(parameterName = "NewPassword", mandatory = true) private String newPassword; @Param(parameterName = "NewPasswordRetype", mandatory = true) private String newPasswordRetype; @Override public ProcessPreconditionsResolution checkPreconditionsApplicable(final IProcessPreconditionsContext context) { if (!context.isSingleSelection()) { return ProcessPreconditionsResolution.rejectBecauseNotSingleSelection(); } if (!I_AD_User.Table_Name.equals(context.getTableName())) { return ProcessPreconditionsResolution.rejectWithInternalReason("not running on AD_User table"); } // Make sure it's the current logged in user final int adUserId = context.getSingleSelectedRecordId(); if (adUserId != Env.getAD_User_ID(Env.getCtx())) { return ProcessPreconditionsResolution.rejectWithInternalReason("not current logged in user"); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { if (!I_AD_User.Table_Name.equals(getTableName()))
{ throw new AdempiereException("Call it from User window"); } // // Get the AD_User_ID and make sure it's the currently logged on. final Properties ctx = getCtx(); // logged in context final UserId adUserId = UserId.ofRepoId(getRecord_ID()); final UserId loggedUserId = Env.getLoggedUserId(ctx); if (!UserId.equals(adUserId, loggedUserId)) { throw new AdempiereException("Changing password for other user is not allowed"); } // // Actually change it's password usersService.changePassword(ChangeUserPasswordRequest.builder() .userId(adUserId) .oldPassword(HashableString.ofPlainValue(oldPassword)) .newPassword(newPassword) .newPasswordRetype(newPasswordRetype) // .contextClientId(Env.getClientId(ctx)) .contextUserId(loggedUserId) .contextDate(Env.getLocalDate(ctx)) // .build()); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\user\process\AD_User_ChangeMyPassword.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public Integer getAge() { return age; } public void setAge(Integer age) { this.age = age; } public Date getBirthDate() {
return birthDate; } public void setBirthDate(Date birthDate) { this.birthDate = birthDate; } public Gender getGender() { return gender; } public void setGender(Gender gender) { this.gender = gender; } }
repos\tutorials-master\persistence-modules\java-jpa\src\main\java\com\baeldung\jpa\entity\Student.java
1
请完成以下Java代码
public HttpServletRequest getHttpServletRequest() { final RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes(); if (requestAttributes == null) { return null; } if (!(requestAttributes instanceof ServletRequestAttributes)) { return null; } return ((ServletRequestAttributes)requestAttributes).getRequest(); } public JsonAttributeSetInstance extractJsonAttributeSetInstance( @NonNull final ImmutableAttributeSet attributeSet, @NonNull final OrgId orgId) { final IOrgDAO orgDAO = Services.get(IOrgDAO.class); final JsonAttributeSetInstance.JsonAttributeSetInstanceBuilder jsonAttributeSetInstance = JsonAttributeSetInstance.builder(); for (final AttributeId attributeId : attributeSet.getAttributeIds()) { final AttributeCode attributeCode = attributeSet.getAttributeCode(attributeId); final JsonAttributeInstance.JsonAttributeInstanceBuilder instanceBuilder = JsonAttributeInstance.builder() .attributeCode(attributeCode.getCode()); final String attributeValueType = attributeSet.getAttributeValueType(attributeId); if (X_M_Attribute.ATTRIBUTEVALUETYPE_Date.equals(attributeValueType)) { final Date valueAsDate = attributeSet.getValueAsDate(attributeCode); if (valueAsDate != null) { final ZoneId timeZone = orgDAO.getTimeZone(orgId); final LocalDate localDate = valueAsDate.toInstant().atZone(timeZone).toLocalDate(); instanceBuilder.valueDate(localDate); }
} else if (X_M_Attribute.ATTRIBUTEVALUETYPE_StringMax40.equals(attributeValueType)) { instanceBuilder.valueStr(attributeSet.getValueAsString(attributeCode)); } else if (X_M_Attribute.ATTRIBUTEVALUETYPE_List.equals(attributeValueType)) { instanceBuilder.valueStr(attributeSet.getValueAsString(attributeCode)); } else if (X_M_Attribute.ATTRIBUTEVALUETYPE_Number.equals(attributeValueType)) { instanceBuilder.valueNumber(attributeSet.getValueAsBigDecimal(attributeCode)); } jsonAttributeSetInstance.attributeInstance(instanceBuilder.build()); } return jsonAttributeSetInstance.build(); } @NonNull public Quantity getQuantity(final JsonPurchaseCandidateCreateItem request) { final IUOMDAO uomDAO = Services.get(IUOMDAO.class); final JsonQuantity jsonQuantity = request.getQty(); final String uomCode = jsonQuantity.getUomCode(); final Optional<I_C_UOM> uom = uomDAO.getByX12DE355IfExists(X12DE355.ofCode(uomCode)); if (!uom.isPresent()) { throw MissingResourceException.builder().resourceIdentifier("quantity.uomCode").resourceIdentifier(uomCode).build(); } return Quantity.of(jsonQuantity.getQty(), uom.get()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business.rest-api-impl\src\main\java\de\metas\rest_api\utils\RestApiUtilsV2.java
1
请完成以下Java代码
class POJOModelInternalAccessor implements IModelInternalAccessor { private final POJOWrapper pojoWrapper; POJOModelInternalAccessor(final POJOWrapper pojoWrapper) { super(); this.pojoWrapper = pojoWrapper; } @Override public Set<String> getColumnNames() { return pojoWrapper.getColumnNames(); } @Override public int getColumnIndex(final String propertyName) { // TODO Auto-generated method stub throw new UnsupportedOperationException("POJOWrapper has no supported for column indexes"); } @Override public boolean isVirtualColumn(final String columnName) { return pojoWrapper.isCalculated(columnName); } @Override public Object getValue(final String propertyName, final int idx, final Class<?> returnType) { return getValue(propertyName, returnType); } @Override public Object getValue(final String propertyName, final Class<?> returnType) { return pojoWrapper.getValue(propertyName, returnType); } @Override public boolean setValue(final String propertyName, final Object value) { pojoWrapper.setValue(propertyName, value); return true; } @Override public boolean setValueNoCheck(String columnName, Object value) { pojoWrapper.setValue(columnName, value); return true; } @Override public Object getReferencedObject(final String propertyName, final Method interfaceMethod) throws Exception { return pojoWrapper.getReferencedObject(propertyName, interfaceMethod); } @Override public void setValueFromPO(final String idPropertyName, final Class<?> parameterType, final Object value) {
final String propertyName; if (idPropertyName.endsWith("_ID")) { propertyName = idPropertyName.substring(0, idPropertyName.length() - 3); } else { throw new AdempiereException("Invalid idPropertyName: " + idPropertyName); } pojoWrapper.setReferencedObject(propertyName, value); } @Override public boolean invokeEquals(final Object[] methodArgs) { return pojoWrapper.invokeEquals(methodArgs); } @Override public Object invokeParent(final Method method, final Object[] methodArgs) throws Exception { throw new IllegalStateException("Invoking parent method is not supported"); } @Override public boolean isKeyColumnName(final String columnName) { return pojoWrapper.isKeyColumnName(columnName); } @Override public boolean isCalculated(final String columnName) { return pojoWrapper.isCalculated(columnName); } @Override public boolean hasColumnName(String columnName) { return pojoWrapper.hasColumnName(columnName); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\ad\wrapper\POJOModelInternalAccessor.java
1
请完成以下Java代码
protected final Stream<HuId> streamSelectedHUIds(@NonNull final Select select) { return streamSelectedHUIds(HUEditorRowFilter.select(select)); } protected final Stream<HuId> streamSelectedHUIds(@NonNull final HUEditorRowFilter filter) { return streamSelectedRows(filter) .map(HUEditorRow::getHuId) .filter(Objects::nonNull); } /** * Gets <b>all</b> selected {@link HUEditorRow}s and loads the top level-HUs from those. * I.e. this method does not rely on {@link HUEditorRow#isTopLevel()}, but checks the underlying HU. */ protected final Stream<I_M_HU> streamSelectedHUs(@NonNull final Select select) { return streamSelectedHUs(HUEditorRowFilter.select(select)); } protected final Stream<I_M_HU> streamSelectedHUs(@NonNull final HUEditorRowFilter filter)
{ final Stream<HuId> huIds = streamSelectedHUIds(filter); return StreamUtils .dice(huIds, 100) .flatMap(huIdsChunk -> handlingUnitsRepo.getByIds(huIdsChunk).stream()); } protected final void addHUIdsAndInvalidateView(Collection<HuId> huIds) { if (huIds.isEmpty()) { return; } getView().addHUIdsAndInvalidate(huIds); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\handlingunits\HUEditorProcessTemplate.java
1
请完成以下Java代码
public class JsonUtils { private static final Pattern BASE64_PATTERN = Pattern.compile("^[A-Za-z0-9+/]+={0,2}$"); public static JsonObject getJsonObject(List<KeyValueProto> tsKv) { JsonObject json = new JsonObject(); for (KeyValueProto kv : tsKv) { switch (kv.getType()) { case BOOLEAN_V: json.addProperty(kv.getKey(), kv.getBoolV()); break; case LONG_V: json.addProperty(kv.getKey(), kv.getLongV()); break; case DOUBLE_V: json.addProperty(kv.getKey(), kv.getDoubleV()); break; case STRING_V: json.addProperty(kv.getKey(), kv.getStringV()); break; case JSON_V: json.add(kv.getKey(), JsonParser.parseString(kv.getJsonV())); break; } } return json; } public static JsonElement parse(Object value) { if (value instanceof Integer) { return new JsonPrimitive((Integer) value); } else if (value instanceof Long) { return new JsonPrimitive((Long) value); } else if (value instanceof String) { try { return JsonParser.parseString((String) value); } catch (Exception e) { if (isBase64(value.toString())) { value = "\"" + value + "\""; }
return JsonParser.parseString((String) value); } } else if (value instanceof Boolean) { return new JsonPrimitive((Boolean) value); } else if (value instanceof Double) { return new JsonPrimitive((Double) value); } else if (value instanceof Float) { return new JsonPrimitive((Float) value); } else { throw new IllegalArgumentException("Unsupported type: " + value.getClass().getSimpleName()); } } public static JsonObject convertToJsonObject(Map<String, ?> map) { JsonObject jsonObject = new JsonObject(); for (Map.Entry<String, ?> entry : map.entrySet()) { jsonObject.add(entry.getKey(), parse(entry.getValue())); } return jsonObject; } public static boolean isBase64(String value) { return value.length() % 4 == 0 && BASE64_PATTERN.matcher(value).matches(); } }
repos\thingsboard-master\common\transport\transport-api\src\main\java\org\thingsboard\server\common\transport\util\JsonUtils.java
1
请完成以下Java代码
protected void run(final EncryptionService newService, final Path path, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws MojoExecutionException { String decryptedContents = decrypt(path, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix); log.info("Re-encrypting file " + path); try { String encryptedContents = newService.encrypt(decryptedContents, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix); FileService.write(path, encryptedContents); } catch (Exception e) { throw new MojoExecutionException("Error Re-encrypting: " + e.getMessage(), e); } } private String decrypt(final Path path, String encryptPrefix, String encryptSuffix, String decryptPrefix, String decryptSuffix) throws MojoExecutionException { log.info("Decrypting file " + path); try { String contents = FileService.read(path); return getOldEncryptionService().decrypt(contents, encryptPrefix, encryptSuffix, decryptPrefix, decryptSuffix); } catch (Exception e) { throw new MojoExecutionException("Error Decrypting: " + e.getMessage(), e); } } private EncryptionService getOldEncryptionService() { JasyptEncryptorConfigurationProperties properties = new JasyptEncryptorConfigurationProperties(); configure(properties); StringEncryptor encryptor = new StringEncryptorBuilder(properties, "jasypt.plugin.old").build(); return new EncryptionService(encryptor); }
/** * <p>configure.</p> * * @param properties a {@link com.ulisesbocchio.jasyptspringboot.properties.JasyptEncryptorConfigurationProperties} object */ protected abstract void configure(JasyptEncryptorConfigurationProperties properties); /** * <p>setIfNotNull.</p> * * @param setter a {@link java.util.function.Consumer} object * @param value a T object * @param <T> a T class */ protected <T> void setIfNotNull(Consumer<T> setter, T value) { if (value != null) { setter.accept(value); } } }
repos\jasypt-spring-boot-master\jasypt-maven-plugin\src\main\java\com\ulisesbocchio\jasyptmavenplugin\mojo\AbstractReencryptMojo.java
1
请完成以下Java代码
public final void removeAssignedHUs(final Collection<I_M_HU> husToUnassign) { final Object documentLineModel = getDocumentLineModel(); final String trxName = getTrxName(); final Set<HuId> huIdsToUnassign = husToUnassign.stream() .map(I_M_HU::getM_HU_ID) .map(HuId::ofRepoId) .collect(Collectors.toSet()); huAssignmentBL.unassignHUs(documentLineModel, huIdsToUnassign, trxName); deleteAllocations(husToUnassign); // // Reset cached values assignedHUs = null; markStorageStaled(); } @Override public final void destroyAssignedHU(final I_M_HU huToDestroy) { Check.assumeNotNull(huToDestroy, "huToDestroy not null");
InterfaceWrapperHelper.setThreadInheritedTrxName(huToDestroy); removeAssignedHUs(Collections.singleton(huToDestroy)); final IContextAware contextProvider = InterfaceWrapperHelper.getContextAware(huToDestroy); final IHUContext huContext = Services.get(IHandlingUnitsBL.class).createMutableHUContext(contextProvider); handlingUnitsBL.markDestroyed(huContext, huToDestroy); } @Override public String toString() { return "AbstractHUAllocations [contextProvider=" + contextProvider + ", documentLineModel=" + documentLineModel + ", productStorage=" + productStorage + ", assignedHUs=" + assignedHUs + ", assignedHUsTrxName=" + assignedHUsTrxName + "]"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\document\impl\AbstractHUAllocations.java
1
请完成以下Java代码
public class M_PriceList_Version_RecalculateSeqNo extends JavaProcess { // Services final ITrxManager trxManager = Services.get(ITrxManager.class); final IPriceListDAO priceListDAO = Services.get(IPriceListDAO.class); @Override protected void prepare() { // nothing to do } /** * Recalculates SeqNo in M_ProductPrice in 10-steps for the current M_PriceList_Version, keeping the order they already had */ @Override protected String doIt() { final PriceListVersionId priceListVersionId = PriceListVersionId.ofRepoId(getRecord_ID());
int seqNumber = 10; final Iterator<I_M_ProductPrice> productPrices = priceListDAO.retrieveProductPricesOrderedBySeqNoAndProductIdAndMatchSeqNo(priceListVersionId); while (productPrices.hasNext()) { final I_M_ProductPrice pp = productPrices.next(); pp.setSeqNo(seqNumber); InterfaceWrapperHelper.save(pp); seqNumber = seqNumber + 10; } return "@SeqNoRecalculated@"; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\org\compiere\process\M_PriceList_Version_RecalculateSeqNo.java
1
请完成以下Java代码
public BigDecimal getQty() { return qty; } @Override public I_C_UOM getC_UOM() { return uom; } @Override public IAttributeSet getAttributesFrom() { return attributeStorageFrom; } @Override public IAttributeStorage getAttributesTo() { return attributeStorageTo; } @Override public IHUStorage getHUStorageFrom() { return huStorageFrom; } @Override public IHUStorage getHUStorageTo()
{ return huStorageTo; } @Override public BigDecimal getQtyUnloaded() { return qtyUnloaded; } @Override public boolean isVHUTransfer() { return vhuTransfer; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\attribute\strategy\impl\HUAttributeTransferRequest.java
1
请完成以下Java代码
public <K, V> Cache<K, V> getCache(String name) throws CacheException { org.springframework.cache.Cache springCache = cacheManager.getCache(name); return new SpringCacheWrapper(springCache); } @SuppressWarnings("rawtypes") static class SpringCacheWrapper implements Cache { private org.springframework.cache.Cache springCache; SpringCacheWrapper(org.springframework.cache.Cache springCache) { this.springCache = springCache; } @Override public Object get(Object key) throws CacheException { Object value = springCache.get(key); if (value instanceof SimpleValueWrapper) { return ((SimpleValueWrapper) value).get(); } return value; } @Override public Object put(Object key, Object value) throws CacheException { springCache.put(key, value); return value; } @Override public Object remove(Object key) throws CacheException { springCache.evict(key); return null; } @Override public void clear() throws CacheException { springCache.clear(); } @Override public int size() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return ehcache.getSize(); } throw new UnsupportedOperationException("invoke spring cache abstract size method not supported"); }
@SuppressWarnings("unchecked") @Override public Set keys() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); return new HashSet(ehcache.getKeys()); } throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported"); } @SuppressWarnings("unchecked") @Override public Collection values() { if (springCache.getNativeCache() instanceof Ehcache) { Ehcache ehcache = (Ehcache) springCache.getNativeCache(); List keys = ehcache.getKeys(); if (!CollectionUtils.isEmpty(keys)) { List values = new ArrayList(keys.size()); for (Object key : keys) { Object value = get(key); if (value != null) { values.add(value); } } return Collections.unmodifiableList(values); } else { return Collections.emptyList(); } } throw new UnsupportedOperationException("invoke spring cache abstract values method not supported"); } } }
repos\roncoo-pay-master\roncoo-pay-web-boss\src\main\java\com\roncoo\pay\permission\shiro\spring\SpringCacheManagerWrapper.java
1
请完成以下Java代码
public void setC_DocType_ID (int C_DocType_ID) { if (C_DocType_ID < 0) set_Value (COLUMNNAME_C_DocType_ID, null); else set_Value (COLUMNNAME_C_DocType_ID, Integer.valueOf(C_DocType_ID)); } /** Get Belegart. @return Belegart oder Verarbeitungsvorgaben */ @Override public int getC_DocType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_C_DocType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set DocumentLinesNumber. @param DocumentLinesNumber DocumentLinesNumber */ @Override public void setDocumentLinesNumber (int DocumentLinesNumber) { set_Value (COLUMNNAME_DocumentLinesNumber, Integer.valueOf(DocumentLinesNumber)); } /** Get DocumentLinesNumber. @return DocumentLinesNumber */ @Override public int getDocumentLinesNumber () { Integer ii = (Integer)get_Value(COLUMNNAME_DocumentLinesNumber); if (ii == null) return 0; return ii.intValue(); } /** Set Abgabemeldung Konfiguration. @param M_Shipment_Declaration_Config_ID Abgabemeldung Konfiguration */ @Override public void setM_Shipment_Declaration_Config_ID (int M_Shipment_Declaration_Config_ID) { if (M_Shipment_Declaration_Config_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Config_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Shipment_Declaration_Config_ID, Integer.valueOf(M_Shipment_Declaration_Config_ID)); } /** Get Abgabemeldung Konfiguration. @return Abgabemeldung Konfiguration */
@Override public int getM_Shipment_Declaration_Config_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Shipment_Declaration_Config_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Name */ @Override public void setName (java.lang.String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Name */ @Override public java.lang.String getName () { return (java.lang.String)get_Value(COLUMNNAME_Name); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Shipment_Declaration_Config.java
1
请完成以下Java代码
public String getProcessInstanceId() { return processInstanceId; } @Override public String getExecutionId() { return executionId; } @Override public BusinessProcessEventType getType() { return type; } @Override public Date getTimeStamp() { return timeStamp; } @Override public DelegateTask getTask() { return delegateTask; }
@Override public String getTaskId() { if (delegateTask != null) { return delegateTask.getId(); } return null; } @Override public String getTaskDefinitionKey() { if (delegateTask != null) { return delegateTask.getTaskDefinitionKey(); } return null; } @Override public String toString() { return "Event '" + processDefinition.getKey() + "' ['" + type + "', " + (type == BusinessProcessEventType.TAKE ? transitionName : activityId) + "]"; } }
repos\camunda-bpm-platform-master\engine-cdi\core\src\main\java\org\camunda\bpm\engine\cdi\impl\event\CdiBusinessProcessEvent.java
1
请完成以下Spring Boot application配置
server.port=8081 spring.main.allow-bean-definition-overriding=true spring.datasource.url=jdbc:mysql://127.0.0.1:3306/flowable-sample?characterEncoding=UTF-8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver spri
ng.servlet.multipart.enabled=true spring.servlet.multipart.max-file-size=100MB spring.servlet.multipart.max-request-size=500MB
repos\spring-boot-quick-master\quick-flowable\src\main\resources\application.properties
2
请在Spring Boot框架中完成以下Java代码
public ObjectMapper jsonObjectMapper() { return JsonObjectMapperHolder.sharedJsonObjectMapper(); } @Bean(Adempiere.BEAN_NAME) public Adempiere adempiere() { // when this is done, Adempiere.getBean(...) is ready to use return Env.getSingleAdempiereInstance(applicationContext); } @Override public void afterPropertiesSet() { if (clearQuerySelectionsRateInSeconds > 0) { final ScheduledExecutorService scheduledExecutor = Executors.newScheduledThreadPool( 1, // corePoolSize CustomizableThreadFactory.builder() .setDaemon(true) .setThreadNamePrefix("cleanup-" + I_T_Query_Selection.Table_Name) .build()); // note: "If any execution of this task takes longer than its period, then subsequent executions may start late, but will not concurrently execute." scheduledExecutor.scheduleAtFixedRate(
QuerySelectionToDeleteHelper::deleteScheduledSelectionsNoFail, // command, don't fail because on failure the task won't be re-scheduled so it's game over clearQuerySelectionsRateInSeconds, // initialDelay clearQuerySelectionsRateInSeconds, // period TimeUnit.SECONDS // timeUnit ); logger.info("Clearing query selection tables each {} seconds", clearQuerySelectionsRateInSeconds); } } private static void setDefaultProperties() { if (Check.isBlank(System.getProperty(SYSTEM_PROPERTY_APP_NAME))) { System.setProperty(SYSTEM_PROPERTY_APP_NAME, ServerBoot.class.getSimpleName()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\serverRoot\de.metas.adempiere.adempiere.serverRoot.base\src\main\java\de\metas\ServerBoot.java
2
请完成以下Java代码
public double getValue () { return m_value; } // getValue /** * @param value The data value to set. */ public void setValue (double value) { m_value = value; if (m_label != null) m_labelValue = s_format.format(m_value) + " - " + m_label; else m_labelValue = s_format.format(m_value); } // setValue /** * @return Returns the column width in pixels. */ public double getColWidth () { return m_width; } // getColWidth /** * @param width The column width in pixels. */ public void setColWidth (double width) { m_width = width; } // getColWidth /** * @return Returns the height in pixels. */ public double getColHeight() { return m_height; } // getHeight /** * @param height The height in pixels. */ public void setColHeight (double height) { m_height = height; } // setHeight public MQuery getMQuery(MGoal mGoal) { MQuery query = null; if (getAchievement() != null) // Single Achievement { MAchievement a = getAchievement(); query = MQuery.getEqualQuery("PA_Measure_ID", a.getPA_Measure_ID()); } else if (getGoal() != null) // Multiple Achievements { MGoal goal = getGoal();
query = MQuery.getEqualQuery("PA_Measure_ID", goal.getPA_Measure_ID()); } else if (getMeasureCalc() != null) // Document { MMeasureCalc mc = getMeasureCalc(); query = mc.getQuery(mGoal.getRestrictions(false), getMeasureDisplay(), getDate(), Env.getUserRolePermissions()); // logged in role } else if (getProjectType() != null) // Document { ProjectType pt = getProjectType(); query = MMeasure.getQuery(pt, mGoal.getRestrictions(false), getMeasureDisplay(), getDate(), getID(), Env.getUserRolePermissions()); // logged in role } else if (getRequestType() != null) // Document { MRequestType rt = getRequestType(); query = rt.getQuery(mGoal.getRestrictions(false), getMeasureDisplay(), getDate(), getID(), Env.getUserRolePermissions()); // logged in role } return query; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java-legacy\org\adempiere\apps\graph\GraphColumn.java
1
请完成以下Java代码
public abstract class SimpleLookupDescriptorTemplate implements LookupDescriptor, LookupDataSourceFetcher { @Override public final LookupDataSourceFetcher getLookupDataSourceFetcher() { return this; } @Override public final boolean isHighVolume() { // NOTE: method will never be called because isCached() == true return false; } @Override public LookupSource getLookupSourceType() { return LookupSource.list; } @Override public boolean hasParameters() { return !getDependsOnFieldNames().isEmpty(); } @Override public abstract boolean isNumericKey(); @Override public abstract Set<String> getDependsOnFieldNames(); // // // // ----------------------- // // @Override public LookupDataSourceContext.Builder newContextForFetchingById(final Object id) { return LookupDataSourceContext.builderWithoutTableName();
} @Override @Nullable public abstract LookupValue retrieveLookupValueById(@NonNull LookupDataSourceContext evalCtx); @Override public LookupDataSourceContext.Builder newContextForFetchingList() { return LookupDataSourceContext.builderWithoutTableName(); } @Override public abstract LookupValuesPage retrieveEntities(LookupDataSourceContext evalCtx); @Override @Nullable public final String getCachePrefix() { // NOTE: method will never be called because isCached() == true return null; } @Override public final boolean isCached() { return true; } @Override public void cacheInvalidate() { } @Override public Optional<WindowId> getZoomIntoWindowId() { return Optional.empty(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\window\descriptor\SimpleLookupDescriptorTemplate.java
1
请完成以下Java代码
public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Image Link. @param ImageLink Image Link */ public void setImageLink (String ImageLink) { set_Value (COLUMNNAME_ImageLink, ImageLink); } /** Get Image Link. @return Image Link */ public String getImageLink () { return (String)get_Value(COLUMNNAME_ImageLink); } /** Set Menu Link. @param MenuLink Menu Link */ public void setMenuLink (String MenuLink) { set_Value (COLUMNNAME_MenuLink, MenuLink); } /** Get Menu Link. @return Menu Link */ public String getMenuLink () { return (String)get_Value(COLUMNNAME_MenuLink); } /** Set Module. @param Module Module */ public void setModule (String Module) { set_Value (COLUMNNAME_Module, Module); } /** Get Module. @return Module */ public String getModule () { return (String)get_Value(COLUMNNAME_Module); } /** 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); } public I_U_WebMenu getParentMenu() throws RuntimeException { return (I_U_WebMenu)MTable.get(getCtx(), I_U_WebMenu.Table_Name) .getPO(getParentMenu_ID(), get_TrxName()); } /** Set Parent Menu. @param ParentMenu_ID Parent Menu */ public void setParentMenu_ID (int ParentMenu_ID)
{ if (ParentMenu_ID < 1) set_Value (COLUMNNAME_ParentMenu_ID, null); else set_Value (COLUMNNAME_ParentMenu_ID, Integer.valueOf(ParentMenu_ID)); } /** Get Parent Menu. @return Parent Menu */ public int getParentMenu_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_ParentMenu_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Position. @param Position Position */ public void setPosition (String Position) { set_Value (COLUMNNAME_Position, Position); } /** Get Position. @return Position */ public String getPosition () { return (String)get_Value(COLUMNNAME_Position); } /** Set Sequence. @param Sequence Sequence */ public void setSequence (BigDecimal Sequence) { set_Value (COLUMNNAME_Sequence, Sequence); } /** Get Sequence. @return Sequence */ public BigDecimal getSequence () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_Sequence); if (bd == null) return Env.ZERO; return bd; } /** Set Web Menu. @param U_WebMenu_ID Web Menu */ public void setU_WebMenu_ID (int U_WebMenu_ID) { if (U_WebMenu_ID < 1) set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, null); else set_ValueNoCheck (COLUMNNAME_U_WebMenu_ID, Integer.valueOf(U_WebMenu_ID)); } /** Get Web Menu. @return Web Menu */ public int getU_WebMenu_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_U_WebMenu_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_U_WebMenu.java
1
请完成以下Java代码
public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public Date getLastUpdate() { return lastUpdate;
} public void setLastUpdate(Date lastUpdate) { this.lastUpdate = lastUpdate; } public ContactWithJavaUtilDate() { } public ContactWithJavaUtilDate(String name, String address, String phone, Date birthday, Date lastUpdate) { this.name = name; this.address = address; this.phone = phone; this.birthday = birthday; this.lastUpdate = lastUpdate; } }
repos\tutorials-master\spring-boot-modules\spring-boot-data\src\main\java\com\baeldung\jsondateformat\ContactWithJavaUtilDate.java
1
请完成以下Spring Boot application配置
#服务器端口 server: port: 8100 #数据源配置 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: ${blade.datasource.dev.url} username: ${blade.datasource.dev.username} password: ${blad
e.datasource.dev.password} #第三方登陆 social: enabled: true domain: http://127.0.0.1:1888
repos\SpringBlade-master\blade-auth\src\main\resources\application-dev.yml
2
请完成以下Java代码
public Builder setRowId(final DocumentId rowId) { this.rowId = rowId; _rowIdEffective = null; return this; } /** @return view row ID; never null */ public DocumentId getRowId() { if (_rowIdEffective == null) { if (rowId == null) { throw new IllegalStateException("No rowId was provided for " + this); } if (isRootRow()) { _rowIdEffective = rowId; } else { // NOTE: we have to do this because usually, the root row can have the same ID as one of the included rows, // because the root/aggregated rows are build on demand and they don't really exist in database. // Also see https://github.com/metasfresh/metasfresh-webui-frontend/issues/835#issuecomment-307783959 _rowIdEffective = rowId.toIncludedRowId(); } } return _rowIdEffective; } public Builder setParentRowId(final DocumentId parentRowId) { this.parentRowId = parentRowId; _rowIdEffective = null; return this; } private DocumentId getParentRowId() { return parentRowId; } public boolean isRootRow() { return getParentRowId() == null; } private IViewRowType getType() { return type; } public Builder setType(final IViewRowType type) { this.type = type; return this; } public Builder setProcessed(final boolean processed) { this.processed = processed; return this; } private boolean isProcessed() { if (processed == null) { // NOTE: don't take the "Processed" field if any, because in frontend we will end up with a lot of grayed out completed sales orders, for example. // return DisplayType.toBoolean(values.getOrDefault("Processed", false)); return false; } else { return processed.booleanValue(); } } public Builder putFieldValue(final String fieldName, @Nullable final Object jsonValue) {
if (jsonValue == null || JSONNullValue.isNull(jsonValue)) { values.remove(fieldName); } else { values.put(fieldName, jsonValue); } return this; } private Map<String, Object> getValues() { return values; } public LookupValue getFieldValueAsLookupValue(final String fieldName) { return LookupValue.cast(values.get(fieldName)); } public Builder addIncludedRow(final IViewRow includedRow) { if (includedRows == null) { includedRows = new ArrayList<>(); } includedRows.add(includedRow); return this; } private List<IViewRow> buildIncludedRows() { if (includedRows == null || includedRows.isEmpty()) { return ImmutableList.of(); } return ImmutableList.copyOf(includedRows); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\view\ViewRow.java
1
请完成以下Spring Boot application配置
server: port: 8888 spring: application: name: gateway-application cloud: # Spring Cloud Gateway 配置项,对应 GatewayProperties 类 gateway: # 路由配置项,对应 RouteDefinition 数组 routes: - id: yudaoyuanma # 路由的编号 uri: http://www.iocoder.cn # 路由到的目标地址 predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组 - Path=/blog filters: - StripPrefix=1 - id: oschina # 路由的编号 uri: https://www
.oschina.net # 路由的目标地址 predicates: # 断言,作为路由的匹配条件,对应 RouteDefinition 数组 - Path=/oschina filters: # 过滤器,对请求进行拦截,实现自定义的功能,对应 FilterDefinition 数组 - StripPrefix=1
repos\SpringBoot-Labs-master\labx-08-spring-cloud-gateway\labx-08-sc-gateway-demo01\src\main\resources\application.yaml
2
请在Spring Boot框架中完成以下Java代码
public class ClusterServiceImpl implements ClusterService { private static final Logger logger = LoggerFactory.getLogger(ClusterServiceImpl.class); private Cluster cluster; private Map<String, Bucket> buckets = new ConcurrentHashMap<>(); @PostConstruct private void init() { CouchbaseEnvironment env = DefaultCouchbaseEnvironment.create(); cluster = CouchbaseCluster.create(env, "localhost"); } @Override synchronized public Bucket openBucket(String name, String password) { if (!buckets.containsKey(name)) { Bucket bucket = cluster.openBucket(name, password); buckets.put(name, bucket); } return buckets.get(name); } @Override public List<JsonDocument> getDocuments(Bucket bucket, Iterable<String> keys) { List<JsonDocument> docs = new ArrayList<>(); for (String key : keys) { JsonDocument doc = bucket.get(key); if (doc != null) { docs.add(doc); } } return docs; } @Override public List<JsonDocument> getDocumentsAsync(final AsyncBucket asyncBucket, Iterable<String> keys) { Observable<JsonDocument> asyncBulkGet = Observable.from(keys).flatMap(new Func1<String, Observable<JsonDocument>>() { public Observable<JsonDocument> call(String key) { return asyncBucket.get(key);
} }); final List<JsonDocument> docs = new ArrayList<>(); try { asyncBulkGet.toBlocking().forEach(new Action1<JsonDocument>() { public void call(JsonDocument doc) { docs.add(doc); } }); } catch (Exception e) { logger.error("Error during bulk get", e); } return docs; } }
repos\tutorials-master\persistence-modules\couchbase\src\main\java\com\baeldung\couchbase\spring\service\ClusterServiceImpl.java
2
请完成以下Java代码
public void setExternalSystem_Config_LeichMehl_ProductMapping_ID (final int ExternalSystem_Config_LeichMehl_ProductMapping_ID) { if (ExternalSystem_Config_LeichMehl_ProductMapping_ID < 1) set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID, null); else set_ValueNoCheck (COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID, ExternalSystem_Config_LeichMehl_ProductMapping_ID); } @Override public int getExternalSystem_Config_LeichMehl_ProductMapping_ID() { return get_ValueAsInt(COLUMNNAME_ExternalSystem_Config_LeichMehl_ProductMapping_ID); } @Override public I_LeichMehl_PluFile_ConfigGroup getLeichMehl_PluFile_ConfigGroup() { return get_ValueAsPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class); } @Override public void setLeichMehl_PluFile_ConfigGroup(final I_LeichMehl_PluFile_ConfigGroup LeichMehl_PluFile_ConfigGroup) { set_ValueFromPO(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, I_LeichMehl_PluFile_ConfigGroup.class, LeichMehl_PluFile_ConfigGroup); } @Override public void setLeichMehl_PluFile_ConfigGroup_ID (final int LeichMehl_PluFile_ConfigGroup_ID) { if (LeichMehl_PluFile_ConfigGroup_ID < 1) set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, null); else set_Value (COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID, LeichMehl_PluFile_ConfigGroup_ID); }
@Override public int getLeichMehl_PluFile_ConfigGroup_ID() { return get_ValueAsInt(COLUMNNAME_LeichMehl_PluFile_ConfigGroup_ID); } @Override public void setM_Product_ID (final int M_Product_ID) { if (M_Product_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_ID, M_Product_ID); } @Override public int getM_Product_ID() { return get_ValueAsInt(COLUMNNAME_M_Product_ID); } @Override public void setPLU_File (final String PLU_File) { set_Value (COLUMNNAME_PLU_File, PLU_File); } @Override public String getPLU_File() { return get_ValueAsString(COLUMNNAME_PLU_File); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.externalsystem\src\main\java-gen\de\metas\externalsystem\model\X_ExternalSystem_Config_LeichMehl_ProductMapping.java
1
请完成以下Java代码
public @Nullable String getName() { return this.name; } public @Nullable String getVersion() { return this.version; } public @Nullable Instant getTime() { return this.time; } public @Nullable Map<String, String> getAdditionalProperties() { return this.additionalProperties; }
} /** * Exception thrown when an additional property with a null value is encountered. */ public static class NullAdditionalPropertyValueException extends IllegalArgumentException { public NullAdditionalPropertyValueException(String name) { super("Additional property '" + name + "' is illegal as its value is null"); } } }
repos\spring-boot-4.0.1\loader\spring-boot-loader-tools\src\main\java\org\springframework\boot\loader\tools\BuildPropertiesWriter.java
1
请完成以下Java代码
public String toString() { StringBuffer sb = new StringBuffer ("X_K_Type[") .append(get_ID()).append("]"); return sb.toString(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Comment/Help. @param Help Comment or Hint */ public void setHelp (String Help) { set_Value (COLUMNNAME_Help, Help); } /** Get Comment/Help. @return Comment or Hint */ public String getHelp () { return (String)get_Value(COLUMNNAME_Help); } /** Set Public. @param IsPublic Public can read entry */ public void setIsPublic (boolean IsPublic) { set_Value (COLUMNNAME_IsPublic, Boolean.valueOf(IsPublic)); } /** Get Public. @return Public can read entry */ public boolean isPublic () { Object oo = get_Value(COLUMNNAME_IsPublic); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Public Write. @param IsPublicWrite Public can write entries */ public void setIsPublicWrite (boolean IsPublicWrite) { set_Value (COLUMNNAME_IsPublicWrite, Boolean.valueOf(IsPublicWrite)); } /** Get Public Write. @return Public can write entries */ public boolean isPublicWrite () {
Object oo = get_Value(COLUMNNAME_IsPublicWrite); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** Set Knowldge Type. @param K_Type_ID Knowledge Type */ public void setK_Type_ID (int K_Type_ID) { if (K_Type_ID < 1) set_ValueNoCheck (COLUMNNAME_K_Type_ID, null); else set_ValueNoCheck (COLUMNNAME_K_Type_ID, Integer.valueOf(K_Type_ID)); } /** Get Knowldge Type. @return Knowledge Type */ public int getK_Type_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_K_Type_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) { set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_K_Type.java
1
请在Spring Boot框架中完成以下Java代码
public class SignalEventSubscriptionEntityImpl extends EventSubscriptionEntityImpl implements SignalEventSubscriptionEntity { private static final long serialVersionUID = 1L; // Using json here, but not worth of adding json dependency lib for this private static final String CONFIGURATION_TEMPLATE = "'{'\"scope\":\"{0}\"'}'"; public SignalEventSubscriptionEntityImpl() {} public SignalEventSubscriptionEntityImpl(EventSubscriptionServiceConfiguration eventSubscriptionServiceConfiguration) { super(eventSubscriptionServiceConfiguration); eventType = EVENT_TYPE; } @Override public void setConfiguration(String configuration) { if (configuration != null && configuration.contains("{\"scope\":")) { this.configuration = configuration; } else { this.configuration = MessageFormat.format(CONFIGURATION_TEMPLATE, configuration); } }
@Override public boolean isProcessInstanceScoped() { String scope = extractScopeFormConfiguration(); return Signal.SCOPE_PROCESS_INSTANCE.equals(scope); } @Override public boolean isGlobalScoped() { String scope = extractScopeFormConfiguration(); return (scope == null) || Signal.SCOPE_GLOBAL.equals(scope); } protected String extractScopeFormConfiguration() { if (this.configuration == null) { return null; } else { return this.configuration.substring(10, this.configuration.length() - 2); // 10 --> length of {"scope": and -2 for removing"} } } }
repos\flowable-engine-main\modules\flowable-eventsubscription-service\src\main\java\org\flowable\eventsubscription\service\impl\persistence\entity\SignalEventSubscriptionEntityImpl.java
2
请完成以下Java代码
public static INDArray getGrayImageFeatures(String base, String fileName) throws Exception { log.info("start getImageFeatures [{}]", base + fileName); // 和训练模型时一样的设置 ImageRecordReader imageRecordReader = new ImageRecordReader(RESIZE_HEIGHT, RESIZE_WIDTH, 1); FileSplit fileSplit = new FileSplit(new File(base + fileName), NativeImageLoader.ALLOWED_FORMATS); imageRecordReader.initialize(fileSplit); DataSetIterator dataSetIterator = new RecordReaderDataSetIterator(imageRecordReader, 1); dataSetIterator.setPreProcessor(new ImagePreProcessingScaler(0, 1)); // 取特征 return dataSetIterator.next().getFeatures(); } /** * 批量清理文件 * @param base 处理文件的目录 * @param fileNames 待清理文件集合 */
public static void clear(String base, String...fileNames) { for (String fileName : fileNames) { if (null==fileName) { continue; } File file = new File(base + fileName); if (file.exists()) { file.delete(); } } } }
repos\springboot-demo-master\Deeplearning4j\src\main\java\com\et\dl4j\util\ImageFileUtil.java
1
请完成以下Java代码
public int getAD_User_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_AD_User_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Description. @param Description Optional short description of the record */ public void setDescription (String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Description. @return Optional short description of the record */ public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Internal. @param IsInternal Internal Organization */ public void setIsInternal (boolean IsInternal) { set_Value (COLUMNNAME_IsInternal, Boolean.valueOf(IsInternal)); } /** Get Internal. @return Internal Organization */ public boolean isInternal () { Object oo = get_Value(COLUMNNAME_IsInternal); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } /** 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 Valid to. @param ValidTo Valid to including this date (last day) */ public void setValidTo (Timestamp ValidTo) { set_Value (COLUMNNAME_ValidTo, ValidTo); } /** Get Valid to. @return Valid to including this date (last day) */ public Timestamp getValidTo () { return (Timestamp)get_Value(COLUMNNAME_ValidTo); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_B_Seller.java
1
请完成以下Java代码
protected void prepare() { ProcessInfoParameter[] para = getParametersAsArray(); for (int i = 0; i < para.length; i++) { String name = para[i].getParameterName(); if (para[i].getParameter() == null) ; else log.error("prepare - Unknown Parameter: " + name); } m_AD_Tree_ID = getRecord_ID(); // from Window } // prepare /** * Perform process. * @return Message (clear text) * @throws Exception if not successful */ protected String doIt() throws Exception
{ log.info("AD_Tree_ID=" + m_AD_Tree_ID); if (m_AD_Tree_ID == 0) throw new IllegalArgumentException("Tree_ID = 0"); MTree tree = new MTree (getCtx(), m_AD_Tree_ID, get_TrxName()); if (tree == null || tree.getAD_Tree_ID() == 0) throw new IllegalArgumentException("No Tree -" + tree); // if (MTree.TREETYPE_BoM.equals(tree.getTreeType())) return "BOM Trees not implemented"; tree.verifyTree(); return "Ok"; } // doIt } // TreeMaintenence
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-legacy\org\compiere\process\TreeMaintenance.java
1
请完成以下Java代码
public void postProcessEnvironment(ConfigurableEnvironment environment, SpringApplication application) { ResourceLoader resourceLoader = application.getResourceLoader(); if (resourceLoader == null) { resourceLoader = new DefaultResourceLoader(); } MutablePropertySources propertySources = environment.getPropertySources(); for (String location : DEPRECATED_LOCATIONS) { try { Resource resource = resourceLoader.getResource(location); PropertySource<?> propertySource = DEFAULT_PROPERTY_SOURCE_FACTORY.createPropertySource(null, new EncodedResource(resource)); if (propertySources.contains(propertySource.getName())) { propertySources.replace(propertySource.getName(), propertySource); } else { propertySources.addLast(propertySource); } logger.warn("Using deprecated property source {} please switch to using Spring Boot externalized configuration", propertySource);
} catch (IllegalArgumentException | FileNotFoundException | UnknownHostException ex) { // We are always ignoring the deprecated resources. This is done in the same way as in the Spring ConfigurationClassParsers // Placeholders not resolvable or resource not found when trying to open it if (logger.isInfoEnabled()) { logger.info("Properties location [{}] not resolvable: {}", location, ex.getMessage()); } } catch (IOException ex) { throw new UncheckedIOException("Failed to create property source", ex); } } } @Override public int getOrder() { return order; } }
repos\flowable-engine-main\modules\flowable-app-rest\src\main\java\org\flowable\rest\app\properties\BackwardsCompatiblePropertiesLoader.java
1
请完成以下Java代码
public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } public boolean isScope() { return isScope; } public void setScope(boolean isScope) { this.isScope = isScope; } @Override public int getX() { return x; } @Override public void setX(int x) { this.x = x; } @Override public int getY() { return y; } @Override public void setY(int y) { this.y = y; } @Override public int getWidth() { return width; }
@Override public void setWidth(int width) { this.width = width; } @Override public int getHeight() { return height; } @Override public void setHeight(int height) { this.height = height; } @Override public boolean isAsync() { return isAsync; } public void setAsync(boolean isAsync) { this.isAsync = isAsync; } @Override public boolean isExclusive() { return isExclusive; } public void setExclusive(boolean isExclusive) { this.isExclusive = isExclusive; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\pvm\process\ActivityImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class InsuranceContractRequiredTemplates { @SerializedName("templateId") private String templateId = null; @SerializedName("careType") private BigDecimal careType = null; public InsuranceContractRequiredTemplates templateId(String templateId) { this.templateId = templateId; return this; } /** * Alberta-Id der Dokumentenvorlage - HIER FEHLT NOCH DIE API ZUM ABRUF für das Mapping /template * @return templateId **/ @Schema(example = "13e2a423-24e8-4844-b710-3d1e0ee60c92", description = "Alberta-Id der Dokumentenvorlage - HIER FEHLT NOCH DIE API ZUM ABRUF für das Mapping /template") public String getTemplateId() { return templateId; } public void setTemplateId(String templateId) { this.templateId = templateId; } public InsuranceContractRequiredTemplates careType(BigDecimal careType) { this.careType = careType; return this; } /** * Art der Versorgung (0 &#x3D; Unbekannt, 1 &#x3D; Erstversorgung, 2 &#x3D; Folgeversorgung) * @return careType **/ @Schema(example = "1", description = "Art der Versorgung (0 = Unbekannt, 1 = Erstversorgung, 2 = Folgeversorgung)") public BigDecimal getCareType() { return careType; } public void setCareType(BigDecimal careType) { this.careType = careType; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false;
} InsuranceContractRequiredTemplates insuranceContractRequiredTemplates = (InsuranceContractRequiredTemplates) o; return Objects.equals(this.templateId, insuranceContractRequiredTemplates.templateId) && Objects.equals(this.careType, insuranceContractRequiredTemplates.careType); } @Override public int hashCode() { return Objects.hash(templateId, careType); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class InsuranceContractRequiredTemplates {\n"); sb.append(" templateId: ").append(toIndentedString(templateId)).append("\n"); sb.append(" careType: ").append(toIndentedString(careType)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-externalsystems\alberta\alberta-article-api\src\main\java\io\swagger\client\model\InsuranceContractRequiredTemplates.java
2
请完成以下Java代码
public String getDescription () { return (String)get_Value(COLUMNNAME_Description); } /** Set Invoiced. @param IsInvoiced Is this invoiced? */ public void setIsInvoiced (boolean IsInvoiced) { set_Value (COLUMNNAME_IsInvoiced, Boolean.valueOf(IsInvoiced)); } /** Get Invoiced. @return Is this invoiced? */ public boolean isInvoiced () { Object oo = get_Value(COLUMNNAME_IsInvoiced); if (oo != null) { if (oo instanceof Boolean) return ((Boolean)oo).booleanValue(); return "Y".equals(oo); } return false; } public I_M_Product_Category getM_Product_Category() throws RuntimeException { return (I_M_Product_Category)MTable.get(getCtx(), I_M_Product_Category.Table_Name) .getPO(getM_Product_Category_ID(), get_TrxName()); } /** Set Product Category. @param M_Product_Category_ID Category of a Product */ public void setM_Product_Category_ID (int M_Product_Category_ID) { if (M_Product_Category_ID < 1) set_Value (COLUMNNAME_M_Product_Category_ID, null); else set_Value (COLUMNNAME_M_Product_Category_ID, Integer.valueOf(M_Product_Category_ID)); } /** Get Product Category. @return Category of a Product */ public int getM_Product_Category_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_Category_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Name. @param Name Alphanumeric identifier of the entity */ public void setName (String Name) {
set_Value (COLUMNNAME_Name, Name); } /** Get Name. @return Alphanumeric identifier of the entity */ public String getName () { return (String)get_Value(COLUMNNAME_Name); } /** Get Record ID/ColumnName @return ID/ColumnName pair */ public KeyNamePair getKeyNamePair() { return new KeyNamePair(get_ID(), getName()); } /** Set Expense Type. @param S_ExpenseType_ID Expense report type */ public void setS_ExpenseType_ID (int S_ExpenseType_ID) { if (S_ExpenseType_ID < 1) set_ValueNoCheck (COLUMNNAME_S_ExpenseType_ID, null); else set_ValueNoCheck (COLUMNNAME_S_ExpenseType_ID, Integer.valueOf(S_ExpenseType_ID)); } /** Get Expense Type. @return Expense report type */ public int getS_ExpenseType_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_S_ExpenseType_ID); if (ii == null) return 0; return ii.intValue(); } /** Set Search Key. @param Value Search key for the record in the format required - must be unique */ public void setValue (String Value) { set_Value (COLUMNNAME_Value, Value); } /** Get Search Key. @return Search key for the record in the format required - must be unique */ public String getValue () { return (String)get_Value(COLUMNNAME_Value); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_S_ExpenseType.java
1
请完成以下Java代码
public Integer getId() { return id; } public UserProfileDO setId(Integer id) { this.id = id; return this; } public Integer getGender() { return gender; } public UserProfileDO setGender(Integer gender) { this.gender = gender; return this; } public Integer getDeleted() { return deleted; } public UserProfileDO setDeleted(Integer deleted) { this.deleted = deleted; return this; } public Integer getTenantId() { return tenantId; }
public UserProfileDO setTenantId(Integer tenantId) { this.tenantId = tenantId; return this; } public Integer getUserId() { return userId; } public UserProfileDO setUserId(Integer userId) { this.userId = userId; return this; } }
repos\SpringBoot-Labs-master\lab-12-mybatis\lab-12-mybatis-plus-tenant\src\main\java\cn\iocoder\springboot\lab12\mybatis\dataobject\UserProfileDO.java
1
请在Spring Boot框架中完成以下Java代码
public void insertAuthorWithBooks() { Author jn = new Author(); jn.setName("Joana Nimar"); jn.setAge(34); jn.setGenre("History"); Book jn01 = new Book(); jn01.setIsbn("001-JN"); jn01.setTitle("A History of Ancient Prague"); Book jn02 = new Book(); jn02.setIsbn("002-JN"); jn02.setTitle("A People's History"); Book jn03 = new Book(); jn03.setIsbn("003-JN"); jn03.setTitle("World History"); jn.addBook(jn01); jn.addBook(jn02); jn.addBook(jn03); authorRepository.save(jn); } @Transactional public void insertNewBook() { Author author = authorRepository.fetchByName("Joana Nimar"); Book book = new Book(); book.setIsbn("004-JN"); book.setTitle("History Details"); author.addBook(book); // use addBook() helper
authorRepository.save(author); } @Transactional public void deleteLastBook() { Author author = authorRepository.fetchByName("Joana Nimar"); List<Book> books = author.getBooks(); author.removeBook(books.get(books.size() - 1)); } @Transactional public void deleteFirstBook() { Author author = authorRepository.fetchByName("Joana Nimar"); List<Book> books = author.getBooks(); author.removeBook(books.get(0)); } }
repos\Hibernate-SpringBoot-master\HibernateSpringBootOneToManyUnidirectional\src\main\java\com\bookstore\service\BookstoreService.java
2
请完成以下Java代码
public String getMessage() { return this.message; } public void setMessage(String message) { this.message = message; } @Override public String toString() { return new StringJoiner(", ", "{", "}").add("invalid=" + this.invalid) .add("javaVersion=" + this.javaVersion) .add("language=" + this.language) .add("configurationFileFormat=" + this.configurationFileFormat) .add("packaging=" + this.packaging) .add("type=" + this.type) .add("dependencies=" + this.dependencies) .add("message='" + this.message + "'") .toString(); } } /** * Invalid dependencies information. */ public static class InvalidDependencyInformation {
private boolean invalid = true; private final List<String> values; public InvalidDependencyInformation(List<String> values) { this.values = values; } public boolean isInvalid() { return this.invalid; } public List<String> getValues() { return this.values; } @Override public String toString() { return new StringJoiner(", ", "{", "}").add(String.join(", ", this.values)).toString(); } } }
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\ProjectRequestDocument.java
1
请完成以下Java代码
public static CurrencyConversionTypeId ofRepoIdOrNull(final int repoId) { return repoId > 0 ? ofRepoId(repoId) : null; } public static Optional<CurrencyConversionTypeId> optionalOfRepoId(final int repoId) { return Optional.ofNullable(ofRepoIdOrNull(repoId)); } public static int toRepoId(@Nullable final CurrencyConversionTypeId CurrencyConversionTypeId) { return CurrencyConversionTypeId != null ? CurrencyConversionTypeId.getRepoId() : -1; } int repoId; private CurrencyConversionTypeId(final int repoId) {
this.repoId = Check.assumeGreaterThanZero(repoId, "C_ConversionType_ID"); } @Override @JsonValue public int getRepoId() { return repoId; } public static boolean equals(@Nullable final CurrencyConversionTypeId currencyConversionTypeId1, @Nullable final CurrencyConversionTypeId currencyConversionTypeId2) { return Objects.equals(currencyConversionTypeId1, currencyConversionTypeId2); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\money\CurrencyConversionTypeId.java
1
请完成以下Java代码
public String getDescriptionBottomById(@NonNull final OrderId orderId) { return getById(orderId).getDescriptionBottom(); } @Override public String getDescriptionById(@NonNull final OrderId orderId) { return getById(orderId).getDescription(); } @Override public void setShipperId(@NonNull final I_C_Order order) { order.setM_Shipper_ID(ShipperId.toRepoId(findShipperId(order))); } private ShipperId findShipperId(@NonNull final I_C_Order orderRecord) { final Optional<ShipperId> dropShipShipperId = getDropShipAddressShipperId(orderRecord); return dropShipShipperId.orElse(getDeliveryAddressShipperId(orderRecord)); } private Optional<ShipperId> getDropShipAddressShipperId(final I_C_Order orderRecord) { if (orderRecord.getDropShip_BPartner_ID() <= 0 || orderRecord.getDropShip_Location_ID() <= 0) { return Optional.empty(); } final Optional<ShipperId> dropShipShipperId = partnerDAO.getShipperIdByBPLocationId( BPartnerLocationId.ofRepoId( orderRecord.getDropShip_BPartner_ID(), orderRecord.getDropShip_Location_ID())); return Optional.ofNullable(dropShipShipperId.orElse(getPartnerShipperId(BPartnerId.ofRepoId(orderRecord.getDropShip_BPartner_ID())))); } private ShipperId getDeliveryAddressShipperId(final I_C_Order orderRecord) { final Optional<ShipperId> deliveryShipShipperId = partnerDAO.getShipperIdByBPLocationId( BPartnerLocationId.ofRepoId( orderRecord.getC_BPartner_ID(), orderRecord.getC_BPartner_Location_ID())); return deliveryShipShipperId.orElse(getPartnerShipperId(BPartnerId.ofRepoId(orderRecord.getC_BPartner_ID()))); } private ShipperId getPartnerShipperId(@NonNull final BPartnerId partnerId) { return partnerDAO.getShipperId(partnerId); }
@Override public PaymentTermId getPaymentTermId(@NonNull final I_C_Order orderRecord) { return PaymentTermId.ofRepoId(orderRecord.getC_PaymentTerm_ID()); } @Override public Money getGrandTotal(@NonNull final I_C_Order order) { final BigDecimal grandTotal = order.getGrandTotal(); return Money.of(grandTotal, CurrencyId.ofRepoId(order.getC_Currency_ID())); } @Override public void save(final I_C_Order order) { orderDAO.save(order); } @Override public void syncDatesFromTransportOrder(@NonNull final OrderId orderId, @NonNull final I_M_ShipperTransportation transportOrder) { final I_C_Order order = getById(orderId); order.setBLDate(transportOrder.getBLDate()); order.setETA(transportOrder.getETA()); save(order); } @Override public void syncDateInvoicedFromInvoice(@NonNull final OrderId orderId, @NonNull final I_C_Invoice invoice) { final I_C_Order order = getById(orderId); order.setInvoiceDate(invoice.getDateInvoiced()); save(order); } public List<I_C_Order> getByQueryFilter(final IQueryFilter<I_C_Order> queryFilter) { return orderDAO.getByQueryFilter(queryFilter); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.business\src\main\java\de\metas\order\impl\OrderBL.java
1
请在Spring Boot框架中完成以下Java代码
public List<FilterProperties> getFilters() { return filters; } public void setFilters(List<FilterProperties> filters) { this.filters = filters; } public @Nullable URI getUri() { return uri; } public void setUri(URI uri) { this.uri = uri; } public int getOrder() { return order; } public void setOrder(int order) { this.order = order; } public Map<String, Object> getMetadata() { return metadata; } public void setMetadata(Map<String, Object> metadata) { this.metadata = metadata;
} @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } RouteProperties that = (RouteProperties) o; return this.order == that.order && Objects.equals(this.id, that.id) && Objects.equals(this.predicates, that.predicates) && Objects.equals(this.filters, that.filters) && Objects.equals(this.uri, that.uri) && Objects.equals(this.metadata, that.metadata); } @Override public int hashCode() { return Objects.hash(this.id, this.predicates, this.filters, this.uri, this.metadata, this.order); } @Override public String toString() { return "RouteDefinition{" + "id='" + id + '\'' + ", predicates=" + predicates + ", filters=" + filters + ", uri=" + uri + ", order=" + order + ", metadata=" + metadata + '}'; } }
repos\spring-cloud-gateway-main\spring-cloud-gateway-server-webmvc\src\main\java\org\springframework\cloud\gateway\server\mvc\config\RouteProperties.java
2
请完成以下Java代码
public ProcessEngineConfigurationImpl setDmnFeelCustomFunctionProviders(List<FeelCustomFunctionProvider> dmnFeelCustomFunctionProviders) { this.dmnFeelCustomFunctionProviders = dmnFeelCustomFunctionProviders; return this; } public boolean isDmnFeelEnableLegacyBehavior() { return dmnFeelEnableLegacyBehavior; } public ProcessEngineConfigurationImpl setDmnFeelEnableLegacyBehavior(boolean dmnFeelEnableLegacyBehavior) { this.dmnFeelEnableLegacyBehavior = dmnFeelEnableLegacyBehavior; return this; } public boolean isDmnReturnBlankTableOutputAsNull() { return dmnReturnBlankTableOutputAsNull; } public ProcessEngineConfigurationImpl setDmnReturnBlankTableOutputAsNull(boolean dmnReturnBlankTableOutputAsNull) { this.dmnReturnBlankTableOutputAsNull = dmnReturnBlankTableOutputAsNull; return this; } public DiagnosticsCollector getDiagnosticsCollector() { return diagnosticsCollector; } public void setDiagnosticsCollector(DiagnosticsCollector diagnosticsCollector) { this.diagnosticsCollector = diagnosticsCollector; } public TelemetryDataImpl getTelemetryData() { return telemetryData; } public ProcessEngineConfigurationImpl setTelemetryData(TelemetryDataImpl telemetryData) { this.telemetryData = telemetryData; return this; } public boolean isReevaluateTimeCycleWhenDue() { return reevaluateTimeCycleWhenDue; } public ProcessEngineConfigurationImpl setReevaluateTimeCycleWhenDue(boolean reevaluateTimeCycleWhenDue) { this.reevaluateTimeCycleWhenDue = reevaluateTimeCycleWhenDue; return this; } public int getRemovalTimeUpdateChunkSize() { return removalTimeUpdateChunkSize; }
public ProcessEngineConfigurationImpl setRemovalTimeUpdateChunkSize(int removalTimeUpdateChunkSize) { this.removalTimeUpdateChunkSize = removalTimeUpdateChunkSize; return this; } /** * @return a exception code interceptor. The interceptor is not registered in case * {@code disableExceptionCode} is configured to {@code true}. */ protected ExceptionCodeInterceptor getExceptionCodeInterceptor() { return new ExceptionCodeInterceptor(builtinExceptionCodeProvider, customExceptionCodeProvider); } public DiagnosticsRegistry getDiagnosticsRegistry() { return diagnosticsRegistry; } public ProcessEngineConfiguration setDiagnosticsRegistry(DiagnosticsRegistry diagnosticsRegistry) { this.diagnosticsRegistry = diagnosticsRegistry; return this; } public boolean isLegacyJobRetryBehaviorEnabled() { return legacyJobRetryBehaviorEnabled; } public ProcessEngineConfiguration setLegacyJobRetryBehaviorEnabled(boolean legacyJobRetryBehaviorEnabled) { this.legacyJobRetryBehaviorEnabled = legacyJobRetryBehaviorEnabled; return this; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\cfg\ProcessEngineConfigurationImpl.java
1
请完成以下Java代码
public ProcessPreconditionsResolution checkPreconditionsApplicable() { final DocumentIdsSelection selectedRowIds = getSelectedRowIds(); if (selectedRowIds.isEmpty()) { return ProcessPreconditionsResolution.rejectBecauseNoSelection(); } return ProcessPreconditionsResolution.accept(); } @Override protected String doIt() { final Set<TableRecordReference> purchaseCandidateRefs = getSelectedRowIds() .stream() .map(DocumentId::toInt)
.map(recordId -> TableRecordReference.of(I_C_PurchaseCandidate.Table_Name, recordId)) .collect(ImmutableSet.toImmutableSet()); if (purchaseCandidateRefs.isEmpty()) { throw new AdempiereException("@NoSelection@"); } getResult().setRecordsToOpen( purchaseCandidateRefs, PurchaseCandidates2PurchaseViewFactory.WINDOW_ID_STRING); return MSG_OK; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\sales\purchasePlanning\process\WEBUI_PurchaseCandidates_PurchaseView_Launcher.java
1
请完成以下Java代码
public final void setBusyMessagePlain(final String message) { m_glassPane.setMessagePlain(message); } /** * Set and start Busy Counter * @param time in seconds */ public void setBusyTimer (int time) { m_glassPane.setBusyTimer (time); } // setBusyTimer /** * Set Maximize Window * @param max maximize */ public void setMaximize (boolean max) { m_maximize = max; } // setMaximize /** * Form Window Opened. * Maximize window if required * @param evt event */ private void formWindowOpened(java.awt.event.WindowEvent evt) { if (m_maximize == true) { super.setVisible(true); super.setExtendedState(JFrame.MAXIMIZED_BOTH); } } // formWindowOpened // Add window and tab no called from public void setProcessInfo(ProcessInfo pi) { m_pi = pi; } public ProcessInfo getProcessInfo() { return m_pi; } // End /** * Start Batch * @param process * @return running thread */ public Thread startBatch (final Runnable process)
{ Thread worker = new Thread() { @Override public void run() { setBusy(true); process.run(); setBusy(false); } }; worker.start(); return worker; } // startBatch /** * @return Returns the AD_Form_ID. */ public int getAD_Form_ID () { return p_AD_Form_ID; } // getAD_Window_ID public int getWindowNo() { return m_WindowNo; } /** * @return Returns the manuBar */ public JMenuBar getMenu() { return menuBar; } public void showFormWindow() { if (m_panel instanceof FormPanel2) { ((FormPanel2)m_panel).showFormWindow(m_WindowNo, this); } else { AEnv.showCenterScreenOrMaximized(this); } } } // FormFrame
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\client\src\main\java-legacy\org\compiere\apps\form\FormFrame.java
1
请在Spring Boot框架中完成以下Java代码
protected void configureTopology(@NonNull Environment environment, @NonNull ConnectionEndpointList connectionEndpoints, int connectionCount) { // do nothing! } } public static class CloudFoundryClusterAvailableCondition extends AbstractCloudPlatformAvailableCondition { protected static final String CLOUD_FOUNDRY_NAME = "CloudFoundry"; protected static final String RUNTIME_ENVIRONMENT_NAME = "VMware Tanzu GemFire for VMs"; @Override protected String getCloudPlatformName() { return CLOUD_FOUNDRY_NAME; } @Override protected String getRuntimeEnvironmentName() { return RUNTIME_ENVIRONMENT_NAME; } @Override protected boolean isCloudPlatformActive(@NonNull Environment environment) { return environment != null && CloudPlatform.CLOUD_FOUNDRY.isActive(environment); } } public static class KubernetesClusterAvailableCondition extends AbstractCloudPlatformAvailableCondition { protected static final String KUBERNETES_NAME = "Kubernetes"; protected static final String RUNTIME_ENVIRONMENT_NAME = "VMware Tanzu GemFire for K8S"; @Override protected String getCloudPlatformName() { return KUBERNETES_NAME; } @Override protected String getRuntimeEnvironmentName() { return RUNTIME_ENVIRONMENT_NAME; } @Override protected boolean isCloudPlatformActive(@NonNull Environment environment) { return environment != null && CloudPlatform.KUBERNETES.isActive(environment); } } public static class StandaloneClusterAvailableCondition extends ClusterAwareConfiguration.ClusterAwareCondition { @Override public synchronized boolean matches(@NonNull ConditionContext conditionContext,
@NonNull AnnotatedTypeMetadata typeMetadata) { return isNotSupportedCloudPlatform(conditionContext) && super.matches(conditionContext, typeMetadata); } private boolean isNotSupportedCloudPlatform(@NonNull ConditionContext conditionContext) { return conditionContext != null && isNotSupportedCloudPlatform(conditionContext.getEnvironment()); } private boolean isNotSupportedCloudPlatform(@NonNull Environment environment) { CloudPlatform activeCloudPlatform = environment != null ? CloudPlatform.getActive(environment) : null; return !isSupportedCloudPlatform(activeCloudPlatform); } private boolean isSupportedCloudPlatform(@NonNull CloudPlatform cloudPlatform) { return cloudPlatform != null && SUPPORTED_CLOUD_PLATFORMS.contains(cloudPlatform); } } }
repos\spring-boot-data-geode-main\spring-geode-project\spring-geode\src\main\java\org\springframework\geode\config\annotation\ClusterAvailableConfiguration.java
2
请完成以下Java代码
public IHUDisplayNameBuilder setIncludedHUCountSuffix(final String includedHUCountSuffix) { this.includedHUCountSuffix = includedHUCountSuffix; return this; } @Override public boolean isShowHUPINameNextLine() { return showHUPINameNextLine; } @Override public IHUDisplayNameBuilder setShowHUPINameNextLine(final boolean showHUPINameNextLine) { this.showHUPINameNextLine = showHUPINameNextLine; return this; } protected String getHUValue() { final I_M_HU hu = getM_HU(); String huValue = hu.getValue(); if (Check.isEmpty(huValue, true)) { huValue = String.valueOf(hu.getM_HU_ID()); } return huValue; } @Override public final String getPIName() { final I_M_HU hu = getM_HU(); final String piNameRaw; if (handlingUnitsBL.isAggregateHU(hu)) { piNameRaw = getAggregateHuPiName(hu); } else { final I_M_HU_PI pi = handlingUnitsBL.getPI(hu); piNameRaw = pi != null ? pi.getName() : "?"; } return escape(piNameRaw); } private String getAggregateHuPiName(final I_M_HU hu) { // note: if HU is an aggregate HU, then there won't be an NPE here. final I_M_HU_Item parentItem = hu.getM_HU_Item_Parent(); final I_M_HU_PI_Item parentPIItem = handlingUnitsBL.getPIItem(parentItem);
if (parentPIItem == null) { // new HUException("Aggregate HU's parent item has no M_HU_PI_Item; parent-item=" + parentItem) // .setParameter("parent M_HU_PI_Item_ID", parentItem != null ? parentItem.getM_HU_PI_Item_ID() : null) // .throwIfDeveloperModeOrLogWarningElse(logger); return "?"; } HuPackingInstructionsId includedPIId = HuPackingInstructionsId.ofRepoIdOrNull(parentPIItem.getIncluded_HU_PI_ID()); if (includedPIId == null) { //noinspection ThrowableNotThrown new HUException("Aggregate HU's parent item has M_HU_PI_Item without an Included_HU_PI; parent-item=" + parentItem).throwIfDeveloperModeOrLogWarningElse(logger); return "?"; } final I_M_HU_PI included_HU_PI = handlingUnitsBL.getPI(includedPIId); return included_HU_PI.getName(); } // NOTE: this method can be overridden by extending classes in order to optimize how the HUs are counted. @Override public int getIncludedHUsCount() { // NOTE: we need to iterate the HUs and count them (instead of doing a COUNT directly on database), // because we rely on HU&Items caching // and also because in case of aggregated HUs, we need special handling final IncludedHUsCounter includedHUsCounter = new IncludedHUsCounter(getM_HU()); final HUIterator huIterator = new HUIterator(); huIterator.setListener(includedHUsCounter.toHUIteratorListener()); huIterator.setEnableStorageIteration(false); huIterator.iterate(getM_HU()); return includedHUsCounter.getHUsCount(); } protected String escape(final String string) { return StringUtils.maskHTML(string); } @Override public IHUDisplayNameBuilder setShowIfDestroyed(final boolean showIfDestroyed) { this.showIfDestroyed = showIfDestroyed; return this; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.handlingunits.base\src\main\java\de\metas\handlingunits\impl\HUDisplayNameBuilder.java
1
请在Spring Boot框架中完成以下Java代码
public class StudentDaoImp implements StudentDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public int add(Student student) { // String sql = "insert into student(sno,sname,ssex) values(?,?,?)"; // Object[] args = { student.getSno(), student.getName(), student.getSex() }; // int[] argTypes = { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR }; // return this.jdbcTemplate.update(sql, args, argTypes); String sql = "insert into student(sno,sname,ssex) values(:sno,:name,:sex)"; NamedParameterJdbcTemplate npjt = new NamedParameterJdbcTemplate(this.jdbcTemplate.getDataSource()); return npjt.update(sql, new BeanPropertySqlParameterSource(student)); } @Override public int update(Student student) { String sql = "update student set sname = ?,ssex = ? where sno = ?"; Object[] args = { student.getName(), student.getSex(), student.getSno() }; int[] argTypes = { Types.VARCHAR, Types.VARCHAR, Types.VARCHAR }; return this.jdbcTemplate.update(sql, args, argTypes); } @Override public int deleteBysno(String sno) {
String sql = "delete from student where sno = ?"; Object[] args = { sno }; int[] argTypes = { Types.VARCHAR }; return this.jdbcTemplate.update(sql, args, argTypes); } @Override public List<Map<String, Object>> queryStudentsListMap() { String sql = "select * from student"; return this.jdbcTemplate.queryForList(sql); } @Override public Student queryStudentBySno(String sno) { String sql = "select * from student where sno = ?"; Object[] args = { sno }; int[] argTypes = { Types.VARCHAR }; List<Student> studentList = this.jdbcTemplate.query(sql, args, argTypes, new StudentMapper()); if (studentList != null && studentList.size() > 0) { return studentList.get(0); } else { return null; } } }
repos\SpringAll-master\04.Spring-Boot-JdbcTemplate\src\main\java\com\springboot\dao\impl\StudentDaoImp.java
2
请完成以下Java代码
public Map<String, TaskDefinition> getTaskDefinitions() { return taskDefinitions; } public void setTaskDefinitions(Map<String, TaskDefinition> taskDefinitions) { this.taskDefinitions = taskDefinitions; } public Map<String, Object> getVariables() { return variables; } public void setVariables(Map<String, Object> variables) { this.variables = variables; } @Override public String getCategory() { return category; } public void setCategory(String category) { this.category = category; } @Override public String getDiagramResourceName() { return diagramResourceName; } public void setDiagramResourceName(String diagramResourceName) { this.diagramResourceName = diagramResourceName; } @Override public boolean hasStartFormKey() { return hasStartFormKey; } public boolean getHasStartFormKey() { return hasStartFormKey; } public void setStartFormKey(boolean hasStartFormKey) { this.hasStartFormKey = hasStartFormKey; } public void setHasStartFormKey(boolean hasStartFormKey) { this.hasStartFormKey = hasStartFormKey; } public boolean isGraphicalNotationDefined() { return isGraphicalNotationDefined; } @Override public boolean hasGraphicalNotation() { return isGraphicalNotationDefined; } public void setGraphicalNotationDefined(boolean isGraphicalNotationDefined) { this.isGraphicalNotationDefined = isGraphicalNotationDefined; } @Override public int getRevision() { return revision; } @Override public void setRevision(int revision) { this.revision = revision; } @Override public int getRevisionNext() {
return revision + 1; } public int getSuspensionState() { return suspensionState; } public void setSuspensionState(int suspensionState) { this.suspensionState = suspensionState; } @Override public boolean isSuspended() { return suspensionState == SuspensionState.SUSPENDED.getStateCode(); } public Set<Expression> getCandidateStarterUserIdExpressions() { return candidateStarterUserIdExpressions; } public void addCandidateStarterUserIdExpression(Expression userId) { candidateStarterUserIdExpressions.add(userId); } public Set<Expression> getCandidateStarterGroupIdExpressions() { return candidateStarterGroupIdExpressions; } public void addCandidateStarterGroupIdExpression(Expression groupId) { candidateStarterGroupIdExpressions.add(groupId); } @Override public String getEngineVersion() { return engineVersion; } public void setEngineVersion(String engineVersion) { this.engineVersion = engineVersion; } }
repos\flowable-engine-main\modules\flowable5-engine\src\main\java\org\activiti\engine\impl\persistence\entity\ProcessDefinitionEntity.java
1
请完成以下Java代码
public abstract class DebugMailRestControllerTemplate { @NonNull private final MailService mailService; protected abstract void assertAuth(); protected abstract UserId getLoggedUserId(); protected abstract boolean isLoggedInAsSysAdmin(); @GetMapping("/send") public ResponseEntity<String> sendMail( @RequestParam(name = "AD_Client_ID", required = false, defaultValue = "-1") int adClientId, @RequestParam(name = "AD_Org_ID", required = false, defaultValue = "-1") int adOrgId, @RequestParam(name = "AD_Process_ID", required = false, defaultValue = "-1") int adProcessId, @RequestParam(name = "EMailCustomType", required = false) String emailCustomType, @RequestParam(name = "From_User_ID", required = false, defaultValue = "-1") int fromUserRepoId, @RequestParam(name = "to") String to, @RequestParam(name = "subject", required = false) String subject, @RequestParam(name = "message", required = false) String message, @RequestParam(name = "isHtml", required = false, defaultValue = "false") boolean isHtml) { assertAuth(); final PlainStringLoggable loggable = Loggables.newPlainStringLoggable(); final TestMailRequest request = TestMailRequest.builder() .clientId(adClientId >= 0 ? ClientId.ofRepoId(adClientId) : ClientId.METASFRESH) .orgId(OrgId.ofRepoIdOrAny(adOrgId)) .processId(AdProcessId.ofRepoIdOrNull(adProcessId)) .emailCustomType(EMailCustomType.ofNullableCode(emailCustomType)) .fromUserId(UserId.ofRepoIdOrNull(fromUserRepoId)) .mailTo(EMailAddress.ofString(to)) .subject(subject)
.message(message) .isHtml(isHtml) .loggable(loggable) .build(); assertPermissions(request); mailService.test(request); return ResponseEntity.ok() .contentType(MediaType.TEXT_PLAIN) .body(loggable.getConcatenatedMessages()); } private void assertPermissions(@NonNull final TestMailRequest request) { if (isLoggedInAsSysAdmin()) { return; } final UserId fromUserId = request.getFromUserId(); if (fromUserId != null && !UserId.equals(fromUserId, getLoggedUserId())) { throw new AdempiereException("From_User_ID must be either not set/negative or " + getLoggedUserId().getRepoId()); } if (!ClientId.equals(request.getClientId(), ClientId.METASFRESH)) { throw new AdempiereException("AD_Client_ID must be either not set/negative or " + ClientId.METASFRESH.getRepoId()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\email\rest\DebugMailRestControllerTemplate.java
1
请完成以下Java代码
public class ExecutionRequestObservationContext extends Observation.Context { private final ExecutionInput executionInput; private @Nullable ExecutionContext executionContext; private @Nullable ExecutionResult executionResult; public ExecutionRequestObservationContext(ExecutionInput executionInput) { this.executionInput = executionInput; } /** * Return the {@link ExecutionInput input} for the request execution. * @since 1.1.4 */ public ExecutionInput getExecutionInput() { return this.executionInput; } /** * Return the {@link ExecutionContext context} for the request execution. * @since 1.3.7 */ public @Nullable ExecutionContext getExecutionContext() { return this.executionContext; } /** * Set the {@link ExecutionContext context} for the request execution. * @param executionContext the execution context * @since 1.3.7 */ public void setExecutionContext(ExecutionContext executionContext) { this.executionContext = executionContext; }
/** * Return the {@link ExecutionResult result} for the request execution. * @since 1.1.4 */ public @Nullable ExecutionResult getExecutionResult() { return this.executionResult; } /** * Set the {@link ExecutionResult result} for the request execution. * @param executionResult the execution result * @since 1.1.4 */ public void setExecutionResult(ExecutionResult executionResult) { this.executionResult = executionResult; } }
repos\spring-graphql-main\spring-graphql\src\main\java\org\springframework\graphql\observation\ExecutionRequestObservationContext.java
1
请完成以下Java代码
public void setA_Ins_Premium (BigDecimal A_Ins_Premium) { set_Value (COLUMNNAME_A_Ins_Premium, A_Ins_Premium); } /** Get Insurance Premium. @return Insurance Premium */ public BigDecimal getA_Ins_Premium () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Ins_Premium); if (bd == null) return Env.ZERO; return bd; } /** Set Insurance Company. @param A_Insurance_Co Insurance Company */ public void setA_Insurance_Co (String A_Insurance_Co) { set_Value (COLUMNNAME_A_Insurance_Co, A_Insurance_Co); } /** Get Insurance Company. @return Insurance Company */ public String getA_Insurance_Co () { return (String)get_Value(COLUMNNAME_A_Insurance_Co); } /** Set Insured Value. @param A_Ins_Value Insured Value */ public void setA_Ins_Value (BigDecimal A_Ins_Value) { set_Value (COLUMNNAME_A_Ins_Value, A_Ins_Value); } /** Get Insured Value. @return Insured Value */ public BigDecimal getA_Ins_Value () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Ins_Value); if (bd == null) return Env.ZERO; return bd; } /** Set Policy Number. @param A_Policy_No Policy Number */ public void setA_Policy_No (String A_Policy_No) { set_Value (COLUMNNAME_A_Policy_No, A_Policy_No); } /** Get Policy Number. @return Policy Number */ public String getA_Policy_No () { return (String)get_Value(COLUMNNAME_A_Policy_No); }
/** Set Policy Renewal Date. @param A_Renewal_Date Policy Renewal Date */ public void setA_Renewal_Date (Timestamp A_Renewal_Date) { set_Value (COLUMNNAME_A_Renewal_Date, A_Renewal_Date); } /** Get Policy Renewal Date. @return Policy Renewal Date */ public Timestamp getA_Renewal_Date () { return (Timestamp)get_Value(COLUMNNAME_A_Renewal_Date); } /** Set Replacement Costs. @param A_Replace_Cost Replacement Costs */ public void setA_Replace_Cost (BigDecimal A_Replace_Cost) { set_Value (COLUMNNAME_A_Replace_Cost, A_Replace_Cost); } /** Get Replacement Costs. @return Replacement Costs */ public BigDecimal getA_Replace_Cost () { BigDecimal bd = (BigDecimal)get_Value(COLUMNNAME_A_Replace_Cost); if (bd == null) return Env.ZERO; return bd; } /** Set Text. @param Text Text */ public void setText (String Text) { set_Value (COLUMNNAME_Text, Text); } /** Get Text. @return Text */ public String getText () { return (String)get_Value(COLUMNNAME_Text); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_A_Asset_Info_Ins.java
1
请在Spring Boot框架中完成以下Java代码
public void setPhone(String phone) { this.phone = phone; } public String getIdNo() { return idNo; } public void setIdNo(String idNo) { this.idNo = idNo; } public String getBankAccountNo() { return bankAccountNo; } public void setBankAccountNo(String bankAccountNo) { this.bankAccountNo = bankAccountNo; } public String getOpenId() { return openId; } public void setOpenId(String openId) { this.openId = openId; } public String getPayWayCode() { return payWayCode; } public void setPayWayCode(String payWayCode) { this.payWayCode = payWayCode; }
public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } public String getSign() { return sign; } public void setSign(String sign) { this.sign = sign; } }
repos\roncoo-pay-master\roncoo-pay-service\src\main\java\com\roncoo\pay\trade\vo\AuthProgramInitParamVo.java
2
请在Spring Boot框架中完成以下Java代码
private Retry createRetrySpec() { return Retry.backoff(Long.MAX_VALUE, Duration.ofSeconds(1)) .maxBackoff(maxBackoff) .doBeforeRetry((s) -> this.retryConsumer.accept(s.failure())); } public void markAsChecked(InstanceId instanceId) { this.lastChecked.put(instanceId, Instant.now()); } protected Publisher<Void> checkAllInstances() { log.debug("check {} for all instances", this.name); Instant expiration = Instant.now().minus(this.minRetention); return Flux.fromIterable(this.lastChecked.entrySet()) .filter((entry) -> entry.getValue().isBefore(expiration)) .map(Map.Entry::getKey)
.flatMap(this.checkFn) .then(); } public void stop() { if (this.subscription != null) { this.subscription.dispose(); this.subscription = null; } if (this.scheduler != null) { this.scheduler.dispose(); this.scheduler = null; } } }
repos\spring-boot-admin-master\spring-boot-admin-server\src\main\java\de\codecentric\boot\admin\server\services\IntervalCheck.java
2
请在Spring Boot框架中完成以下Java代码
public @Nullable String getApiKey() { return this.apiKey; } public void setApiKey(@Nullable String apiKey) { this.apiKey = apiKey; } public Duration getConnectionTimeout() { return this.connectionTimeout; } public void setConnectionTimeout(Duration connectionTimeout) { this.connectionTimeout = connectionTimeout; } public Duration getSocketTimeout() { return this.socketTimeout; } public void setSocketTimeout(Duration socketTimeout) { this.socketTimeout = socketTimeout; } public boolean isSocketKeepAlive() { return this.socketKeepAlive; } public void setSocketKeepAlive(boolean socketKeepAlive) { this.socketKeepAlive = socketKeepAlive; } public @Nullable String getPathPrefix() { return this.pathPrefix; } public void setPathPrefix(@Nullable String pathPrefix) { this.pathPrefix = pathPrefix; } public Restclient getRestclient() { return this.restclient; } public static class Restclient { private final Sniffer sniffer = new Sniffer(); private final Ssl ssl = new Ssl(); public Sniffer getSniffer() { return this.sniffer; } public Ssl getSsl() { return this.ssl; } public static class Sniffer { /** * Whether the sniffer is enabled. */ private boolean enabled;
/** * Interval between consecutive ordinary sniff executions. */ private Duration interval = Duration.ofMinutes(5); /** * Delay of a sniff execution scheduled after a failure. */ private Duration delayAfterFailure = Duration.ofMinutes(1); public boolean isEnabled() { return this.enabled; } public void setEnabled(boolean enabled) { this.enabled = enabled; } public Duration getInterval() { return this.interval; } public void setInterval(Duration interval) { this.interval = interval; } public Duration getDelayAfterFailure() { return this.delayAfterFailure; } public void setDelayAfterFailure(Duration delayAfterFailure) { this.delayAfterFailure = delayAfterFailure; } } public static class Ssl { /** * SSL bundle name. */ private @Nullable String bundle; public @Nullable String getBundle() { return this.bundle; } public void setBundle(@Nullable String bundle) { this.bundle = bundle; } } } }
repos\spring-boot-4.0.1\module\spring-boot-elasticsearch\src\main\java\org\springframework\boot\elasticsearch\autoconfigure\ElasticsearchProperties.java
2
请完成以下Java代码
public int getModifiers() { return this.modifiers; } /** * Return the name. * @return the name */ public String getName() { return this.name; } /** * Return the return type. * @return the return type */ public String getReturnType() { return this.returnType; } /** * Return the value. * @return the value */ public Object getValue() { return this.value; } /** * Whether the field declaration is initialized. * @return whether the field declaration is initialized */ public boolean isInitialized() { return this.initialized; } /** * Builder for {@link GroovyFieldDeclaration}. */ public static final class Builder { private final String name; private String returnType; private int modifiers; private Object value; private boolean initialized; private Builder(String name) { this.name = name;
} /** * Sets the modifiers. * @param modifiers the modifiers * @return this for method chaining */ public Builder modifiers(int modifiers) { this.modifiers = modifiers; return this; } /** * Sets the value. * @param value the value * @return this for method chaining */ public Builder value(Object value) { this.value = value; this.initialized = true; return this; } /** * Sets the return type. * @param returnType the return type * @return the field */ public GroovyFieldDeclaration returning(String returnType) { this.returnType = returnType; return new GroovyFieldDeclaration(this); } } }
repos\initializr-main\initializr-generator\src\main\java\io\spring\initializr\generator\language\groovy\GroovyFieldDeclaration.java
1
请在Spring Boot框架中完成以下Java代码
public String getDocumentPositionNumber() { return documentPositionNumber; } /** * Sets the value of the documentPositionNumber property. * * @param value * allowed object is * {@link String } * */ public void setDocumentPositionNumber(String value) { this.documentPositionNumber = value; } /** * Reference date of the document. Typcially this element refers to the document date of the preceding document. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getReferenceDate() { return referenceDate; } /** * Sets the value of the referenceDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setReferenceDate(XMLGregorianCalendar value) { this.referenceDate = value; } /** * An optional description in free-text or a specification of the reference type for the DocumentType 'DocumentReference'. *
* @return * possible object is * {@link DescriptionType } * */ public DescriptionType getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link DescriptionType } * */ public void setDescription(DescriptionType value) { this.description = value; } }
repos\metasfresh-new_dawn_uat\misc\services\camel\de-metas-camel-edi\src\main\java-xjc_ecosio_remadv\at\erpel\schemas\_1p0\documents\DocumentReferenceType.java
2
请完成以下Java代码
public TypedValue createValue(Object value, Map<String, Object> valueInfo) { if (valueInfo == null) { throw new IllegalArgumentException("Cannot create file without valueInfo."); } Object filename = valueInfo.get(VALUE_INFO_FILE_NAME); if (filename == null) { throw new IllegalArgumentException("Cannot create file without filename! Please set a name into ValueInfo with key " + VALUE_INFO_FILE_NAME); } FileValueBuilder builder = Variables.fileValue(filename.toString()); if (value instanceof File) { builder.file((File) value); } else if (value instanceof InputStream) { builder.file((InputStream) value); } else if (value instanceof byte[]) { builder.file((byte[]) value); } else { throw new IllegalArgumentException("Provided value is not of File, InputStream or byte[] type."); } if (valueInfo.containsKey(VALUE_INFO_FILE_MIME_TYPE)) { Object mimeType = valueInfo.get(VALUE_INFO_FILE_MIME_TYPE); if (mimeType == null) { throw new IllegalArgumentException("The provided mime type is null. Set a non-null value info property with key '" + VALUE_INFO_FILE_NAME + "'"); } builder.mimeType(mimeType.toString()); } if (valueInfo.containsKey(VALUE_INFO_FILE_ENCODING)) { Object encoding = valueInfo.get(VALUE_INFO_FILE_ENCODING); if (encoding == null) { throw new IllegalArgumentException("The provided encoding is null. Set a non-null value info property with key '" + VALUE_INFO_FILE_ENCODING + "'"); } builder.encoding(encoding.toString()); }
builder.setTransient(isTransient(valueInfo)); return builder.create(); } @Override public Map<String, Object> getValueInfo(TypedValue typedValue) { if (!(typedValue instanceof FileValue)) { throw new IllegalArgumentException("Value not of type FileValue"); } FileValue fileValue = (FileValue) typedValue; Map<String, Object> result = new HashMap<String, Object>(2); result.put(VALUE_INFO_FILE_NAME, fileValue.getFilename()); if (fileValue.getMimeType() != null) { result.put(VALUE_INFO_FILE_MIME_TYPE, fileValue.getMimeType()); } if (fileValue.getEncoding() != null) { result.put(VALUE_INFO_FILE_ENCODING, fileValue.getEncoding()); } if (fileValue.isTransient()) { result.put(VALUE_INFO_TRANSIENT, fileValue.isTransient()); } return result; } @Override public boolean isPrimitiveValueType() { return true; } }
repos\camunda-bpm-platform-master\commons\typed-values\src\main\java\org\camunda\bpm\engine\variable\impl\type\FileValueTypeImpl.java
1
请完成以下Java代码
int[] getBuffer() { return _buf; } int get(int id) { return _buf[id]; } void set(int id, int value) { _buf[id] = value; } boolean empty() { return (_size == 0); } int size() { return _size; } void clear() { resize(0); _buf = null; _size = 0; _capacity = 0; } void add(int value) { if (_size == _capacity) { resizeBuf(_size + 1); } _buf[_size++] = value; } void deleteLast() { --_size; } void resize(int size) { if (size > _capacity) { resizeBuf(size); } _size = size; }
void resize(int size, int value) { if (size > _capacity) { resizeBuf(size); } while (_size < size) { _buf[_size++] = value; } } void reserve(int size) { if (size > _capacity) { resizeBuf(size); } } private void resizeBuf(int size) { int capacity; if (size >= _capacity * 2) { capacity = size; } else { capacity = 1; while (capacity < size) { capacity <<= 1; } } int[] buf = new int[capacity]; if (_size > 0) { System.arraycopy(_buf, 0, buf, 0, _size); } _buf = buf; _capacity = capacity; } private int[] _buf; private int _size; private int _capacity; }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\collection\dartsclone\details\AutoIntPool.java
1
请在Spring Boot框架中完成以下Java代码
protected void startTimerJobAcquisitionForTenant(String tenantId) { timerJobAcquisitionThreads.get(tenantId).start(); } protected void startAsyncJobAcquisitionForTenant(String tenantId) { asyncJobAcquisitionThreads.get(tenantId).start(); } protected void startResetExpiredJobsForTenant(String tenantId) { resetExpiredJobsThreads.get(tenantId).start(); } @Override protected void stopJobAcquisitionThread() { for (String tenantId : timerJobAcquisitionRunnables.keySet()) { stopThreadsForTenant(tenantId); } } protected void stopThreadsForTenant(String tenantId) { timerJobAcquisitionRunnables.get(tenantId).stop(); asyncJobAcquisitionRunnables.get(tenantId).stop(); resetExpiredJobsRunnables.get(tenantId).stop(); try { timerJobAcquisitionThreads.get(tenantId).join(); } catch (InterruptedException e) {
LOGGER.warn("Interrupted while waiting for the timer job acquisition thread to terminate", e); } try { asyncJobAcquisitionThreads.get(tenantId).join(); } catch (InterruptedException e) { LOGGER.warn("Interrupted while waiting for the timer job acquisition thread to terminate", e); } try { resetExpiredJobsThreads.get(tenantId).join(); } catch (InterruptedException e) { LOGGER.warn("Interrupted while waiting for the reset expired jobs thread to terminate", e); } } }
repos\flowable-engine-main\modules\flowable-job-service\src\main\java\org\flowable\job\service\impl\asyncexecutor\multitenant\SharedExecutorServiceAsyncExecutor.java
2
请完成以下Java代码
public boolean isOnlyApprovedForInvoicing() { return params.getParameterAsBool(PARA_OnlyApprovedForInvoicing); } @Override public boolean isConsolidateApprovedICs() { return params.getParameterAsBool(PARA_IsConsolidateApprovedICs); } @Override public boolean isIgnoreInvoiceSchedule() { return params.getParameterAsBool(PARA_IgnoreInvoiceSchedule); } @Override public boolean isUpdateLocationAndContactForInvoice() { return params.getParameterAsBool(PARA_IsUpdateLocationAndContactForInvoice); } @Override public LocalDate getDateInvoiced() { return params.getParameterAsLocalDate(PARA_DateInvoiced); } @Override public LocalDate getDateAcct() { return params.getParameterAsLocalDate(PARA_DateAcct); } @Override
public String getPOReference() { return params.getParameterAsString(PARA_POReference); } @Override public BigDecimal getCheck_NetAmtToInvoice() { return params.getParameterAsBigDecimal(PARA_Check_NetAmtToInvoice); } /** * Always returns {@code false}. */ @Override public boolean isAssumeOneInvoice() { return false; } @Override public boolean isCompleteInvoices() { return params.getParameterAsBoolean(PARA_IsCompleteInvoices, true /*true for backwards-compatibility*/); } /** * Always returns {@code false}. */ @Override public boolean isStoreInvoicesInResult() { return false; } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\api\impl\InvoicingParams.java
1
请完成以下Java代码
public Map<String, Object> convert(OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse) { Map<String, Object> parameters = new HashMap<>(); parameters.put(OAuth2ParameterNames.DEVICE_CODE, deviceAuthorizationResponse.getDeviceCode().getTokenValue()); parameters.put(OAuth2ParameterNames.USER_CODE, deviceAuthorizationResponse.getUserCode().getTokenValue()); parameters.put(OAuth2ParameterNames.VERIFICATION_URI, deviceAuthorizationResponse.getVerificationUri()); if (StringUtils.hasText(deviceAuthorizationResponse.getVerificationUriComplete())) { parameters.put(OAuth2ParameterNames.VERIFICATION_URI_COMPLETE, deviceAuthorizationResponse.getVerificationUriComplete()); } parameters.put(OAuth2ParameterNames.EXPIRES_IN, getExpiresIn(deviceAuthorizationResponse)); if (deviceAuthorizationResponse.getInterval() > 0) { parameters.put(OAuth2ParameterNames.INTERVAL, deviceAuthorizationResponse.getInterval()); } if (!CollectionUtils.isEmpty(deviceAuthorizationResponse.getAdditionalParameters())) { parameters.putAll(deviceAuthorizationResponse.getAdditionalParameters());
} return parameters; } private static long getExpiresIn(OAuth2DeviceAuthorizationResponse deviceAuthorizationResponse) { if (deviceAuthorizationResponse.getDeviceCode().getExpiresAt() != null) { Instant issuedAt = (deviceAuthorizationResponse.getDeviceCode().getIssuedAt() != null) ? deviceAuthorizationResponse.getDeviceCode().getIssuedAt() : Instant.now(); return ChronoUnit.SECONDS.between(issuedAt, deviceAuthorizationResponse.getDeviceCode().getExpiresAt()); } return -1; } } }
repos\spring-security-main\oauth2\oauth2-core\src\main\java\org\springframework\security\oauth2\core\http\converter\OAuth2DeviceAuthorizationResponseHttpMessageConverter.java
1
请完成以下Java代码
public DecisionRequirementsDefinition getDecisionRequirementsDefinition(String decisionRequirementsDefinitionId) { try { return commandExecutor.execute(new GetDeploymentDecisionRequirementsDefinitionCmd(decisionRequirementsDefinitionId)); } catch (NullValueException e) { throw new NotValidException(e.getMessage(), e); } catch (DecisionDefinitionNotFoundException e) { throw new NotFoundException(e.getMessage(), e); } } public InputStream getDecisionModel(String decisionDefinitionId) { try { return commandExecutor.execute(new GetDeploymentDecisionModelCmd(decisionDefinitionId)); } catch (NullValueException e) { throw new NotValidException(e.getMessage(), e); } catch (DecisionDefinitionNotFoundException e) { throw new NotFoundException(e.getMessage(), e); } catch (DeploymentResourceNotFoundException e) { throw new NotFoundException(e.getMessage(), e); } } public InputStream getDecisionRequirementsModel(String decisionRequirementsDefinitionId) { try { return commandExecutor.execute(new GetDeploymentDecisionRequirementsModelCmd(decisionRequirementsDefinitionId)); } catch (NullValueException e) { throw new NotValidException(e.getMessage(), e); } catch (DecisionDefinitionNotFoundException e) { throw new NotFoundException(e.getMessage(), e);
} catch (DeploymentResourceNotFoundException e) { throw new NotFoundException(e.getMessage(), e); } } public InputStream getDecisionDiagram(String decisionDefinitionId) { return commandExecutor.execute(new GetDeploymentDecisionDiagramCmd(decisionDefinitionId)); } public InputStream getDecisionRequirementsDiagram(String decisionRequirementsDefinitionId) { return commandExecutor.execute(new GetDeploymentDecisionRequirementsDiagramCmd(decisionRequirementsDefinitionId)); } @Override public Collection<CalledProcessDefinition> getStaticCalledProcessDefinitions(String processDefinitionId) { return commandExecutor.execute(new GetStaticCalledProcessDefinitionCmd(processDefinitionId)); } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\RepositoryServiceImpl.java
1
请在Spring Boot框架中完成以下Java代码
public class DictWrapper extends BaseEntityWrapper<Dict, DictVO> { private static IDictService dictService; static { dictService = SpringUtil.getBean(IDictService.class); } public static DictWrapper build() { return new DictWrapper(); } @Override public DictVO entityVO(Dict dict) { DictVO dictVO = BeanUtil.copyProperties(dict, DictVO.class);
if (Func.equals(dict.getParentId(), CommonConstant.TOP_PARENT_ID)) { dictVO.setParentName(CommonConstant.TOP_PARENT_NAME); } else { Dict parent = dictService.getById(dict.getParentId()); dictVO.setParentName(parent.getDictValue()); } return dictVO; } public List<DictVO> listNodeVO(List<Dict> list) { List<DictVO> collect = list.stream().map(dict -> BeanUtil.copyProperties(dict, DictVO.class)).collect(Collectors.toList()); return ForestNodeMerger.merge(collect); } }
repos\SpringBlade-master\blade-service\blade-system\src\main\java\org\springblade\system\wrapper\DictWrapper.java
2
请完成以下Java代码
public static class ToInvoiceExclOverride { enum InvoicedQtys { SUBTRACTED, NOT_SUBTRACTED } InvoicedQtys invoicedQtys; /** * Excluding possible receipt quantities with quality issues */ StockQtyAndUOMQty qtysRaw; /** * Computed including possible receipt quality issues, not overridden by a possible qtyToInvoice override.
*/ StockQtyAndUOMQty qtysCalc; private ToInvoiceExclOverride( @NonNull final InvoicedQtys invoicedQtys, @NonNull final StockQtyAndUOMQty qtysRaw, @NonNull final StockQtyAndUOMQty qtysCalc) { this.qtysRaw = qtysRaw; this.qtysCalc = qtysCalc; this.invoicedQtys = invoicedQtys; StockQtyAndUOMQtys.assumeCommonProductAndUom(qtysRaw, qtysCalc); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java\de\metas\invoicecandidate\internalbusinesslogic\InvoiceCandidate.java
1
请完成以下Java代码
public void setDefaultTimerJobAcquireWaitTimeInMillis(int waitTimeInMillis) { for (AsyncExecutor asyncExecutor : tenantExecutors.values()) { asyncExecutor.setDefaultTimerJobAcquireWaitTimeInMillis(waitTimeInMillis); } } public int getDefaultAsyncJobAcquireWaitTimeInMillis() { return determineAsyncExecutor().getDefaultAsyncJobAcquireWaitTimeInMillis(); } public void setDefaultAsyncJobAcquireWaitTimeInMillis(int waitTimeInMillis) { for (AsyncExecutor asyncExecutor : tenantExecutors.values()) { asyncExecutor.setDefaultAsyncJobAcquireWaitTimeInMillis(waitTimeInMillis); } } public int getDefaultQueueSizeFullWaitTimeInMillis() { return determineAsyncExecutor().getDefaultQueueSizeFullWaitTimeInMillis(); } public void setDefaultQueueSizeFullWaitTimeInMillis(int defaultQueueSizeFullWaitTimeInMillis) { for (AsyncExecutor asyncExecutor : tenantExecutors.values()) { asyncExecutor.setDefaultQueueSizeFullWaitTimeInMillis(defaultQueueSizeFullWaitTimeInMillis); } } public int getMaxAsyncJobsDuePerAcquisition() { return determineAsyncExecutor().getMaxAsyncJobsDuePerAcquisition(); } public void setMaxAsyncJobsDuePerAcquisition(int maxJobs) { for (AsyncExecutor asyncExecutor : tenantExecutors.values()) { asyncExecutor.setMaxAsyncJobsDuePerAcquisition(maxJobs); } } public int getMaxTimerJobsPerAcquisition() { return determineAsyncExecutor().getMaxTimerJobsPerAcquisition(); } public void setMaxTimerJobsPerAcquisition(int maxJobs) { for (AsyncExecutor asyncExecutor : tenantExecutors.values()) { asyncExecutor.setMaxTimerJobsPerAcquisition(maxJobs); } } public int getRetryWaitTimeInMillis() { return determineAsyncExecutor().getRetryWaitTimeInMillis(); } public void setRetryWaitTimeInMillis(int retryWaitTimeInMillis) { for (AsyncExecutor asyncExecutor : tenantExecutors.values()) { asyncExecutor.setRetryWaitTimeInMillis(retryWaitTimeInMillis);
} } @Override public int getResetExpiredJobsInterval() { return determineAsyncExecutor().getResetExpiredJobsInterval(); } @Override public void setResetExpiredJobsInterval(int resetExpiredJobsInterval) { for (AsyncExecutor asyncExecutor : tenantExecutors.values()) { asyncExecutor.setResetExpiredJobsInterval(resetExpiredJobsInterval); } } @Override public int getResetExpiredJobsPageSize() { return determineAsyncExecutor().getResetExpiredJobsPageSize(); } @Override public void setResetExpiredJobsPageSize(int resetExpiredJobsPageSize) { for (AsyncExecutor asyncExecutor : tenantExecutors.values()) { asyncExecutor.setResetExpiredJobsPageSize(resetExpiredJobsPageSize); } } }
repos\Activiti-develop\activiti-core\activiti-engine\src\main\java\org\activiti\engine\impl\asyncexecutor\multitenant\ExecutorPerTenantAsyncExecutor.java
1
请完成以下Java代码
private static ObjectMapper createObjectMapper() { ObjectMapper mapper = new ObjectMapper(); mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); return mapper; } // For testing purposes only protected RestTemplate getRestTemplate() { return this.restTemplate; } protected void updateRequestUrl(URI requestUrl) { this.requestUrl = requestUrl; } private static RestTemplateBuilder configureAuthorization(RestTemplateBuilder restTemplateBuilder, Elastic elastic, UriComponentsBuilder uriComponentsBuilder) { String userInfo = uriComponentsBuilder.build().getUserInfo(); if (StringUtils.hasText(userInfo)) { String[] credentials = userInfo.split(":"); return restTemplateBuilder.basicAuthentication(credentials[0], credentials[1]); }
else if (StringUtils.hasText(elastic.getUsername())) { return restTemplateBuilder.basicAuthentication(elastic.getUsername(), elastic.getPassword()); } return restTemplateBuilder; } private static URI determineEntityUrl(Elastic elastic) { String entityUrl = elastic.getUri() + "/" + elastic.getIndexName() + "/_doc/"; try { return new URI(entityUrl); } catch (URISyntaxException ex) { throw new IllegalStateException("Cannot create entity URL: " + entityUrl, ex); } } }
repos\initializr-main\initializr-actuator\src\main\java\io\spring\initializr\actuate\stat\ProjectGenerationStatPublisher.java
1
请完成以下Java代码
private static class OrderLineBasePricingSystemPriceCalculator implements BasePricingSystemPriceCalculator { private final IOrderLineBL orderLineBL = Services.get(IOrderLineBL.class); private final I_C_OrderLine orderLine; private final ConcurrentHashMap<PricingConditionsBreak, Money> basePricesCache = new ConcurrentHashMap<>(); public OrderLineBasePricingSystemPriceCalculator(@NonNull final I_C_OrderLine orderLine) { this.orderLine = orderLine; } @Override public Money calculate(final BasePricingSystemPriceCalculatorRequest request) {
final PricingConditionsBreak pricingConditionsBreak = request.getPricingConditionsBreak(); return basePricesCache.computeIfAbsent(pricingConditionsBreak, this::calculate); } private Money calculate(final PricingConditionsBreak pricingConditionsBreak) { final IPricingResult pricingResult = orderLineBL.computePrices(OrderLinePriceUpdateRequest.builder() .orderLine(orderLine) .pricingConditionsBreakOverride(pricingConditionsBreak) .resultUOM(ResultUOM.PRICE_UOM_IF_ORDERLINE_IS_NEW) .build()); return Money.of(pricingResult.getPriceStd(), pricingResult.getCurrencyId()); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\order\pricingconditions\view\OrderLinePricingConditionsViewFactory.java
1
请完成以下Java代码
public void onMessage(ConsumerRecord receivedRecord, @Nullable Acknowledgment acknowledgment, @Nullable Consumer consumer) { ConsumerRecord convertedConsumerRecord = convertConsumerRecord(receivedRecord); if (this.delegate instanceof AcknowledgingConsumerAwareMessageListener) { this.delegate.onMessage(convertedConsumerRecord, acknowledgment, consumer); } else if (this.delegate instanceof ConsumerAwareMessageListener) { this.delegate.onMessage(convertedConsumerRecord, consumer); } else if (this.delegate instanceof AcknowledgingMessageListener) { this.delegate.onMessage(convertedConsumerRecord, acknowledgment); } else { this.delegate.onMessage(convertedConsumerRecord); } } private ConsumerRecord convertConsumerRecord(ConsumerRecord receivedRecord) { Map<String, Object> headerMap = new HashMap<>(); if (this.headerMapper != null) { this.headerMapper.toHeaders(receivedRecord.headers(), headerMap); } Message message = new GenericMessage<>(receivedRecord.value(), headerMap); Object convertedPayload = this.messageConverter.fromMessage(message, this.desiredValueType); if (convertedPayload == null) { throw new MessageConversionException(message, "Message cannot be converted by used MessageConverter"); } return rebuildConsumerRecord(receivedRecord, convertedPayload); }
@SuppressWarnings("unchecked") private static ConsumerRecord rebuildConsumerRecord(ConsumerRecord receivedRecord, Object convertedPayload) { return new ConsumerRecord( receivedRecord.topic(), receivedRecord.partition(), receivedRecord.offset(), receivedRecord.timestamp(), receivedRecord.timestampType(), receivedRecord.serializedKeySize(), receivedRecord.serializedValueSize(), receivedRecord.key(), convertedPayload, receivedRecord.headers(), receivedRecord.leaderEpoch() ); } }
repos\spring-kafka-main\spring-kafka\src\main\java\org\springframework\kafka\listener\adapter\ConvertingMessageListener.java
1
请完成以下Java代码
public final class HttpMessageConverterAuthenticationSuccessHandler implements AuthenticationSuccessHandler { private HttpMessageConverter<Object> converter = new MappingJackson2HttpMessageConverter(); private RequestCache requestCache = new HttpSessionRequestCache(); /** * Sets the {@link GenericHttpMessageConverter} to write to the response. The default * is {@link MappingJackson2HttpMessageConverter}. * @param converter the {@link GenericHttpMessageConverter} to use. Cannot be null. */ public void setConverter(HttpMessageConverter<Object> converter) { Assert.notNull(converter, "converter cannot be null"); this.converter = converter; } /** * Sets the {@link RequestCache} to use. The default is * {@link HttpSessionRequestCache}. * @param requestCache the {@link RequestCache} to use. Cannot be null */ public void setRequestCache(RequestCache requestCache) { Assert.notNull(requestCache, "requestCache cannot be null"); this.requestCache = requestCache; } @Override public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException { final SavedRequest savedRequest = this.requestCache.getRequest(request, response); final String redirectUrl = (savedRequest != null) ? savedRequest.getRedirectUrl() : request.getContextPath() + "/"; this.requestCache.removeRequest(request, response); this.converter.write(new AuthenticationSuccess(redirectUrl), MediaType.APPLICATION_JSON, new ServletServerHttpResponse(response)); }
/** * A response object used to write the JSON response for successful authentication. * * NOTE: We should be careful about writing {@link Authentication} or * {@link Authentication#getPrincipal()} to the response since it contains * credentials. */ public static final class AuthenticationSuccess { private final String redirectUrl; private AuthenticationSuccess(String redirectUrl) { this.redirectUrl = redirectUrl; } public String getRedirectUrl() { return this.redirectUrl; } public boolean isAuthenticated() { return true; } } }
repos\spring-security-main\web\src\main\java\org\springframework\security\web\authentication\HttpMessageConverterAuthenticationSuccessHandler.java
1
请完成以下Java代码
public class ProfileDatafetcher { private ProfileQueryService profileQueryService; @DgsData(parentType = USER.TYPE_NAME, field = USER.Profile) public Profile getUserProfile(DataFetchingEnvironment dataFetchingEnvironment) { User user = dataFetchingEnvironment.getLocalContext(); String username = user.getUsername(); return queryProfile(username); } @DgsData(parentType = ARTICLE.TYPE_NAME, field = ARTICLE.Author) public Profile getAuthor(DataFetchingEnvironment dataFetchingEnvironment) { Map<String, ArticleData> map = dataFetchingEnvironment.getLocalContext(); Article article = dataFetchingEnvironment.getSource(); return queryProfile(map.get(article.getSlug()).getProfileData().getUsername()); } @DgsData(parentType = COMMENT.TYPE_NAME, field = COMMENT.Author) public Profile getCommentAuthor(DataFetchingEnvironment dataFetchingEnvironment) { Comment comment = dataFetchingEnvironment.getSource(); Map<String, CommentData> map = dataFetchingEnvironment.getLocalContext(); return queryProfile(map.get(comment.getId()).getProfileData().getUsername()); } @DgsData(parentType = DgsConstants.QUERY_TYPE, field = QUERY.Profile) public ProfilePayload queryProfile(
@InputArgument("username") String username, DataFetchingEnvironment dataFetchingEnvironment) { Profile profile = queryProfile(dataFetchingEnvironment.getArgument("username")); return ProfilePayload.newBuilder().profile(profile).build(); } private Profile queryProfile(String username) { User current = SecurityUtil.getCurrentUser().orElse(null); ProfileData profileData = profileQueryService .findByUsername(username, current) .orElseThrow(ResourceNotFoundException::new); return Profile.newBuilder() .username(profileData.getUsername()) .bio(profileData.getBio()) .image(profileData.getImage()) .following(profileData.isFollowing()) .build(); } }
repos\spring-boot-realworld-example-app-master\src\main\java\io\spring\graphql\ProfileDatafetcher.java
1
请在Spring Boot框架中完成以下Java代码
private static class ProductIdAndAcctSchemaId { @NonNull ProductId productId; @NonNull AcctSchemaId acctSchemaId; } @Value(staticConstructor = "of") private static class ProductCategoryIdAndAcctSchemaId { @NonNull ProductCategoryId productCategoryId; @NonNull AcctSchemaId acctSchemaId; } @EqualsAndHashCode @ToString private static class ProductCategoryAccountsCollection { private final ImmutableMap<ProductCategoryIdAndAcctSchemaId, ProductCategoryAccounts> productCategoryAccts;
public ProductCategoryAccountsCollection(final List<ProductCategoryAccounts> productCategoryAccts) { this.productCategoryAccts = Maps.uniqueIndex( productCategoryAccts, productCategoryAcct -> ProductCategoryIdAndAcctSchemaId.of(productCategoryAcct.getProductCategoryId(), productCategoryAcct.getAcctSchemaId())); } public Optional<ProductCategoryAccounts> getBy( @NonNull final ProductCategoryId productCategoryId, @NonNull final AcctSchemaId acctSchemaId) { final ProductCategoryIdAndAcctSchemaId key = ProductCategoryIdAndAcctSchemaId.of(productCategoryId, acctSchemaId); return Optional.ofNullable(productCategoryAccts.get(key)); } } }
repos\metasfresh-new_dawn_uat\backend\de.metas.acct.base\src\main\java\de\metas\acct\api\impl\ProductAcctDAO.java
2
请完成以下Java代码
public static ExternalSystemType ofValueOrNull(@Nullable final String value) { final String valueNorm = StringUtils.trimBlankToNull(value); return valueNorm != null ? ofValue(valueNorm) : null; } @NonNull public static ExternalSystemType ofValue(@NonNull final String value) { final String valueNorm = StringUtils.trimBlankToNull(value); return interner.computeIfAbsent(valueNorm, ExternalSystemType::new); } @Nullable public static ExternalSystemType ofLegacyCodeOrNull(@NonNull final String code) { return LEGACY_CODES.inverse().get(code); } @Override public String toString() {return getValue();} @JsonValue public String toJson() {return getValue();} public boolean isAlberta() {return Alberta.equals(this);} public boolean isRabbitMQ() {return RabbitMQ.equals(this);} public boolean isWOO() {return WOO.equals(this);} public boolean isGRSSignum() {return GRSSignum.equals(this);}
public boolean isLeichUndMehl() {return LeichUndMehl.equals(this);} public boolean isPrintClient() {return PrintClient.equals(this);} public boolean isProCareManagement() {return ProCareManagement.equals(this);} public boolean isShopware6() {return Shopware6.equals(this);} public boolean isOther() {return Other.equals(this);} public boolean isGithub() {return Github.equals(this);} public boolean isEverhour() {return Everhour.equals(this);} public boolean isScriptedExportConversion() {return ScriptedExportConversion.equals(this);} public boolean isScriptedImportConversion() {return ScriptedImportConversion.equals(this);} }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\de\metas\externalsystem\ExternalSystemType.java
1
请在Spring Boot框架中完成以下Java代码
protected EventDefinition getEventDefinitionFromRequest(String eventDefinitionId) { EventDefinition eventDefinition = repositoryService.getEventDefinition(eventDefinitionId); if (eventDefinition == null) { throw new FlowableObjectNotFoundException("Could not find an event definition with id '" + eventDefinitionId + "'.", EventDefinition.class); } if (restApiInterceptor != null) { restApiInterceptor.accessEventDefinitionById(eventDefinition); } return eventDefinition; } /**
* 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.getChannelDefinition(channelDefinitionId); 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\BaseEventDefinitionResource.java
2
请完成以下Java代码
public void setOnMouseUp (String script) { addAttribute ("onmouseup", script); } /** * The onmouseover event occurs when the pointing device is moved onto an * element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseOver (String script) { addAttribute ("onmouseover", script); } /** * The onmousemove event occurs when the pointing device is moved while it * is over an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseMove (String script) { addAttribute ("onomousemove", script); } /** * The onmouseout event occurs when the pointing device is moved away from * an element. This attribute may be used with most elements. * * @param script script */ public void setOnMouseOut (String script) { addAttribute ("onmouseout", script); }
/** * The onkeypress event occurs when a key is pressed and released over an * element. This attribute may be used with most elements. * * @param script script */ public void setOnKeyPress (String script) { addAttribute ("onkeypress", script); } /** * The onkeydown event occurs when a key is pressed down over an element. * This attribute may be used with most elements. * * @param script script */ public void setOnKeyDown (String script) { addAttribute ("onkeydown", script); } /** * The onkeyup event occurs when a key is released over an element. This * attribute may be used with most elements. * * @param script script */ public void setOnKeyUp (String script) { addAttribute ("onkeyup", script); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\tools\src\main\java-legacy\org\apache\ecs\xhtml\abbr.java
1
请完成以下Java代码
public class DataScope extends BaseEntity { @Serial private static final long serialVersionUID = 1L; /** * 主键 */ @Schema(description = "主键") @TableId(value = "id", type = IdType.ASSIGN_ID) @JsonSerialize(using = ToStringSerializer.class) private Long id; /** * 菜单主键 */ @Schema(description = "菜单主键") private Long menuId; /** * 资源编号 */ @Schema(description = "资源编号") private String resourceCode; /** * 数据权限名称 */ @Schema(description = "数据权限名称") private String scopeName; /** * 数据权限可见字段 */ @Schema(description = "数据权限可见字段") private String scopeField; /** * 数据权限类名
*/ @Schema(description = "数据权限类名") private String scopeClass; /** * 数据权限字段 */ @Schema(description = "数据权限字段") private String scopeColumn; /** * 数据权限类型 */ @Schema(description = "数据权限类型") private Integer scopeType; /** * 数据权限值域 */ @Schema(description = "数据权限值域") private String scopeValue; /** * 数据权限备注 */ @Schema(description = "数据权限备注") private String remark; }
repos\SpringBlade-master\blade-service-api\blade-system-api\src\main\java\org\springblade\system\entity\DataScope.java
1
请完成以下Java代码
public int getM_Warehouse_Dest_ID() { return get_ValueAsInt(COLUMNNAME_M_Warehouse_Dest_ID); } @Override public void setPackageNetTotal (final @Nullable BigDecimal PackageNetTotal) { set_Value (COLUMNNAME_PackageNetTotal, PackageNetTotal); } @Override public BigDecimal getPackageNetTotal() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageNetTotal); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPackageWeight (final @Nullable BigDecimal PackageWeight) { set_Value (COLUMNNAME_PackageWeight, PackageWeight); } @Override public BigDecimal getPackageWeight() { final BigDecimal bd = get_ValueAsBigDecimal(COLUMNNAME_PackageWeight); return bd != null ? bd : BigDecimal.ZERO; } @Override public void setPOReference (final @Nullable java.lang.String POReference) { set_Value (COLUMNNAME_POReference, POReference); } @Override public java.lang.String getPOReference() { return get_ValueAsString(COLUMNNAME_POReference); } @Override public void setProcessed (final boolean Processed) { set_Value (COLUMNNAME_Processed, Processed); } @Override public boolean isProcessed() { return get_ValueAsBoolean(COLUMNNAME_Processed); } @Override public void setReceivedInfo (final @Nullable java.lang.String ReceivedInfo) { set_Value (COLUMNNAME_ReceivedInfo, ReceivedInfo); } @Override public java.lang.String getReceivedInfo() { return get_ValueAsString(COLUMNNAME_ReceivedInfo); }
@Override public void setShipDate (final @Nullable java.sql.Timestamp ShipDate) { set_Value (COLUMNNAME_ShipDate, ShipDate); } @Override public java.sql.Timestamp getShipDate() { return get_ValueAsTimestamp(COLUMNNAME_ShipDate); } @Override public void setTrackingInfo (final @Nullable java.lang.String TrackingInfo) { set_Value (COLUMNNAME_TrackingInfo, TrackingInfo); } @Override public java.lang.String getTrackingInfo() { return get_ValueAsString(COLUMNNAME_TrackingInfo); } @Override public void setTrackingURL (final @Nullable java.lang.String TrackingURL) { set_Value (COLUMNNAME_TrackingURL, TrackingURL); } @Override public java.lang.String getTrackingURL() { return get_ValueAsString(COLUMNNAME_TrackingURL); } @Override public void setWidthInCm (final int WidthInCm) { set_Value (COLUMNNAME_WidthInCm, WidthInCm); } @Override public int getWidthInCm() { return get_ValueAsInt(COLUMNNAME_WidthInCm); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java-gen\org\compiere\model\X_M_Package.java
1
请完成以下Java代码
protected String determineTargetUrl(final Authentication authentication) { boolean isUser = false; boolean isAdmin = false; final Collection<? extends GrantedAuthority> authorities = authentication.getAuthorities(); for (final GrantedAuthority grantedAuthority : authorities) { if (grantedAuthority.getAuthority().equals("ROLE_USER")) { isUser = true; break; } else if (grantedAuthority.getAuthority().equals("ROLE_ADMIN")) { isAdmin = true; break; } } if (isUser) { return "/homepage"; } else if (isAdmin) { return "/console"; } else { throw new IllegalStateException(); } } /** * Removes temporary authentication-related data which may have been stored in the session * during the authentication process. */ protected final void clearAuthenticationAttributes(final HttpServletRequest request) { final HttpSession session = request.getSession(false);
if (session == null) { return; } session.removeAttribute(WebAttributes.AUTHENTICATION_EXCEPTION); } public void setRedirectStrategy(final RedirectStrategy redirectStrategy) { this.redirectStrategy = redirectStrategy; } protected RedirectStrategy getRedirectStrategy() { return redirectStrategy; } }
repos\tutorials-master\spring-security-modules\spring-security-web-mvc\src\main\java\com\baeldung\security\MySimpleUrlAuthenticationSuccessHandler.java
1
请在Spring Boot框架中完成以下Java代码
private static final class ExactUrlRequestMatcher implements RequestMatcher { private String processUrl; private ExactUrlRequestMatcher(String processUrl) { this.processUrl = processUrl; } @Override public boolean matches(HttpServletRequest request) { String uri = request.getRequestURI(); String query = request.getQueryString(); if (query != null) { uri += "?" + query; } if ("".equals(request.getContextPath())) {
return uri.equals(this.processUrl); } return uri.equals(request.getContextPath() + this.processUrl); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("ExactUrl [processUrl='").append(this.processUrl).append("']"); return sb.toString(); } } }
repos\spring-security-main\config\src\main\java\org\springframework\security\config\annotation\web\configurers\PermitAllSupport.java
2
请完成以下Java代码
public boolean learn(String segmentedTaggedSentence) { Sentence sentence = Sentence.create(segmentedTaggedSentence); return learn(sentence); } /** * 在线学习 * * @param sentence 已分词、标好词性和命名实体的人民日报2014格式的句子 * @return 是否学习成果(失败的原因是句子格式不合法) */ public boolean learn(Sentence sentence) { CharTable.normalize(sentence); if (!getPerceptronSegmenter().learn(sentence)) return false; if (posTagger != null && !getPerceptronPOSTagger().learn(sentence)) return false; if (neRecognizer != null && !getPerceptionNERecognizer().learn(sentence)) return false; return true; } /** * 获取分词器 * * @return */
public PerceptronSegmenter getPerceptronSegmenter() { return (PerceptronSegmenter) segmenter; } /** * 获取词性标注器 * * @return */ public PerceptronPOSTagger getPerceptronPOSTagger() { return (PerceptronPOSTagger) posTagger; } /** * 获取命名实体识别器 * * @return */ public PerceptronNERecognizer getPerceptionNERecognizer() { return (PerceptronNERecognizer) neRecognizer; } }
repos\springboot-demo-master\hanlp\src\main\java\demo\hankcs\hanlp\model\perceptron\PerceptronLexicalAnalyzer.java
1
请完成以下Java代码
public void setTrustResolver(AuthenticationTrustResolver trustResolver) { getDefaultAuthorizationManagerFactory().setTrustResolver(trustResolver); } /** * <p> * Sets the default prefix to be added to * {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasAnyRole(String...)} * or * {@link org.springframework.security.access.expression.SecurityExpressionRoot#hasRole(String)}. * For example, if hasRole("ADMIN") or hasRole("ROLE_ADMIN") is passed in, then the * role ROLE_ADMIN will be used when the defaultRolePrefix is "ROLE_" (default). * </p> * * <p>
* If null or empty, then no default role prefix is used. * </p> * @param defaultRolePrefix the default prefix to add to roles. Default "ROLE_". * @deprecated Use * {@link #setAuthorizationManagerFactory(AuthorizationManagerFactory)} instead */ @Deprecated(since = "7.0") public void setDefaultRolePrefix(@Nullable String defaultRolePrefix) { if (defaultRolePrefix == null) { defaultRolePrefix = ""; } getDefaultAuthorizationManagerFactory().setRolePrefix(defaultRolePrefix); this.defaultRolePrefix = defaultRolePrefix; } }
repos\spring-security-main\access\src\main\java\org\springframework\security\web\access\expression\DefaultWebSecurityExpressionHandler.java
1
请在Spring Boot框架中完成以下Java代码
public class NotificationRestController { public static final String ENDPOINT = WebConfig.ENDPOINT_ROOT + "/notifications"; @Autowired private UserSession userSession; @Autowired private UserNotificationsService userNotificationsService; @GetMapping("/websocketEndpoint") public final String getWebsocketEndpoint() { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); return userNotificationsService.getWebsocketEndpoint(adUserId).getAsString(); } @GetMapping("/all") public JSONNotificationsList getNotifications( @RequestParam(name = "limit", defaultValue = "-1") final int limit // ) { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); final UserNotificationsList notifications = userNotificationsService.getNotifications(adUserId, QueryLimit.ofInt(limit)); final JSONOptions jsonOpts = JSONOptions.of(userSession); return JSONNotificationsList.of(notifications, jsonOpts); } @GetMapping("/unreadCount") public int getNotificationsUnreadCount() { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); return userNotificationsService.getNotificationsUnreadCount(adUserId); } @PutMapping("/{notificationId}/read") public void markAsRead(@PathVariable("notificationId") final String notificationId) { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); userNotificationsService.markNotificationAsRead(adUserId, notificationId); } @PutMapping("/all/read") public void markAllAsRead() { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); userNotificationsService.markAllNotificationsAsRead(adUserId); } @DeleteMapping("/{notificationId}") public void deleteById(@PathVariable("notificationId") final String notificationId) { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId();
userNotificationsService.deleteNotification(adUserId, notificationId); } @DeleteMapping public void deleteByIds(@RequestParam(name = "ids") final String notificationIdsListStr) { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); final List<String> notificationIds = Splitter.on(",") .trimResults() .omitEmptyStrings() .splitToList(notificationIdsListStr); if (notificationIds.isEmpty()) { throw new AdempiereException("No IDs provided"); } notificationIds.forEach(notificationId -> userNotificationsService.deleteNotification(adUserId, notificationId)); } @DeleteMapping("/all") public void deleteAll() { userSession.assertLoggedIn(); final UserId adUserId = userSession.getLoggedUserId(); userNotificationsService.deleteAllNotification(adUserId); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\notification\NotificationRestController.java
2
请完成以下Java代码
public class FetchAndLockContextListener implements ServletContextListener { protected static FetchAndLockHandler fetchAndLockHandler; @Override public void contextInitialized(ServletContextEvent sce) { if (fetchAndLockHandler == null) { fetchAndLockHandler = lookupFetchAndLockHandler(); fetchAndLockHandler.contextInitialized(sce); fetchAndLockHandler.start(); } } @Override public void contextDestroyed(ServletContextEvent sce) { fetchAndLockHandler.shutdown(); }
public static FetchAndLockHandler getFetchAndLockHandler() { return fetchAndLockHandler; } protected FetchAndLockHandler lookupFetchAndLockHandler() { ServiceLoader<FetchAndLockHandler> serviceLoader = ServiceLoader.load(FetchAndLockHandler.class); Iterator<FetchAndLockHandler> iterator = serviceLoader.iterator(); if(iterator.hasNext()) { return iterator.next(); } else { throw new RestException(Response.Status.INTERNAL_SERVER_ERROR, "Could not find an implementation of the " + FetchAndLockHandler.class.getSimpleName() + "- SPI"); } } }
repos\camunda-bpm-platform-master\engine-rest\engine-rest\src\main\java\org\camunda\bpm\engine\rest\impl\FetchAndLockContextListener.java
1
请在Spring Boot框架中完成以下Java代码
public String getClassDiscriminator() { return this.classDiscriminator; } public void setClassDiscriminator(String classDiscriminator) { this.classDiscriminator = classDiscriminator; } public ClassDiscriminatorMode getClassDiscriminatorMode() { return this.classDiscriminatorMode; } public void setClassDiscriminatorMode(ClassDiscriminatorMode classDiscriminatorMode) { this.classDiscriminatorMode = classDiscriminatorMode; } public boolean isDecodeEnumsCaseInsensitive() { return this.decodeEnumsCaseInsensitive; } public void setDecodeEnumsCaseInsensitive(boolean decodeEnumsCaseInsensitive) { this.decodeEnumsCaseInsensitive = decodeEnumsCaseInsensitive; } public boolean isUseAlternativeNames() { return this.useAlternativeNames; } public void setUseAlternativeNames(boolean useAlternativeNames) { this.useAlternativeNames = useAlternativeNames; } public boolean isAllowTrailingComma() { return this.allowTrailingComma; } public void setAllowTrailingComma(boolean allowTrailingComma) { this.allowTrailingComma = allowTrailingComma; } public boolean isAllowComments() { return this.allowComments;
} public void setAllowComments(boolean allowComments) { this.allowComments = allowComments; } /** * Enum representing strategies for JSON property naming. The values correspond to * {@link kotlinx.serialization.json.JsonNamingStrategy} implementations that cannot * be directly referenced. */ public enum JsonNamingStrategy { /** * Snake case strategy. */ SNAKE_CASE, /** * Kebab case strategy. */ KEBAB_CASE } }
repos\spring-boot-4.0.1\module\spring-boot-kotlinx-serialization-json\src\main\java\org\springframework\boot\kotlinx\serialization\json\autoconfigure\KotlinxSerializationJsonProperties.java
2
请完成以下Java代码
public static LocatorQRCode ofLocator(@NonNull final I_M_Locator locator) { return builder() .locatorId(LocatorId.ofRepoId(locator.getM_Warehouse_ID(), locator.getM_Locator_ID())) .caption(locator.getValue()) .build(); } public PrintableQRCode toPrintableQRCode() { return PrintableQRCode.builder() .qrCode(toGlobalQRCodeJsonString()) .bottomText(caption) .build(); }
public GlobalQRCode toGlobalQRCode() { return LocatorQRCodeJsonConverter.toGlobalQRCode(this); } public ScannedCode toScannedCode() { return ScannedCode.ofString(toGlobalQRCodeJsonString()); } public static boolean isTypeMatching(@NonNull final GlobalQRCode globalQRCode) { return LocatorQRCodeJsonConverter.isTypeMatching(globalQRCode); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.adempiere.adempiere\base\src\main\java\org\adempiere\warehouse\qrcode\LocatorQRCode.java
1
请完成以下Java代码
protected org.compiere.model.POInfo initPO (Properties ctx) { org.compiere.model.POInfo poi = org.compiere.model.POInfo.getPOInfo (ctx, Table_Name, get_TrxName()); return poi; } /** Set Beschreibung. @param Description Beschreibung */ @Override public void setDescription (java.lang.String Description) { set_Value (COLUMNNAME_Description, Description); } /** Get Beschreibung. @return Beschreibung */ @Override public java.lang.String getDescription () { return (java.lang.String)get_Value(COLUMNNAME_Description); } /** Set Los-Nr.. @param Lot Los-Nummer (alphanumerisch) */ @Override public void setLot (java.lang.String Lot) { set_Value (COLUMNNAME_Lot, Lot); } /** Get Los-Nr.. @return Los-Nummer (alphanumerisch) */ @Override public java.lang.String getLot () { return (java.lang.String)get_Value(COLUMNNAME_Lot); } @Override public org.compiere.model.I_M_Product getM_Product() throws RuntimeException { return get_ValueAsPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class); } @Override public void setM_Product(org.compiere.model.I_M_Product M_Product) { set_ValueFromPO(COLUMNNAME_M_Product_ID, org.compiere.model.I_M_Product.class, M_Product); }
/** Set Produkt. @param M_Product_ID Produkt, Leistung, Artikel */ @Override public void setM_Product_ID (int M_Product_ID) { if (M_Product_ID < 1) set_Value (COLUMNNAME_M_Product_ID, null); else set_Value (COLUMNNAME_M_Product_ID, Integer.valueOf(M_Product_ID)); } /** Get Produkt. @return Produkt, Leistung, Artikel */ @Override public int getM_Product_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_ID); if (ii == null) return 0; return ii.intValue(); } /** Set M_Product_LotNumber_Quarantine. @param M_Product_LotNumber_Quarantine_ID M_Product_LotNumber_Quarantine */ @Override public void setM_Product_LotNumber_Quarantine_ID (int M_Product_LotNumber_Quarantine_ID) { if (M_Product_LotNumber_Quarantine_ID < 1) set_ValueNoCheck (COLUMNNAME_M_Product_LotNumber_Quarantine_ID, null); else set_ValueNoCheck (COLUMNNAME_M_Product_LotNumber_Quarantine_ID, Integer.valueOf(M_Product_LotNumber_Quarantine_ID)); } /** Get M_Product_LotNumber_Quarantine. @return M_Product_LotNumber_Quarantine */ @Override public int getM_Product_LotNumber_Quarantine_ID () { Integer ii = (Integer)get_Value(COLUMNNAME_M_Product_LotNumber_Quarantine_ID); if (ii == null) return 0; return ii.intValue(); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.swat\de.metas.swat.base\src\main\java-gen\de\metas\product\model\X_M_Product_LotNumber_Quarantine.java
1
请完成以下Java代码
public String getErrorCode() { return errorCode; } public void setErrorCode(String errorCode) { this.errorCode = errorCode; } public String getHandlerActivityId() { return handlerActivityId; } public Integer getPrecedence() { // handlers with error code take precedence over catchall-handlers return precedence + (errorCode != null ? 1 : 0); } public void setPrecedence(Integer precedence) { this.precedence = precedence; } public boolean catchesError(String errorCode) { return this.errorCode == null || this.errorCode.equals(errorCode); } public boolean catchesException(Exception ex) { if(this.errorCode == null) { return false; } else { // unbox exception while ((ex instanceof ProcessEngineException || ex instanceof ScriptException) && ex.getCause() != null) { ex = (Exception) ex.getCause(); } // check exception hierarchy Class<?> exceptionClass = ex.getClass();
do { if(this.errorCode.equals(exceptionClass.getName())) { return true; } exceptionClass = exceptionClass.getSuperclass(); } while(exceptionClass != null); return false; } } public void setErrorCodeVariable(String errorCodeVariable) { this.errorCodeVariable = errorCodeVariable; } public String getErrorCodeVariable() { return errorCodeVariable; } public void setErrorMessageVariable(String errorMessageVariable) { this.errorMessageVariable = errorMessageVariable; } public String getErrorMessageVariable() { return errorMessageVariable; } }
repos\camunda-bpm-platform-master\engine\src\main\java\org\camunda\bpm\engine\impl\bpmn\parser\ErrorEventDefinition.java
1
请完成以下Java代码
public DocumentFilterList mergeWithNullable(@Nullable final DocumentFilter filter) { return filter != null ? mergeWith(filter) : this; } public Optional<DocumentFilter> getFilterById(@NonNull final String filterId) { final DocumentFilter filter = getFilterByIdOrNull(filterId); return Optional.ofNullable(filter); } private DocumentFilter getFilterByIdOrNull(@NonNull final String filterId) { return filtersById.get(filterId); } public void forEach(@NonNull final Consumer<DocumentFilter> consumer) { filtersById.values().forEach(consumer); } @Nullable public String getParamValueAsString(final String filterId, final String parameterName) { final DocumentFilter filter = getFilterByIdOrNull(filterId); if (filter == null) { return null; } return filter.getParameterValueAsString(parameterName); } public int getParamValueAsInt(final String filterId, final String parameterName, final int defaultValue) { final DocumentFilter filter = getFilterByIdOrNull(filterId);
if (filter == null) { return defaultValue; } return filter.getParameterValueAsInt(parameterName, defaultValue); } public boolean getParamValueAsBoolean(final String filterId, final String parameterName, final boolean defaultValue) { final DocumentFilter filter = getFilterByIdOrNull(filterId); if (filter == null) { return defaultValue; } return filter.getParameterValueAsBoolean(parameterName, defaultValue); } }
repos\metasfresh-new_dawn_uat\backend\de.metas.ui.web.base\src\main\java\de\metas\ui\web\document\filter\DocumentFilterList.java
1